Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,13 @@ impl<const N: usize, K, V, const LINEAR_THRESHOLD: usize> RawInline<N, (K, V), L
i += 1;
} else {
unsafe {
core::ptr::drop_in_place(self.data[i].as_mut_ptr());
// Read the rejected element out first, fix up the structure
// via `erase`, and only then drop it. If the destructor
// panics, the container is already consistent, so the slot
// is not dropped again.
let removed = core::ptr::read(self.data[i].as_ptr());
self.erase(i);
drop(removed);
}
// Don't increment i, check the swapped element
}
Expand Down
37 changes: 37 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2109,4 +2109,41 @@ mod tests {
assert_eq!(map.get(&1), Some(&10), "Failed to find 1");
assert_eq!(map.get(&5), Some(&50), "Failed to find 5");
}

#[test]
fn retain_panicking_drop_keeps_map_consistent() {
use std::panic::{catch_unwind, AssertUnwindSafe};

struct PanicOnDrop {
tag: String,
}
impl Drop for PanicOnDrop {
fn drop(&mut self) {
if self.tag == "panic" {
panic!("boom");
}
}
}

let mut map: SmallMap<16, u32, PanicOnDrop> = SmallMap::default();
for i in 0..8u32 {
let tag = if i == 4 {
"panic".to_string()
} else {
format!("ok{i}")
};
map.insert(i, PanicOnDrop { tag });
}

// One element's Drop panics during retain. Before the fix this left the
// inline storage claiming the already-dropped slots were still occupied,
// so dropping the map re-dropped them (double-free / UAF under ASan).
let result = catch_unwind(AssertUnwindSafe(|| {
map.retain(|_k, _v| false);
}));
assert!(result.is_err());

// With the fix, dropping the map here must not double-drop.
drop(map);
}
}
Loading