Skip to content

Commit f25c81a

Browse files
committed
rustuv: Fix a use-after-free on destruction
The uv loop was being destroyed before the async handle was being destroyed, so closing the async handle was causing a use-after-free in the uv loop. This was fixed by moving destruction of the queue's async handle to an earlier location and then actually freeing it once the loop has been dropped.
1 parent 962af91 commit f25c81a

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/librustuv/queue.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,10 @@ impl QueuePool {
138138
}
139139
Queue { queue: self.producer.clone() }
140140
}
141+
142+
pub fn handle(&self) -> *uvll::uv_async_t {
143+
unsafe { (*self.producer.packet()).handle }
144+
}
141145
}
142146

143147
impl Queue {
@@ -180,7 +184,9 @@ impl Drop for State {
180184
fn drop(&mut self) {
181185
unsafe {
182186
uvll::uv_close(self.handle, cast::transmute(0));
183-
uvll::free_handle(self.handle);
187+
// Note that this does *not* free the handle, that is the
188+
// responsibility of the caller because the uv loop must be closed
189+
// before we deallocate this uv handle.
184190
}
185191
}
186192
}

src/librustuv/uvio.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,13 @@ impl Drop for UvEventLoop {
6767
fn drop(&mut self) {
6868
// Must first destroy the pool of handles before we destroy the loop
6969
// because otherwise the contained async handle will be destroyed after
70-
// the loop is free'd (use-after-free)
70+
// the loop is free'd (use-after-free). We also must free the uv handle
71+
// after the loop has been closed because during the closing of the loop
72+
// the handle is required to be used apparently.
73+
let handle = self.uvio.handle_pool.get_ref().handle();
7174
self.uvio.handle_pool.take();
7275
self.uvio.loop_.close();
76+
unsafe { uvll::free_handle(handle) }
7377
}
7478
}
7579

0 commit comments

Comments
 (0)