Move thread parking to `sys::sync`
Part of #117276.
I'll leave the platform-specific API abstractions in `sys::pal`, as per the initial proposal. I'm not entirely sure whether we'll want to keep it that way, but that remains to be seen.
r? ``@ChrisDenton`` (if you have time)
Reduce code size of `thread::set_current`
#123265 introduced a rather large binary size regression, because it added an `unwrap()` call on a `Result<(), Thread>`, which in turn pulled its rather heavy `Debug` implementation. This PR fixes this by readding the `rtassert!` that was removed.
As of 124114 it's exactly the same in codegen, so might as well not use `unsafe`.
Note that this is only for *unsigned*, since the overflow conditions for `iN::checked_sub` are more complicated.
zkvm: fix run_tests
`zkvm` is single-threaded, similar to `emscripten` and `wasm`. The `cfg` for `zkvm` seems to have been dropped. This PR adds the `cfg` again.
Stabilize `split_at_checked`
Closes#119128
For the const version of `slice::split_at_mut_checked`, I'm reusing the `const_slice_split_at_mut` feature flag (#101804). I don't if it okay to reuse tracking issues or if it preferred to create new ones...
Change `SIGPIPE` ui from `#[unix_sigpipe = "..."]` to `-Zon-broken-pipe=...`
In the stabilization [attempt](https://github.com/rust-lang/rust/pull/120832) of `#[unix_sigpipe = "sig_dfl"]`, a concern was [raised ](https://github.com/rust-lang/rust/pull/120832#issuecomment-2007394609) related to using a language attribute for the feature: Long term, we want `fn lang_start()` to be definable by any crate, not just libstd. Having a special language attribute in that case becomes awkward.
So as a first step towards the next stabilization attempt, this PR changes the `#[unix_sigpipe = "..."]` attribute to a compiler flag `-Zon-broken-pipe=...` to remove that concern, since now the language is not "contaminated" by this feature.
Another point was [also raised](https://github.com/rust-lang/rust/pull/120832#issuecomment-1987023484), namely that the ui should not leak **how** it does things, but rather what the **end effect** is. The new flag uses the proposed naming. This is of course something that can be iterated on further before stabilization.
Tracking issue: https://github.com/rust-lang/rust/issues/97889
Describe and use CStr literals in CStr and CString docs
Mention CStr literals in the description of both types, and use them in some of the code samples for CStr. This is intended to make C string literals more discoverable.
Additionally, I don't think the orange "This example is not tested" warnings are very encouraging, so I have made the examples on `CStr` build.
default_alloc_error_hook: explain difference to default __rdl_oom in alloc
Though I'm not sure if that is really the reason that this code is duplicated. On no_std it may already be possible to call user-defined code on allocation failure.
Implement ptr_as_ref_unchecked
Implementation of #122034.
Prefixed the feature name with `ptr_` for clarity.
Linked const-unstability to #91822, so the post there should probably be updated to mentions the 3 new methods when/if this PR is merged.
Fix HorizonOS build broken by #124210
HorizonOS (for the Tier-3 target `armv6k-nintendo-3ds`) does not support `dirfd()`, as many other similar targets.
library/std: Remove unused `gimli-symbolize` feature
library/backtrace also declares a feature called `gimli-symbolize` which appear used, but the feature in std with the same name is unused, so remove it.
String.truncate comment microfix (greater or equal)
String.truncate calls Vec.truncate, in turn, and that states "is greater or equal to". Beside common sense.
deref patterns: impl `DerefPure` for more std types
Context: [deref patterns](https://github.com/rust-lang/rust/issues/87121). The requirements of `DerefPure` aren't precise yet, but these types unambiguously satisfy them.
Interestingly, a hypothetical `impl DerefMut for Cow` that does a `Clone` would *not* be eligible for `DerefPure` if we allow mixing deref patterns with normal patterns. If the following is exhaustive then the `DerefMut` would cause UB:
```rust
match &mut Cow::Borrowed(&()) {
Cow::Owned(_) => ..., // Doesn't match
deref!(_x) if false => ..., // Causes the variant to switch to `Owned`
Cow::Borrowed(_) => ..., // Doesn't match
// We reach unreachable
}
```
In the stabilization attempt of `#[unix_sigpipe = "sig_dfl"]`, a concern
was raised related to using a language attribute for the feature: Long
term, we want `fn lang_start()` to be definable by any crate, not just
libstd. Having a special language attribute in that case becomes
awkward.
So as a first step towards towards the next stabilization attempt, this
PR changes the `#[unix_sigpipe = "..."]` attribute to a compiler flag
`-Zon-broken-pipe=...` to remove that concern, since now the language
is not "contaminated" by this feature.
Another point was also raised, namely that the ui should not leak
**how** it does things, but rather what the **end effect** is. The new
flag uses the proposed naming. This is of course something that can be
iterated on further before stabilization.
Document never type fallback in `!`'s docs
Pulled the documentation I've written for #123939.
I want a single place where never type fallback is explained, which can be referred in all the lints and migration materials.
library/backtrace also declares a feature called `gimli-symbolize` which
appear used, but the feature in std with the same name is unused, so
remove it.
Use `target_vendor = "apple"` instead of `target_os = "..."`
Use `target_vendor = "apple"` instead of `all(target_os = "macos", target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos")`.
The apple targets are quite close to being identical, with iOS, tvOS, watchOS and visionOS being even closer, so using `target_vendor` when possible makes it clearer when something is actually OS-specific, or just Apple-specific.
Note that `target_vendor` will [be deprecated in the future](https://github.com/rust-lang/rust/issues/100343), but not before an alternative (like `target_family = "apple"`) is available.
While doing this, I found various inconsistencies and small mistakes in the standard library, see the commits for details. Will follow-up with an extra PR for a similar issue that need a bit more discussion. EDIT: https://github.com/rust-lang/rust/pull/124494
Since you've talked about using `target_vendor = "apple"` in the past:
r? workingjubilee
CC `@simlay,` `@thomcc`
`@rustbot` label O-macos O-ios O-tvos O-watchos O-visionos
Fix#124478 - offset_of! returns a temporary
This was due to the must_use() call. Adding HIR's `OffsetOf` to the must_use checking within the compiler avoids this issue while maintaining the lint output.
Fixes#124478. `@tgross35`
Update `is_val_statically_known` Docs
* Add `Type Requirements` section, listing the allowed inputs, as requested by #121115
* Add `Pointers` subsection, explaining is_val_statically_known handles pointers.
* Add `Stability concerns` section, referring to other documentation relating to consistency in `const` functions.
Fixes#121115
Sorry this took so long.
`man posix_spawn` documents it to be able to return `ENOENT`, and there
should be nothing preventing this. Tested in the iOS simulator and on
Mac Catalyst.
Abort a process when FD ownership is violated
When an owned FD has already been closed before it's dropped that means something else touched an FD in ways it is not allowed to. At that point things can already be arbitrarily bad, e.g. clobbered mmaps. Recovery is not possible.
All we can do is hasten the fire.
Unlike the previous attempt in #124130 this shouldn't suffer from the possibility that FUSE filesystems can return arbitrary errors.
Unconditionally call `really_init` on GNU/Linux
This makes miri not diverge in behavior, it fixes running Rust linux-gnu binaries on musl with gcompat, it fixes dlopen edge-cases that cranelift somehow hits, etc.
Fixes#124126
thou hast gazed into this abyss with me:
r? ``@ChrisDenton``
This makes miri not diverge in behavior, it fixes running Rust linux-gnu
binaries on musl with gcompat, it fixes dlopen edge-cases that cranelift
somehow hits, etc.
thread_local: be excruciatingly explicit in dtor code
Use raw pointers to accomplish internal mutability, and clearly split references where applicable. This reduces the likelihood that any of these parts are misunderstood, either by humans or the compiler's optimizations.
Fixes#124317
r? ``@joboet``
PathBuf: replace transmuting by accessor functions
The existing `repr(transparent)` was anyway insufficient as `OsString` was not `repr(transparent)`. And furthermore, on Windows it was blatantly wrong as `OsString` wraps `Wtf8Buf` which is a `repr(Rust)` type with 2 fields:
51a7396ad3/library/std/src/sys_common/wtf8.rs (L131-L146)
So let's just be honest about what happens and add accessor methods that make this abstraction-breaking act of PathBuf visible on the APIs that it pierces through.
Fixes https://github.com/rust-lang/rust/issues/124409
Convert some iter macros to normal functions
With all the MIR optimization changes that have happened since these were written, let's see if they still actually matter.
\*perf comes back\*
Well, it looks like it's not longer relevant for instruction, cycle, nor wall-time perf. Looks like a bunch of things are maybe 10kb bigger in debug, but some are also 50k *smaller* in debug.
So I think they should switch to being normal functions as the "greatly improves performance" justification for them being macros seems to no longer be true -- probably thanks to us always building `core` with `-Z inline-mir` so the difference is negligible.
Add diagnostic item for `std::iter::Enumerate`
This adds a diagnostic item for `std::iter::Enumerate`. The change will be used by the clippy `unused_enumerate_index` lint to move away from type paths to using diagnostic items.
see: https://github.com/rust-lang/rust-clippy/issues/5393
windows fill_utf16_buf: explain the expected return value
The comment just says "return what the syscall returns", but that doesn't work for all syscalls as the Windows API is not consistent in how buffer size is negotiated. For instance, GetUserProfileDirectoryW works a bit differently, and so home_dir_crt has to translate this to the usual protocol itself. So it's worth describing that protocol.
r? ``@ChrisDenton``
Rollup of 3 pull requests
Successful merges:
- #124003 (Dellvmize some intrinsics (use `u32` instead of `Self` in some integer intrinsics))
- #124169 (Don't fatal when calling `expect_one_of` when recovering arg in `parse_seq`)
- #124286 (Subtree sync for rustc_codegen_cranelift)
r? `@ghost`
`@rustbot` modify labels: rollup
Dellvmize some intrinsics (use `u32` instead of `Self` in some integer intrinsics)
This implements https://github.com/rust-lang/compiler-team/issues/693 minus what was implemented in #123226.
Note: I decided to _not_ change `shl`/... builder methods, as it just doesn't seem worth it.
r? ``@scottmcm``
alloc::Layout: explicitly document size invariant on the type level
https://github.com/rust-lang/rust/pull/95295 added this to the constructor, but it seems worth documenting the type invariant at the type level.
panic_str only exists for the migration to 2021 panic macros
The only caller is `expect_failed`, which is already a cold inline(never) function, so inlining into that function should be fine. (And indeed `panic_str` was `#[inline]` anyway.)
The existence of panic_str risks someone calling it when they should call `panic` instead, and I can't see a reason why this footgun should exist.
I also extended the comment in `panic` to explain why it needs a `'static` string -- I know I've wondered about this in the past and it took me quite a while to understand.
remove an unused type from the reentrant lock tests
At least it seems unused. This was added back in 45aa6c8d1b together with a test related to poisoning; when the test got removed, it seems like it was forgotten to also remove this type.
Add simple async drop glue generation
This is a prototype of the async drop glue generation for some simple types. Async drop glue is intended to behave very similar to the regular drop glue except for being asynchronous. Currently it does not execute synchronous drops but only calls user implementations of `AsyncDrop::async_drop` associative function and awaits the returned future. It is not complete as it only recurses into arrays, slices, tuples, and structs and does not have same sensible restrictions as the old `Drop` trait implementation like having the same bounds as the type definition, while code assumes their existence (requires a future work).
This current design uses a workaround as it does not create any custom async destructor state machine types for ADTs, but instead uses types defined in the std library called future combinators (deferred_async_drop, chain, ready_unit).
Also I recommend reading my [explainer](https://zetanumbers.github.io/book/async-drop-design.html).
This is a part of the [MCP: Low level components for async drop](https://github.com/rust-lang/compiler-team/issues/727) work.
Feature completeness:
- [x] `AsyncDrop` trait
- [ ] `async_drop_in_place_raw`/async drop glue generation support for
- [x] Trivially destructible types (integers, bools, floats, string slices, pointers, references, etc.)
- [x] Arrays and slices (array pointer is unsized into slice pointer)
- [x] ADTs (enums, structs, unions)
- [x] tuple-like types (tuples, closures)
- [ ] Dynamic types (`dyn Trait`, see explainer's [proposed design](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#async-drop-glue-for-dyn-trait))
- [ ] coroutines (https://github.com/rust-lang/rust/pull/123948)
- [x] Async drop glue includes sync drop glue code
- [x] Cleanup branch generation for `async_drop_in_place_raw`
- [ ] Union rejects non-trivially async destructible fields
- [ ] `AsyncDrop` implementation requires same bounds as type definition
- [ ] Skip trivially destructible fields (optimization)
- [ ] New [`TyKind::AdtAsyncDestructor`](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#adt-async-destructor-types) and get rid of combinators
- [ ] [Synchronously undroppable types](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#exclusively-async-drop)
- [ ] Automatic async drop at the end of the scope in async context
checked_ilog: improve performance
Addresses #115874.
(This PR replicates the original #115875, which I accidentally closed by deleting my forked repository...)
Fix watchOS and visionOS for pread64 and pwrite64 calls
In #122880, links to `preadv64` and `pwritev64` were added for `watchOS` however the underlying [`weak!` macro did not include `target_os = "watchos"`](c45dee5efd/library/std/src/sys/pal/unix/weak.rs (L30-L74)).
This resulted in an `xcodebuild` error when targeting `watchOS`:
```
Undefined symbols for architecture arm64:
"_preadv64", referenced from:
__rust_extern_with_linkage_preadv64 in libliveview_native_core.a[274](std-324fdd8d31e8eaa2.std.e18cf7e8d0336778-cgu.08.rcgu.o)
"_pwritev64", referenced from:
__rust_extern_with_linkage_pwritev64 in libliveview_native_core.a[274](std-324fdd8d31e8eaa2.std.e18cf7e8d0336778-cgu.08.rcgu.o)
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```
So I added them. I also went ahead and added the same for visionOS because it's bound to create the same issue.
When an EBADF happens then something else already touched an FD in ways it is not allowed to.
At that point things can already be arbitrarily bad, e.g. clobbered mmaps.
Recovery is not possible.
All we can do is hasten the fire.
Use fake libc in core test
The war on libc continues.
Some platforms may not need to link to the libc crate (and it's possible some may not even have a libc), therefore we shouldn't require it for tests. This creates dummy `malloc` and `free` implementations for use in the pointer docs, but, keeps the public documentation looking the same as before.
Add a lower bound check to `unicode-table-generator` output
This adds a dedicated check for the lower bound
(if it is outside of ASCII range) to the output of the `unicode-table-generator` tool.
This generalized the ASCII-only fast-path, but only for the `Grapheme_Extend` property for now, as that is the only one with a lower bound outside of ASCII.
This adds a dedicated check for the lower bound
(if it is outside of ASCII range) to the output of the `unicode-table-generator` tool.
This generalized the ASCII-only fast-path, but only for the `Grapheme_Extend` property for now,
as that is the only one with a lower bound outside of ASCII.
Make `checked` ops emit *unchecked* LLVM operations where feasible
For things with easily pre-checked overflow conditions -- shifts and unsigned subtraction -- write the checked methods in such a way that we stop emitting wrapping versions of them.
For example, today <https://rust.godbolt.org/z/qM9YK8Txb> neither
```rust
a.checked_sub(b).unwrap()
```
nor
```rust
a.checked_sub(b).unwrap_unchecked()
```
actually optimizes to `sub nuw`. After this PR they do.
cc #103299
Use raw-dylib for Windows synchronization functions
Fixes#123999 by using the raw-dylib feature to specify the DLL to load the Windows futex functions from (e.g. [`WaitOnAddress`](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitonaddress)). This avoids reliance on the import library causing that issue.
With apologies to ``@bjorn3,`` as it's currently necessary to revert this for cranelift.
For things with easily pre-checked overflow conditions -- shifts and unsigned subtraction -- write then checked methods in such a way that we stop emitting wrapping versions of them.
For example, today <https://rust.godbolt.org/z/qM9YK8Txb> neither
```rust
a.checked_sub(b).unwrap()
```
nor
```rust
a.checked_sub(b).unwrap_unchecked()
```
actually optimizes to `sub nuw`. After this PR they do.
Add support for Arm64EC to the Standard Library
Adds the final pieces so that the standard library can be built for arm64ec-pc-windows-msvc (initially added in #119199)
* Bumps `windows-sys` to 0.56.0, which adds support for Arm64EC.
* Correctly set the `isEC` parameter for LLVM's `writeArchive` function.
* Add `#![feature(asm_experimental_arch)]` to library crates where Arm64EC inline assembly is used, as it is currently unstable.
Document overrides of `clone_from()` in core/std
As mentioned in https://github.com/rust-lang/rust/pull/96979#discussion_r1379502413
Specifically, when an override doesn't just forward to an inner type, document the behavior and that it's preferred over simply assigning a clone of source. Also, change instances where the second parameter is "other" to "source".
I reused some of the wording over and over for similar impls, but I'm not sure that the wording is actually *good*. Would appreciate feedback about that.
Also, now some of these seem to provide pretty specific guarantees about behavior (e.g. will reuse the exact same allocation iff the len is the same), but I was basing it off of the docs for [`Box::clone_from`](https://doc.rust-lang.org/1.75.0/std/boxed/struct.Box.html#method.clone_from-1) - I'm not sure if providing those strong guarantees is actually good or not.