Skip to content

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

Closed
@SkiFire13

Description

@SkiFire13

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-highHigh priorityT-libsRelevant to the library team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions