rust-lang / rust-lang/rust

A thread closure's destructor can panic in `std::thread::spawn` on Windows

Open
#124,468 7 comments 1 reaction 1 assignee View on GitHub

@fuzzypixelz is already working on this.

Since Apr 28, 2024.

A-thread O-windows T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

The following is part of the native Thread::new implementation on Windows:

// https://github.com/rust-lang/rust/blob/master/library/std/src/sys/pal/windows/thread.rs#L30
let ret = c::CreateThread(
    ptr::null_mut(),
    stack,
    Some(thread_start),
    p as *mut _,
    c::STACK_SIZE_PARAM_IS_A_RESERVATION,
    ptr::null_mut(),
);
let ret = HandleOrNull::from_raw_handle(ret);
return if let Ok(handle) = ret.try_into() {
    Ok(Thread { handle: Handle::from_inner(handle) })
} else {
    // The thread failed to start and as a result p was not consumed. Therefore, it is
    // safe to reconstruct the box so that it gets deallocated.
    drop(Box::from_raw(p));
    Err(io::Error::last_os_error())
};

If drop(Box::from_raw(p)); panics, then the error is not returned. I suggest to replace the drop statement with:

panic::catch_unwind(AssertUnwindSafe(|| drop(Box::from_raw(p))));

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.