
Following Rust issue #164250 to understand how covariance and field assignment could bypass lifetime requirements.
I use Rust mainly because of how much the type system rules out at compile time. So when I came across this issue on the Rust tracker, I wanted to understand it properly, and maybe learn stuff that would make me a better a "low level dev"
The title is "struct's lifetime requirements can be bypassed via covariant field assignment."(Holy buzzwords) In short, it's a soundness bug, basically safe rust (so rust that isnt in a unsafe{} block can generate code that shows a "use after scope" condition . Kinda crazy but a good issue i thought to start learning a little bout how compilers work and how rust offers memory safety a garbage collector.
This "blog" is supposed to go through it in layers: the code, what it does at runtime, the background you need (variance and how the borrow checker works), and then why the compiler lets it through.
This is the example from the issue:
use std::sync::Mutex;
static KEPT: Mutex<Vec<Box<dyn std::any::Any + Send>>> =
Mutex::new(Vec::new());
struct Q<T: 'static + Send>(Option<T>);
impl<T: 'static + Send> Drop for Q<T> {
fn drop(&mut self) {
if let Some(t) = self.0.take() {
KEPT.lock().unwrap().push(Box::new(t));
}
}
}
fn main() {
{
let l = String::from("hello world, this is long enough");
let mut q = Q(None);
q.0 = Some(&l);
}
let _z = String::from("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
let k = KEPT.lock().unwrap();
println!(
"{}",
k[0].downcast_ref::<&'static String>().unwrap()
);
}On compilers from as old as Rust 1.18.0 (which is from 2017) this builds and prints the X string. Under AddressSanitizer it reports stack-use-after-scope. The exact output is incidental, since the behaviour is undefined, but it shows the program reading memory that was freed and reused.
The interesting lines are these two:
let mut q = Q(None);
q.0 = Some(&l);Q is declared with a 'static bound on T, meaning T can't contain a borrow that ends before the program does. The reference to l borrows a local variable, so it can't satisfy that bound, and the assignment should be rejected. The compiler accepts it.
The Drop impl is what turns this into a memory-safety problem. It takes the value out of the Option and moves it into KEPT, a global that outlives every scope. That's safe rust as long as the 'static bound actually holds(subtle forshadowing ahh), and the destructor is written on that assumption. With the bound bypassed, it stores a reference to a local into global state. Its all makes sense till now, like nothing is wrong in this code
At the end of the inner block, locals drop in reverse declaration order, so q goes before l. The destructor of q moves the reference to l into KEPT, and then the allocation of l is freed. KEPT is now holding a dangling reference. When _z is allocated, it lands in the freed memory, and reading through the stale reference returns its contents.
So the runtime is very simple.. The "soudness error" is why does the compiler accept it , and answering that needs one to know 2 main things about rust
Lifetimes participate in subtyping. If say A lifetime outlives B, then a reference with the longer lifetime is a subtype of one with the shorter lifetime(here both A and B are references to a var), and Rust lets you use the subtype wherever the supertype is expected:
fn print_it(s: &str) { println!("{s}"); }
fn main() {
let owned = String::from("hi");
let long_lived: &'static str = "static string";
// a 'static reference can be used where a shorter-lived one is expected
print_it(long_lived);
print_it(&owned);
}This is called covariance: the direction of the subtyping on the inner lifetime matches the direction on the outer type. A shared reference is covariant in its lifetime. A struct is covariant in a parameter when that parameter only appears in covariant positions, so Option<T> is covariant in T, and so is Q here, since its only field is an Option<T>.
This is straight from the Rust "Subtyping and variance" section so refer that for more info.
The main thing is that it only goes one way. Shortening a lifetime is always safe, because you're basically saying that "as this will always be there so I'll use another reference to this which will live for a shorter time". Lengthening one is never safe, because you'd be promising a borrow lasts longer than it does. Covariance can turn a 'static reference into a short-lived one. It can't turn a short-lived reference into a 'static one.
(For contrast, a mutable reference is invariant in the type it points to. That's what stops you from shortening the lifetime inside a mutable reference and then writing a short-lived value through it.)
None of this is inherntly wrong. It's what makes a function taking a string slice accept both literals and borrowed Strings. But it matters here for a diff reason. The thing is that covariance can shorten the lifetime inside a type, but doing so here produces a Q whose type no longer satisfies its declared 'static bound. The compiler should reject that type, but the bug allows it to go unchecked.
Rust's borrow checker works on MIR, which is an intermediate representation of your code that the compiler uses to check things like lifetimes and borrowing.
The basic idea is that the compiler checks how references are used, figures out how long they need to remain valid, and makes sure the data they point to isn't dropped too early.
The problem is that these checks rely on the compiler generating the right constraints in the first place. If a type has a lifetime requirement that the compiler never checks, the borrow checker can do its job correctly and still miss the problem. That's essentially what happens here.
A simplified picture of the MIR for the inner block (illustrative, not literal compiler output; you can dump the real thing with -Zdump-mir on nightly):
_1 = String::from(...) // l
_3 = Option::<&'? String>::None
_2 = Q::<&'? String>(move _3) // q
_5 = &_1 // &l
_4 = Option::<&'? String>::Some(move _5)
(_2.0) = move _4 // q.0 = Some(&l)
drop(_2) // q dropped first
drop(_1) // then lThe '? in the code represents a lifetime that the compiler hasn't resolved yet. The borrow checker has to figure out how long that reference needs to remain valid.
Here's how I understand the types flowing through those statements, based on the issue and the fix PR. I haven't traced it through the compiler source myself, so treat this as my reading of the discussion.
There are two different region variables involved, and it helps to name them:
Step 1: the constructor call. Calling the constructor carries the struct's bounds as obligations, so the compiler requires T: 'static. With T as a reference with region 'c, that produces the constraint that 'c outlives 'static. Fine. The call produces a legitimate, well-formed value of type Q<&'static String>.
Step 2: assigning it to the local. The result is stored in q, whose type is Q<&'q String>. This is a subtyping check, and because Q is covariant in T, it only needs 'c to outlive 'q. That's satisfied by 'c = 'static. So the compiler shortens Q<&'static String> to Q<&'q String>, which is exactly what covariance is for.
Step 3: the field assignment. Writing Some(&l) into the field puts an Option<&'r String> into a slot of type Option<&'q String>, which needs 'r to outlive 'q. The loan on l has to cover 'q, and no more.
What's missing. Q<&'q String> is a type that requires 'q to outlive 'static to be well-formed, because Q declares the bound on T. Nothing ever asked for that. The type of the constructor call was checked for well-formedness, but the type of the local was only related to it via subtyping. Locals whose types were inferred this way never got their own well-formedness check. So 'q stays an unconstrained region that happens to be short, while the value inside gets treated as 'static by every piece of code that trusts the bound on Q.
This is also why the title says covariant. Covariance is the step that turns a valid Q<&'static String> into an invalid-but-unchecked Q<&'q String>. It isn't that covariance is unsound. It's that the compiler used it to produce a type it never verified.
Now the loan check. Since q has a Drop impl, drop(_2) counts as a use of 'q, which means 'q must be live at that point. The loan on l must therefore stay valid until drop(_2). And it does, because l is dropped after q. From the borrow checker's perspective, l outlives every use of the reference, so there's no error.
One must wonder why the exploit needs a destructor at all. If the type system believes Q<&'q String> is fine, why can't ordinary code abuse it?
Because ordinary code gets re-checked. Anything you write that touches q.0 is type-checked against the real, short region 'q. If you try to move the reference somewhere that needs it to be 'static, you generate a constraint that 'q outlives 'static, and the borrow checker rejects it. The false belief isn't visible to code that's checked at the use site.
The Drop impl is different. It was type-checked once, generically, under the assumption that T is 'static, and then it runs on whatever T the drop glue is instantiated with. Nobody re-proves that assumption for the specific T at the point where drop(_2) happens, because Rust assumes the type being dropped is already well-formed. That assumption is the one the bug violates. Explicit method calls in an impl with a 'static bound would re-register the bound at the call site and get caught. The implicit drop doesn't.
That also explains the "malicious Drop impl" caveat. Without code that was compiled trusting the bound, a short-lived value in a mistyped field does nothing harmful on its own.
The issue includes a second example that uses a lifetime relationship instead:
struct MyType<'a, 'b: 'a, 'c>(
&'c mut &'a str,
&'b str,
);
impl<'a, 'b: 'a, 'c> Drop for MyType<'a, 'b, 'c> {
fn drop(&mut self) {
*self.0 = self.1;
}
}
fn main() {
let mut me_out = "rarw";
{
let l = String::from("some cool string");
let mut q = MyType(&mut me_out, "");
q.1 = &l;
}
println!("me_out: {me_out}");
}The bound that 'b outlives 'a guarantees that the second field outlives whatever the first field points to, and drop relies on that when it writes the second field through the first. The same pattern applies: the constructor call is well-formed with a long-lived string literal in the second field, the covariant shortening of 'b produces a local whose type no longer satisfies the bound, and nothing checks it. The assignment to the second field then puts a short-lived borrow in, and the destructor copies it out into me_out, which outlives l.
The takeaway is that any lifetime requirement a Drop impl depends on is exposed, not just 'static.
PR #164277 adds a well-formedness check for MIR local types. In terms of section 6, it makes the compiler ask the missing question: for the local q of type Q<&'q String>, does the bound on T hold? That generates the constraint that 'q outlives 'static. Combined with the loan on l needing to cover 'q, the borrow checker now has an impossible requirement (l can't live forever), and it reports that l does not live long enough, which is the error the original program should always have produced.
It doesn't touch covariance or restrict valid field assignments. It only closes the gap where a type could exist in a local without anyone checking that it was well-formed. When I wrote this, the PR was still open, so it hadn't shipped. (who knows if it is gonna be mergerd or nah)
The main takeaway here is that Drop relies on the guarantees provided by the type system. In this case, it assumes that T: 'static actually holds, and the compiler is supposed to make sure of that. But because of a missing check, a type that violates this requirement slips through, and the destructor ends up doing something it was never supposed to be able to do.
What's interesting is that covariance itself isn't the problem. The compiler simply fails to check whether the resulting type still satisfies its requirements. And that's what makes this bug important: even if the type system is designed to prevent these kinds of errors, those guarantees only work if the compiler enforces them consistently.
I made sum for this, here are they typeshi