Commit Graph

444 Commits

Author SHA1 Message Date
HigherOrderLogic
018b9ad740 std: remove exceed whitespace in docs 2026-09-07 19:37:51 +10:00
Ralf Jung
95d43bf535 remove no-longer-needed MaybeDangling from thread spawning 2026-09-04 16:35:10 +02:00
Chris Denton
a7f7b19ad6 clippy::redundant_closure 2026-08-25 18:15:03 +00:00
Jonathan Brouwer
ddfd6dc62f Rollup merge of #161451 - ohadravid:windows-tls-avoid-registering-dtors-in-fibers, r=ChrisDenton
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
2026-08-22 10:48:43 +02:00
Ohad Ravid
373266b87e Avoid arming the Windows TLS destructor guard in fibers 2026-08-21 06:37:33 -07:00
Jacob Pratt
b7dba0eb2a Rollup merge of #161295 - joboet:sleep_until-long-elapsed, r=tgross35
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...
2026-08-20 21:34:23 -04:00
Jacob Pratt
81d5d74813 Rollup merge of #152617 - joboet:fuchsia_sleep_until, r=nia-e
std: implement `sleep_until` for Fuchsia

Tracking issue: rust-lang/rust#113752

Unfortunately Fuchsia's `clock_nanosleep` is [only a stub](https://cs.opensource.google/fuchsia/fuchsia/+/main:zircon/third_party/ulib/musl/src/time/clock_nanosleep.c;l=4;drc=26e68e7948a6cc4a1c4a0c8eb19b7e4a2dc27153). The kernel's `zx_nanosleep` syscall however does exactly what's needed.

I've done a few drive-by changes in the two outer commits, our uses of `zx_time_t` use the `zx_instant_mono_t` alias nowadays and the syscall table in the `sleep_until` documentation didn't mark the function names as code.

@rustbot ping fuchsia
2026-08-20 21:34:20 -04:00
joboet
2d28ce9ee7 std: add a comment about elapsed deadlines for sleep_until 2026-08-20 13:37:44 +02:00
joboet
1c0a0d9a12 std: update sleep_until syscall table 2026-08-20 13:19:41 +02:00
Josh Stone
d480723d0a reformat 2026-08-19 09:27:38 -07:00
Josh Stone
3f38a78275 replace-version-placeholder
(cherry picked from commit 982c76891ff5e7e2fb61a5bd5f2727c2c5906f8e)
2026-08-19 09:20:34 -07:00
joboet
dd69e6bd7c std: don't panic on long-elapsed deadlines for sleep_until 2026-08-18 14:27:44 +02:00
Marius Melzer
f2dd93228a L4Re: Repair build and move to rustc linking
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.
2026-08-06 13:13:18 +02:00
Max Dexheimer
f80e5c1e9b Explicitly document that spawn hooks are not guaranteed to run 2026-07-26 11:46:15 +02:00
Max Dexheimer
ce472c9f9f Ensure noone can observe the thread spawn hooks being taken 2026-07-26 11:43:18 +02:00
Jacob Pratt
b016514e18 Rollup merge of #159305 - valentynkit:docs/available-parallelism-windows, r=workingjubilee
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
2026-07-14 23:23:17 -04:00
Jacob Pratt
2d4ae662df Rollup merge of #158608 - mejrs:opaque, r=estebank
Implement `#[diagnostic::opaque]` attribute to hide backtraces of macros.

r? @estebank

There are some more places where we can use this, for example 345632878c/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs (L623-L639) but those turned out to be a little complicated so are left for followup prs.

Tracking issue: rust-lang/rust#158813
2026-07-14 23:23:07 -04:00
Valentyn Kit
5411bb0e20 std: clarify available_parallelism docs for Windows 11 processor groups
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.
2026-07-14 23:00:09 +03:00
Jonathan Brouwer
c1d608bb7e Rollup merge of #158760 - kpeis695:fix/localkey-try-with-may-return, r=aapoalas
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.

Closes rust-lang/rust#157889

@rustbot label +A-docs
2026-07-07 22:26:56 +02:00
Jacob Pratt
04b47ed9a3 Rollup merge of #157734 - tgross35:stabilize-local_key_cell_update, r=jhpratt
Stabilize `local_key_cell_update`

Newly stable API:

```rust
impl<T: 'static> LocalKey<Cell<T>> {
    pub fn update(&'static self, f: impl FnOnce(T) -> T)
    where
        T: Copy;
}
```

This matches the signature on `Cell`.

