
Reproduce Rust Borrow Checker Unsoundness in Covariant Fields
Rust issue #164250 describes a borrow-checker soundness bug: assigning a short-lived reference to a covariant field can bypass a lifetime requirement associated with a type’s Drop implementation. The reported program stores that reference in a global Any + Send collection during destruction, then reads it after the referent has gone out of scope. Do not use this pattern to retain borrowed values. Make the type’s lifetime constraints explicit, avoid retention in Drop, and verify compiler behavior against the issue before relying on a workaround.
Environment & baseline specs
The report says the reproducer compiled on nightly and stable versions at least as far back as Rust 1.85.0. That is historical issue context, not a guarantee about every compiler release. The language baseline for this analysis is Rust 1.85+ (Edition 2021); check the current status and test the exact compiler version you ship.
No third-party crates are needed. The reproducer uses only std. For sanitizer experiments, use a nightly toolchain and a target/toolchain combination that supports AddressSanitizer.
# Cargo.toml
[package]
name = "covariant-drop-repro"
version = "0.1.0"
edition = "2021"
[dependencies]
The relevant boundary is between a covariant reference type such as &'a String and a destructor whose implementation is only available for 'static types. The danger is not ordinary borrowing by itself; it is that the compiler accepts a lifetime transition that lets destruction preserve a reference beyond its valid scope.
The reported reproducer
This is the essential mechanism from the issue:
use std::sync::Mutex;
static KEPT: Mutex<Vec<Box<dyn std::any::Any + Send>>> =
Mutex::new(Vec::new());
struct Q<T>(Option<T>);
impl<T: 'static + Send> Drop for Q<T> {
fn drop(&mut self) {
if let Some(value) = self.0.take() {
KEPT.lock().unwrap().push(Box::new(value));
}
}
}
fn main() {
{
let local = String::from("hello world, this is long enough");
let mut q = Q(None);
q.0 = Some(&local);
}
let replacement = String::from("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
let kept = KEPT.lock().unwrap();
println!(
"{}",
kept[0]
.downcast_ref::<&'static String>()
.unwrap()
);
// Keep the binding visibly used and alive through the read.
drop(replacement);
}
The original report observed compilation and output that appeared to contain the replacement string; with AddressSanitizer, it reported stack-use-after-scope. Exact output is not a correctness guarantee: reading through the expired reference is undefined behavior, so results can vary with optimization, compiler, platform, and instrumentation. Do not run this as a test that expects a particular string.
The subtlety is that Q<T> itself does not declare T: 'static. Its Drop implementation does. &String is covariant in its lifetime, so a reference with a shorter lifetime can generally be used where a longer lifetime is expected when the surrounding type permits that coercion. The reported bug involves assignment to the covariant field while the destructor’s lifetime requirements should prevent the short-lived value from escaping. The compiler accepts the program, and Drop moves the reference into a global container typed to retain only 'static values.
The Any downcast does not make the reference safe. It merely asks the global container for the type the program claims is present. Once the referent has died, accessing it is invalid regardless of whether a downcast succeeds.
Why the pattern is dangerous
A destructor runs when its value is dropped, including on ordinary scope exit. Here, Q::drop takes the field and stores it in KEPT, extending the reference’s storage but not the lifetime of the String it points to. The global vector can outlive the local String, so the retained reference becomes dangling.
The essential security lesson is not “never use covariance.” Covariance is a normal and useful property of references. The problem is relying on a compiler-enforced lifetime invariant that the reported assignment path bypasses, then using Drop as an escape hatch for borrowed data.
This differs from an ordinary panic-at-the-boundary problem: no panic is needed for the lifetime escape. For robust failure handling in code that runs destructors during unwinding, see Preventing Panic-Induced Denial of Service in Rust: Designing Resilient Error Boundaries. For a separate class of attacker-controlled worst-case behavior, see Preventing Algorithmic Complexity Attacks in Rust: Defending Data Structures and Parsers from Worst-Case Inputs.
Production design: make retention explicit and owned
The safest design is to avoid retaining arbitrary T from Drop. Require 'static at the API that stores a value, and make retention an explicit consuming operation. The wrapper below does not implement Drop, so it cannot silently publish its field as the value is destroyed.
use std::any::Any;
use std::sync::{Mutex, OnceLock};
static KEPT: OnceLock<Mutex<Vec<Box<dyn Any + Send>>>> = OnceLock::new();
fn kept() -> &'static Mutex<Vec<Box<dyn Any + Send>>> {
KEPT.get_or_init(|| Mutex::new(Vec::new()))
}
struct Holder<T>(Option<T>);
impl<T> Holder<T> {
fn new(value: Option<T>) -> Self {
Self(value)
}
fn retain(self)
where
T: 'static + Send,
{
if let Some(value) = self.0 {
kept()
.lock()
.expect("retention lock poisoned")
.push(Box::new(value));
}
}
}
fn main() {
let owned = String::from("owned and safe to retain");
Holder::new(Some(owned)).retain();
let guard = kept().lock().expect("retention lock poisoned");
assert_eq!(
guard[0].downcast_ref::<String>().map(String::as_str),
Some("owned and safe to retain")
);
}
The constraint is attached to retain, which consumes the wrapper and accepts only values satisfying T: 'static + Send. A borrowed &String cannot satisfy 'static, so safe callers cannot retain a reference to a local string through this method. For designs where the wrapper itself must always contain only retainable values, put the bound on the type declaration too:
struct Retainable<T: 'static + Send>(Option<T>);
That makes invalid instantiations harder to express, but it also narrows the type’s use. Choose the constraint that matches the API: method-level bounds allow temporary borrowed values while they remain local; a type-level bound enforces the restriction everywhere.
Do not “fix” this by changing the global container’s downcast type, adding a runtime check after the reference has escaped, or assuming the borrow checker will reject every equivalent shape. Those changes do not restore the referent’s lifetime. Also avoid treating PhantomData variance tweaks as a universal patch: variance and drop-check behavior are subtle, and an ad hoc marker should not replace an ownership-based API.
Reproduction and verification
Keep a minimal reproduction separate from production code. Record the compiler version and target, and test the exact assignment-and-drop shape; small changes to generic bounds or field types can change type inference and diagnostics.
rustc +stable --version --verbose
cargo +stable check
For a sanitizer run, use a supported nightly target and follow the Rust sanitizer documentation for its target-specific configuration. The reported ASan symptom is useful evidence of an invalid access, but the absence of a sanitizer report does not establish soundness: sanitizers detect only some executions and memory errors.
Use Miri for executable checks of your own code, but interpret the result carefully. Miri can catch many forms of undefined behavior in a particular run; it is not a proof that a borrow-checker soundness issue is absent.
cargo +nightly miri test
cargo clippy --all-targets --all-features -- -D warnings
For a regression test of the production API, verify at compile time that borrowed values cannot be retained. A trybuild compile-fail test is useful for this, but it tests your API’s rejection behavior—not whether the compiler has fixed the original issue. If the reproducer’s acceptance changes between toolchains, preserve the compiler version and diagnostic with the test report, and consult the upstream issue for current status.
Quantitative trade-offs
These figures describe structural costs, not benchmark timings. The global Mutex and Vec are shared, so contention and allocation costs depend on workload and allocator behavior.
| Approach | Retained data | Per-retain allocation | Synchronization | Lifetime guarantee |
|---|---|---|---|---|
Drop moves T into global Any store | Potentially borrowed reference | Usually one Box allocation, plus vector growth as needed | Global mutex | Unsound in the reported pattern |
Explicit consuming retain with T: 'static + Send | Only values meeting the bound | Usually one Box allocation, plus vector growth as needed | Global mutex | Rejects short-lived borrows through the safe API |
| Keep data local; do not retain | No global copy | None for retention | None | Borrow remains scoped to its owner |
The explicit method does not eliminate the allocation or lock. Its benefit is that the lifetime requirement is visible at the operation that crosses the storage boundary, rather than being hidden in a destructor.
Production pitfalls and edge cases
'staticdoes not mean “lives forever at runtime.” An ownedStringis'staticbecause its type contains no non-static borrow; it can still be dropped normally. The bound prevents retaining a value that carries a shorter lifetime.Sendis not a lifetime guarantee. It permits transfer between threads; it does not make a borrowed value live longer.Dropchanges API behavior. A destructor that publishes, leaks, or transfers data makes ordinary scope exit a security-relevant operation. Prefer an explicit method with visible bounds and error handling.- Avoid relying on observed output. Undefined behavior can appear to print plausible data, crash, or remain unnoticed. A successful local run does not establish safety.
- Do not assume a compiler version from an old report. Check upstream status and test supported toolchains. Even after a compiler fix, keeping the ownership boundary explicit is sound design.
- Review adjacent escape paths. Check callbacks, global registries, thread-local storage, trait objects, and type erasure for places where references can be retained beyond their owner.
Frequently Asked Questions (FAQ)
Does this Rust bug mean ordinary references are unsafe?
No. Rust references remain safe to use under the language’s borrowing rules. The issue concerns a specific compiler-accepted interaction between covariance, field assignment, and destructor lifetime requirements.
Can AddressSanitizer prove that this reproducer is fixed?
No. AddressSanitizer can detect some invalid memory accesses in executions it observes, but it cannot prove soundness. Use it as a diagnostic alongside compiler-version checks, API-level compile-fail tests, and upstream issue tracking.
Is adding 'static to the Drop implementation enough to prevent the bug?
The reported pattern already places 'static on the Drop implementation, yet the issue describes the program compiling. Put constraints on the type or on an explicit operation that retains the value, and avoid using Drop to move borrowed data into longer-lived storage.