Avoid arming the Windows TLS destructor guard in fibers
After rust-lang/rust#157645, we use FLS to trigger destructors for thread locals.
In https://github.com/bytecodealliance/wasmtime/pull/14184, it turned out that there's an edge case we didn't cover: if `thread_local/guard/windows.rs::enable` is called from a fiber and later, in a different fiber: (1) the fiber is converted back to a thread and (2) the thread deletes the original fiber, we incorrectly triggers the FLS destructors prematurely.
The fix is simple - avoid arming the FLS slot (setting it to 1) if the calling thread is a fiber.
The issue happened on mingw because it does have target thread local. Tested locally by forcing `registered = false` and checked that the new test fails without the fix.
r? @ChrisDenton
std: don't panic on long-elapsed deadlines for `sleep_until`
`clock_nanosleep` doesn't like deadlines before the clock's epoch, so `sleep_until` can currently panic ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=90acf91e5d4cd3bbb64187a26707d0d8)). Unfortunately the POSIX specification is quite vague about which `timespec` values are allowed, see the code comment...
Fixes the builds of rustc and library/std for the L4Re target OS.
A major change was done in linking binaries: The need for the L4Bender
tool was removed and linking parameters are now fully configured in the
rustc target config.
std: clarify available_parallelism docs for Windows 11 processor groups
On Windows, `available_parallelism`'s docs say the "more than 64 logical CPUs" undercount is harmless because a program needs special support to use more than 64 anyway. That stopped being true in Windows 11 and Windows Server 2022: processes now [span all processor groups by default](https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups#behavior-starting-with-windows-11-and-windows-server-2022), so a program can use more than 64 without any special handling, while `GetSystemInfo` still counts only one group.
Updates the note to describe the before and after. Docs only.
Addresses rust-lang/rust#152389
r? @ChrisDenton
GetSystemInfo reports only the primary processor group's CPU count. Before
Windows 11 and Windows Server 2022 a process was confined to one group by
default, so that count matched what it could use; since then processes span
all groups by default, so it can undercount the parallelism available.
Clarify that `LocalKey::try_with` may return `AccessError`
The docs for `LocalKey::try_with` state that the function *will* return an `AccessError` when the key has been destroyed. That's not actually guaranteed:
- `LocalKey::with` uses `try_with` internally and its docs explicitly acknowledge that it does not always panic when the destructor has run. If `try_with` really did detect every destroyed thread-local, `with` could always panic.
- The top-level `LocalKey` docs already note: "On all platforms it's possible for TLS to re-initialize other TLS slots during destruction."
Change *will* to *may* to accurately reflect the best-effort nature of the destroyed-key check.
Closesrust-lang/rust#157889
@rustbot label +A-docs
The docs stated that try_with will return an AccessError when the key
has been destroyed. This is not guaranteed: on some platforms, TLS
slots can be re-initialized during destruction, so the destroyed state
cannot always be observed. Change 'will' to 'may' to accurately reflect
the best-effort nature of the check.
Document that destructors in running threads are not run on program exit
It's my understanding that, when a Rust program's main thread terminates and thereby causes any still-running threads to be shut down, destructors are not run for the shut-down threads; however, the documentation doesn't seem to come out and say that explicitly anywhere. This PR therefore adds an explicit statement about this to the `std::thread` docs.
If I am mistaken and destructors *are* run, that's worth documenting explicitly, too.
Switch the destructors implementation for thread locals on Windows to use FLS
## Summary
Switch the thread local **destructors** implementation on Windows to use the _Fiber Local Storage_ APIs, which provide native support for setting a callback to be called on thread termination, replacing the current `tls_callback` symbol-based implementation.
_Except for some spellchecking, no LLMs were used to produce code / comments / text in this PR._
## Current Implementation
On Windows, in order to support thread locals with destructors,
the standard library uses a special `tls_callback` symbol that is used to call the `destructors::run()` hook on thread termination.
This has two downsides:
1. It is not well documented, and seems to cause some problems [1] [2] [3].
2. It disallows some synchronization operations, as mentioned in [`LocalKey`'s documentation](https://doc.rust-lang.org/std/thread/struct.LocalKey.html#synchronization-in-thread-local-destructors).
[1]: https://github.com/rust-lang/rust/pull/144234
[2]: https://github.com/rust-lang/rust/issues/145154
[3]: https://github.com/rust-lang/rust/issues/140798
as an example of point 2, this code, which uses `JoinHandle::join` in a thread local Drop impl, will deadlock on stable:
<details>
<summary>Join-on-Drop Deadlock Example</summary>
```rust
struct JoinOnDrop(Option<JoinHandle<()>>);
impl Drop for JoinOnDrop {
fn drop(&mut self) {
self.0.take().unwrap().join().unwrap();
}
}
thread_local! {
static HANDLE: JoinOnDrop = {
let thread = std:🧵:spawn(|| {
println!("Starting...");
// std:🧵:sleep(Duration::from_secs(3));
println!("Done");
});
JoinOnDrop(Some(thread))
};
}
fn main() {
let thread = std:🧵:spawn(|| {
HANDLE.with(|_| {
println!("Some other thread");
})
});
thread.join().unwrap();
println!("Done");
}
```
</details>
## Proposed Change
We can use the `Fls{Alloc,Set,Get,Free}` functions (see https://devblogs.microsoft.com/oldnewthing/20191011-00/?p=102989)
to implement the dtor callback needed for thread locals that have a Drop implementation.
We allocate a single key, and use its destructor callback to run all the registered destructors when a thread is shutting down.
With this implementation, the above code sample will not deadlock (but it still might not be a good idea to do this!).
## Safety and Compatibility
We use the common `thread_local` + atomic pattern to only set a single FLS key.
The destructor callback is only called when that value is non-zero.
Destructors will only run at thread exit: we verify that we are not running in a fiber during the destructors callback. **This means that using fibers (which is very rare) will result in thread locals being leaked**, unless the fiber is converted back to a thread using `ConvertFiberToThread` before thread termination. This is not ideal, but should be OK as destructors are not guaranteed to run, but it needs to be documented.
It might be possible for the user to use something like the current `tls_callback` to observe an already-freed thread locals, which is something that can also happen in the current implementation.
~Destructors will only run on the correct thread: Fibers cannot be moved between threads.~
Destructors will only run on the correct thread: the hook uses a `#[thread_local]` list, so fiber movement between threads does not change which which thread executes the destructors.
Destructors will only run once: even if the hook is called multiple time, the `#[thread_local]` list is cleared after the first run.
Users cannot observe different locals because they are using fibers: because we only use an Fls local marker to trigger the destructors callback, we don't change anything about how users interact with "normal" thread locals and fiber locals.
### DLL Unloading
It is possible to build a `cdylib` which uses thread locals and unload it dynamically using `FreeLibrary`. This can cause the OS to call into an unmapped cleanup hook, so we use `atexit` to manually free the special FLS key, which will also trigger the cleanup hook for each registered thread. This is safe because similar to thread shutdown, no user code can ran after this point, and only the destructors of the running thread will run.
see `tests/run-make/dynamic-loading-cdylib/load_and_unload.rs`.
## Other Notes
The implementation is based on the `key::racy` and `guard::apple` code, because we need a `LazyKey`-like racey static and an `enable` function.
While TLS slots are [limited to 1088](https://devblogs.microsoft.com/oldnewthing/20170712-00/?p=96585), FLS slots are currently [limited to 4000](https://devblogs.microsoft.com/windows-music-dev/effectively-removing-the-fls-slot-allocation-limit-in-windows-10/) per process.
### Miri
Because miri is aware to the thread local implementation, I also implemented these functions and support for them in the interpreter here:
https://github.com/rust-lang/miri/compare/master...ohadravid:miri:windows-fls-support?expand=1
I guess that this will need to be merged before this PR (if this is accepted) - let me know and I'll open that PR as well.
### Targets without `target_thread_local`
In `*-gnu` Windows targets, the `target_thread_local` feature is unavailable.
We could also change the "key" (non-`target_thread_local`) Windows impl at
`library\std\src\sys\thread_local\key\windows.rs`
to be based on the Fls functions. I can add it to this PR, or as a separate PR, if you think this is preferable.
`Cell` in a `#[thread_local]` is used to store the resulting key, like the other implementations. When `target_thread_local` isn't available, we always fetch the atomic and set the FLS key's value.
The `fuzzy_provenance_casts` lint is enabled in most of the standard
library, but its identical twin `lossy_provenance_casts` was not. As
discussed in the tracking issue for those lints, there doesn't seem to
be any good reason to enable one without the other. This PR applies this
principle and as a result removes some unnecessary ptr->int `as` casts.
It's also preparation for merging the two lints, which removes the
option of only enabling `fuzzy_provenance_casts`.
docs: Fix typo in std/src/thready/scoped.rs
# Fix typo in std/src/thread/scoped.rs
## Why this pr
This PR fixes the typo mentioned in rust-lang/rust#155275.
I know this was originally fixed in rust-lang/rust#155325 and then in rust-lang/rust#155328.
But since the first issue was closed due to some ai slop and the second one was closed because the first one was already opened, it seems to me that this PR is still needed.
## What this pr does
This PR "just" fixes a typo inside the `std/src/thread/scoped.rs` file
Changing the comment from this:
```
/// borrow non-`'static` data from the outside the scope. See [`scope`] for
/// details.
```
to this:
```
/// borrow non-`'static` data from outside the scope. See [`scope`] for
/// details.
```
thread::scope: document how join interacts with TLS destructors
Fixes https://github.com/rust-lang/rust/issues/116237 by documenting the current behavior regarding thread-local destructors as intended. (I'm not stoked about this, but documenting it is better than leaving it unclear.)
This also adds documentation for explicit `join` calls (both for scoped and regular threads), saying that those *will* wait for TLS destructors. That reflects my understanding of the current implementation, which calls `join` on the native thread handle. Are we okay with guaranteeing that? I think we should, so people have at least some chance of implementing "wait for all destructors" manually. This fixes https://github.com/rust-lang/rust/issues/127571.
Cc @rust-lang/libs-api