Last active
September 14, 2023 18:31
-
-
Save momvart/bfe4eae7f7efb18b720aee26d9c95521 to your computer and use it in GitHub Desktop.
An example of how unsafe Rust can cause memory deallocation bugs. A case of late `len` update and unsoundness.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(maybe_uninit_uninit_array)] | |
#![feature(extend_one)] | |
use std::mem::MaybeUninit; | |
fn main() { | |
let mut v = MyVec::new(); | |
v.push(Box::new(DropReporter)); | |
let mut dest = BadExtend(Default::default()); | |
// let mut dest = Vec::default(); // This works fine. | |
let _result = std::panic::catch_unwind(move || { | |
v.drain_to_double_free(&mut dest); | |
v.drain_to_drop_uninit(&mut dest); | |
}); | |
println!("No unhandled error."); | |
} | |
struct MyVec<T> { | |
data: [MaybeUninit<Box<T>>; 4], | |
len: usize, | |
} | |
impl<T> MyVec<T> { | |
fn new() -> Self { | |
let data = MaybeUninit::uninit_array(); | |
let len = 0; | |
MyVec { data, len } | |
} | |
fn push(&mut self, item: T) { | |
if self.len == self.data.len() { | |
return; | |
} | |
self.data[self.len] = MaybeUninit::new(Box::new(item)); | |
self.len += 1; | |
} | |
fn drain_to_double_free(&mut self, dest: &mut impl Extend<Box<T>>) { | |
for i in 0..self.len { | |
let mut item = MaybeUninit::uninit(); | |
unsafe { | |
std::ptr::copy(self.data[i].as_ptr(), item.as_mut_ptr(), 1); | |
} | |
dest.extend_one(unsafe { item.assume_init() }); | |
} | |
self.len = 0; | |
} | |
fn drain_to_drop_uninit(&mut self, dest: &mut impl Extend<Box<T>>) { | |
for i in 0..self.len { | |
let mut item = MaybeUninit::uninit(); | |
unsafe { | |
std::mem::swap(self.data[i].assume_init_mut(), item.assume_init_mut()); | |
} | |
dest.extend_one(unsafe { item.assume_init() }); | |
} | |
self.len = 0; | |
} | |
} | |
impl<T> Drop for MyVec<T> { | |
fn drop(&mut self) { | |
for i in 0..self.len { | |
println!("Dropping item at {:?}", i); | |
unsafe { self.data[i].assume_init_drop() } | |
} | |
} | |
} | |
#[derive(Debug)] | |
struct DropReporter(&'static str); | |
impl Drop for DropReporter { | |
fn drop(&mut self) { | |
println!("Dropping {:?}", self.0); | |
} | |
} | |
#[derive(Default)] | |
struct BadExtend<T>(std::marker::PhantomData<T>); | |
impl<X> Extend<X> for BadExtend<X> { | |
fn extend<T: IntoIterator<Item = X>>(&mut self, iter: T) { | |
if iter.into_iter().next().is_some() { | |
panic!("BadExtend::extend called") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The MIR for this program: