rust-lang/rust

String::retain allows safely creating invalid (non-utf8) strings when abusing panic

SkiFire13 opened this issue · 1 comments

While String::retain executes it may temporarily leave the String in an inconsistent state, in particular it may contain invalid utf8. This is safe because it restores this invariant before returning, but the caller may skip this by panicing inside the closure and catching the unwind it outside. This allows to create Strings that are not utf8, breaking the library invariant without using unsafe.

For example the following will panic at the final assertion, while I would expect it to never fail when s has type String:

let mut s = "0è0".to_string();
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
    let mut count = 0;
    s.retain(|_| {
        count += 1;
        match count {
            1 => false,
            2 => true,
            _ => panic!(),
        }
    });
}));
assert!(std::str::from_utf8(s.as_bytes()).is_ok()); // This will fail

Assigning P-high and removing I-prioritize as discussed in the prioritization working group.