In Rust, why is a stack vector's `extend_from_slice` unsound if it raises `len` before cloning each item into `MaybeUninit` slots, and how do you fix it?
answer
- caller code can unwind
- Clone is not yours
- Drop runs during unwinding
- claim the slot after writing
basics
~20 sT::clone may panic. If len already counts unwritten slots, unwinding drops the vector and Drop calls assume_init_drop on uninitialised memory. Raise len only after each write, or use a guard, so every state a panic can leave is safe.
solid answer
~40 sUnsafe code that calls code it does not control, such as `Clone`, `Ord`, a closure or an iterator, must assume that code can panic. The Rustonomicon calls the requirement **minimal exception safety**: whatever state a panic leaves must not allow undefined behaviour. In the buggy `extend_from_slice`, `self.len += items.len()` runs first; if the second `clone` panics, the vector is dropped during unwinding with `len == 3`, and `Drop` runs `assume_init_drop` on two slots that were never written. Miri reports reading uninitialised memory. The fix is to update `len` by one right after each `write`, which also drops the items already cloned. Setting `len` once after the loop is also sound, but it leaks those items. A drop guard does the same job when the loop must hold a broken invariant.
code
rust · 37 linesuse std::mem::MaybeUninit;
pub struct StackVec<T, const N: usize> {
buf: [MaybeUninit<T>; N],
len: usize, // invariant: buf[..len] is initialised
}
impl<T: Clone, const N: usize> StackVec<T, N> {
pub fn extend_from_slice(&mut self, items: &[T]) {
assert!(items.len() <= N - self.len, "capacity exceeded");
let start = self.len;
self.len += items.len(); // BUG: claims slots before they are written
for (i, item) in items.iter().enumerate() {
self.buf[start + i].write(item.clone()); // clone may panic
}
}
}
impl<T, const N: usize> Drop for StackVec<T, N> {
fn drop(&mut self) {
// SAFETY: trusts the invariant that buf[..len] is initialised.
self.buf[..self.len].iter_mut().for_each(|s| unsafe { s.assume_init_drop() });
}
}
struct Bomb(String);
impl Clone for Bomb {
fn clone(&self) -> Self {
if self.0 == "boom" { panic!("clone failed") } else { Bomb(self.0.clone()) }
}
}
fn main() {
let items = [Bomb("a".into()), Bomb("boom".into()), Bomb("c".into())];
let mut v: StackVec<Bomb, 4> = StackVec { buf: [const { MaybeUninit::uninit() }; 4], len: 0 };
v.extend_from_slice(&items); // panics; unwinding drops v with len == 3
}go deeper
Recall that a panic normally unwinds and runs Drop for every live value on the way out, including half-updated containers.
Explain how a panic in caller code such as Clone leaves a container's invariant broken, and how the order of writing a slot and raising len decides whether Drop is safe.
Name minimal exception safety, compare the per-write, after-loop and drop-guard fixes with their trade-offs, and show a test that injects a panicking Clone under Miri.
Make panic safety a review item for every unsafe module that calls generic code, and reject panic = abort as a library-level excuse, since dependencies cannot set the profile.
## Every call into caller code may unwind A **panic** in Rust usually **unwinds**: it walks up the stack, running `Drop` for every live value, until a thread boundary or `std::panic::catch_unwind` stops it (the material on panics covers the mechanism). For unsafe code this means one thing: any call to code you do not control can leave your function early, halfway through an update. The Rustonomicon lists the usual sources: unwrapping a `None`, an out-of-bounds index, division by zero, and arithmetic overflow in debug builds. In generic containers the biggest source is **caller-supplied code**: `T::clone`, `Ord::cmp`, `Hash::hash`, `Iterator::next`, closures and even `T`'s own `Drop`. ## The bug A fixed-capacity stack vector stores `[MaybeUninit<T>; N]` and keeps the invariant "`buf[..len]` is initialised". Its `Drop` relies on that invariant and calls `assume_init_drop` on the first `len` slots. Now look at this `extend_from_slice`: ```rust let start = self.len; self.len += items.len(); // claims every slot up front for (i, item) in items.iter().enumerate() { self.buf[start + i].write(item.clone()); // clone may panic } ``` If the second `clone` panics, the function exits with `len` counting slots that hold nothing. Unwinding then drops the vector, and `Drop` treats garbage as `T` values. With `T` holding a `String`, the native run in the example aborted with exit status 134, and Miri reported "Undefined Behavior: reading memory ... but memory is uninitialized". Nothing here is exotic: a perfectly safe `Clone` impl that panics turns a safe-looking API into one where safe code reaches UB. That makes the method unsound. ## Minimal and maximal exception safety The Rustonomicon names two levels: - **Minimal exception safety**, required of unsafe code: a panic must never leave a state that allows memory unsafety. - **Maximal exception safety**, desirable in safe code: a panic leaves the program doing the right thing. A state witnessed by a panic need not be coherent, only safe. The Rustonomicon's second example shows the other classic failure: a `sift_up` that copies an element out of a heap holds two bitwise copies of one value, and a panic in the user's comparison would then drop that value twice. Leaking values is safe, since `mem::forget` is a safe function; reading uninitialised memory or dropping a value twice is not. ## Three fixes 1. **Claim each slot after it is written.** This keeps the invariant true at every point, and items already cloned are dropped normally if a later clone panics: ```rust for item in items { let value = item.clone(); // may panic: len covers only written slots self.buf[self.len].write(value); self.len += 1; } ``` 2. **Set `len` once, after the loop.** This is also sound: a panic leaves `len` at its old value, so the clones already written are leaked but never misused. It gives up dropping them in exchange for one store. 3. **Use a drop guard** when the loop must temporarily break the invariant, for example to avoid a store per iteration in a hot path. A small struct holds `&mut len` and the local count, and its `Drop` writes the count back. It runs whether the loop finishes or unwinds. std's `Vec` uses an internal `SetLenOnDrop` helper, and `BinaryHeap::sift_up` uses a `Hole` guard that refills the gap on unwind. | Fix | After a panic | Cost | |---|---|---| | `len += 1` per write | Written items dropped, invariant intact | One store per item | | `len` set after the loop | Written items leaked, invariant intact | Leaks on panic | | Drop guard | Same as per-write, written back once | A helper type | | Bump `len` first (the bug) | `Drop` reads uninitialised slots | Unsound | ## What to look for in review - Find every point where unsafe code **calls caller-supplied code**, and ask what state is visible if that call panics. - Treat `panic = "abort"` as no excuse: Cargo ignores profile settings in a dependency's manifest, so a library cannot choose its users' panic strategy. - Separate the phases where possible: run untrusted code first, then mutate with code you control, as the Rustonomicon's two-phase `sift_up` does. - Put the "may panic" fact in the `// SAFETY:` comment, so the next editor does not reorder the lines. - Test with a `Clone` or `Ord` that panics on the n-th call, and run that test under Miri.
- Does `panic = "abort"` in the library's `Cargo.toml` make this a non-issue?No. Cargo only reads profile settings from the workspace root's manifest and ignores those in dependencies, so a library cannot choose its users' panic strategy. Any user building with the default unwinding strategy gets the bug back. Unsafe code in a library has to be correct under unwinding.
- Is leaking the items already cloned an acceptable outcome?For soundness, yes. Leaking is safe in Rust, since `mem::forget` is a safe function, so setting `len` once after the loop meets minimal exception safety. It is still worse behaviour than updating `len` per write, which drops the already-cloned items during unwinding, so prefer the per-write update or a guard unless a benchmark says otherwise.
- How does a drop guard keep the invariant when the loop cannot update `len` each time?Hold the progress in a small struct, such as a `&mut usize` to `len` plus a local count, and give it a `Drop` impl that writes the count back. Drop runs on normal exit and during unwinding, so `len` always ends up covering exactly the written slots. std's `Vec` does this with an internal `SetLenOnDrop`.
- Clone on a reasonable type never panics, so unsafe code may assume it won't.
- Leaking already-cloned items during a panic is undefined behaviour.
- Setting panic = "abort" in the library's own Cargo.toml protects every user.
- Unwinding skips Drop for values whose fields are MaybeUninit.
- Only the unsafe lines can panic, so the safe lines between them need no thought.