HeadlinesBriefing HeadlinesBriefing.com

Rust struct lifetime bypass via covariant assignment

Hacker News •
×

A Hacker News report describes a soundness bug in Rust in which a struct's lifetime requirements can be bypassed through covariant field assignment. The reporter shares a small program that uses a wrapper type, Q<T>, holding an Option<T> with a Drop implementation. The Drop impl moves the contained value into a static Mutex<Vec<Box<dyn Any + Send>>>, which should be impossible for a borrowed value that does not live for 'static.

In the example, a local String is assigned by reference into the wrapper inside an inner scope, so the borrow should end when that scope closes. Because the wrapper's field is covariant, the compiler accepts the assignment, and the reference can then be stored beyond the lifetime of the local. The program compiles and prints unrelated memory contents instead of being rejected.

When run under AddressSanitizer, the program crashes with a stack-use-after-scope error, confirming that the dangling reference is actually dereferenced. The issue is reproducible on current nightly builds and on stable releases back to at least 1.85.0, according to the report. Links to Compiler Explorer examples with and without sanitizers accompany the post.

The finding points to a soundness hole in how variance interacts with Drop-based storage, and it is the kind of issue that Rust maintainers treat as a high priority because safe code should never produce undefined behavior.

Source: Hacker News · Summarized by HeadlinesBriefing