about summary refs log tree commit diff
path: root/src/libstd/sys/cloudabi
diff options
context:
space:
mode:
authorVytautas Astrauskas <astrauv@amazon.com>2020-03-30 20:55:17 -0700
committerVytautas Astrauskas <astrauv@amazon.com>2020-03-31 12:24:08 -0700
commit64e5327b6e7ad79f4a3ca7de17ac105c8c59277e (patch)
treec2109b095525f0d33342894891d74571f1574af4 /src/libstd/sys/cloudabi
parent2113659479a82ea69633b23ef710b58ab127755e (diff)
downloadrust-64e5327b6e7ad79f4a3ca7de17ac105c8c59277e.tar.gz
rust-64e5327b6e7ad79f4a3ca7de17ac105c8c59277e.zip
Fix double-free and undefined behaviour in libstd::syn::unix::Thread::new.
Diffstat (limited to 'src/libstd/sys/cloudabi')
-rw-r--r--src/libstd/sys/cloudabi/thread.rs13
1 files changed, 10 insertions, 3 deletions
diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs
index 3afcae7ae75..a3595debaf5 100644
--- a/src/libstd/sys/cloudabi/thread.rs
+++ b/src/libstd/sys/cloudabi/thread.rs
@@ -22,7 +22,7 @@ unsafe impl Sync for Thread {}
 impl Thread {
     // unsafe: see thread::Builder::spawn_unchecked for safety requirements
     pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
-        let p = box p;
+        let mut p = mem::ManuallyDrop::new(box p);
         let mut native: libc::pthread_t = mem::zeroed();
         let mut attr: libc::pthread_attr_t = mem::zeroed();
         assert_eq!(libc::pthread_attr_init(&mut attr), 0);
@@ -30,13 +30,20 @@ impl Thread {
         let stack_size = cmp::max(stack, min_stack_size(&attr));
         assert_eq!(libc::pthread_attr_setstacksize(&mut attr, stack_size), 0);
 
-        let ret = libc::pthread_create(&mut native, &attr, thread_start, &*p as *const _ as *mut _);
+        let ret = libc::pthread_create(
+            &mut native,
+            &attr,
+            thread_start,
+            &mut *p as &mut Box<dyn FnOnce()> as *mut _ as *mut _,
+        );
         assert_eq!(libc::pthread_attr_destroy(&mut attr), 0);
 
         return if ret != 0 {
+            // The thread failed to start and as a result p was not consumed. Therefore, it is
+            // safe to manually drop it.
+            mem::ManuallyDrop::drop(&mut p);
             Err(io::Error::from_raw_os_error(ret))
         } else {
-            mem::forget(p); // ownership passed to pthread_create
             Ok(Thread { id: native })
         };