Closes: https://www.github.com/rust-lang/rust/issues/143989 (Tracking issue)
2026-07-06 04:33:12 -04:00
mejrs
106bb96346 Remove rustc_diagnostic_item hack 2026-07-05 17:33:52 +02:00
Sylvester Kpei
b51d75e3a9 Clarify that LocalKey::try_with may return AccessError
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.
2026-07-03 20:01:47 -07:00
Jonathan Brouwer
7c3eb23988 Rollup merge of #156788 - jwodder:thread-shutdown, r=traviscross
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.
2026-06-17 19:25:36 +02:00
John T. Wodder II
8410d269e3 Document that destructors in running threads are not run on program exit
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
2026-06-17 12:05:51 -04:00
Trevor Gross
ef5968d200 Stabilize local_key_cell_update
Newly stable API:

    impl<T: 'static> LocalKey<Cell<T>> {
        pub fn update(&'static self, f: impl FnOnce(T) -> T)
        where
            T: Copy;
    }

This matches the signature on `Cell`.

Tracking issue: RUST-143989
2026-06-10 20:39:02 -05:00
Trevor Gross
88c0724b62 std: Update documentation for LocalKey<Cell<T>>::update
The disclaimers relevant for other `LocalKey` methods are relevant for
`update`, so add them to the documentation.
2026-06-10 20:35:18 -05:00
Ohad Ravid
f5e570935d Only register the atexit hook when cleanup is unloadable 2026-06-10 07:04:13 -07:00
Ralf Jung
20479b727f thread spawn hooks: rename run to make it clear that it also handles inheriting spawn hooks 2026-06-05 14:58:31 +02:00
bors
9c963eecaa Auto merge of #148799 - ohadravid:windows-thread-local-dtors-using-fls, r=ChrisDenton
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.
2026-06-03 16:26:56 +00:00
Ohad Ravid
336dc57c29 Prevent races between thread_local::guard and atexit using a dedicated struct
and don't track active `enable` calls in miri
2026-06-02 07:59:37 +03:00
Ohad Ravid
1142cfb0a5 Free FLS key used by thread_local::guard during DLL unload to avoid access violation 2026-05-26 21:06:07 +03:00
Ohad Ravid
b5958a9d90 Replace thread_local::guard on Windows with an FLS-based impl 2026-05-26 21:06:02 +03:00
Hanna Kruppe
fed6279325 library: use strict provenance lints consistently
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`.
2026-05-25 20:45:24 +02:00
Jacob Pratt
4fa293c965 Rollup merge of #155454 - MadeInShineA:issue-155275-fix, r=lqd
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.
```
2026-04-18 00:05:21 -04:00
Olivier Amacker
10cc6c4a39 docs: Fix typo in std/src/thread/scoped.rs 2026-04-17 19:39:18 +02:00
Waffle Lapkin
32cc8b13c9 use MaybeDangling in std 2026-04-09 15:51:46 +02:00
Jules Bertholet
7f83c784bd Allow passing expr metavariable as a cfg predicate 2026-03-15 13:44:14 -04:00
biscuitrescue
014344b0c3 update panicking() docs for panic=abort
rephrasing and grammar
2026-03-04 01:38:06 +05:30
Jonathan Brouwer
faa0d67374 Rollup merge of #149482 - RalfJung:scope-tls-dtors, r=joboet
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
2026-01-29 17:47:31 +01:00
Leonard Chan
5dbaac1357 Remove Fuchsia from target OS list in unix.rs for sleep 2026-01-27 14:08:15 -08:00
joboet
959be82eff std: implement sleep_until on Apple platforms 2026-01-13 11:22:50 +01:00
Martin Nordholts
8e3d60447c Finish transition from semitransparent to semiopaque for rustc_macro_transparency 2026-01-08 19:14:45 +01:00
Tobias Bucher
440bf4ded9 crate::io::Result → io::Result in most places
I don't know why many places refer to the type as `crate::io::Result`
when `crate::io` is already imported.
2025-12-29 15:09:48 +01:00
joboet
33409da171 std: update references to FromInner etc. 2025-12-15 14:00:37 +01:00
Boxy
85aeb4f259 Forbid object lifetime changing pointer casts 2025-12-10 09:38:56 +00:00
Ralf Jung
14830bfd0c ThreadId generation fallback path: avoid spurious yields 2025-11-30 22:52:28 +01:00
Ralf Jung
1deb487076 thread::scope: document how join interacts with TLS destructors 2025-11-30 14:25:17 +01:00
joboet
9c6e0f6f57 std: update broken links in thread module 2025-11-29 15:59:11 +01:00
joboet
8b08da218e std: split up the thread module 2025-11-29 15:59:11 +01:00
joboet
e57df9220a std: split up the thread module (preparation) 2025-11-29 15:12:28 +01:00