Replace links to `github.com/rust-lang/rfcs` with links to the Rust RFC Book
I noticed many error codes link to Rust RFCs via the [source GitHub `.md` files](https://github.com/rust-lang/rfcs/tree/master/text) instead of linking to the [RFC Book](https://rust-lang.github.io/rfcs/). This PR updates those links to point to the RFC book - I also updated any other links to RFCs in the repo (not including subtrees) while I was at it.
read(true) was chained onto custom_flags(O_NOFOLLOW) inside a cfg block that
excludes those two targets, so their OpenOptions had no access mode set and
open() returned EINVAL before any chmod happened. Neither target has an
fchmodat arm either, so set_permissions_nofollow could never succeed there.
std::sys::pal::sgx: fix mismatched alloc/free alignment
### Why the PR?
I've got a local `miri` branch that's able to test `x86_64-fortanix-unknown-sgx`, so I can get better assurance about our enclaves. It's now complaining about a bunch of stuff in std 😅
### Context
1. `x86_64-fortanix-unknown-sgx` enclaves can request the untrusted host enclave runner to allocate/free memory in userspace and get a pointer to it in return.
2. There's a userspace/enclave space memory split for `x86_64-fortanix-unknown-sgx` enclaves. It's a bit like the userspace/kernel space split, where the kernel doesn't trust pointers from userspace and is very paranoid about copying data to/from userspace.
### Problem
In the enclave, `User::new_uninit_bytes` and `User::drop` are requesting the host to alloc/dealloc memory with potentially mismatched alignment, as the enclave side is unconditionally over-aligning on allocation but not doing the same on free.
- Ex: `User::<ByteBuffer>` -> `alloc(_, align=8)` -> `drop()` -> `free(_, align=1)`
See: <https://github.com/rust-lang/rust/blob/main/library/std/src/sys/pal/sgx/abi/usercalls/alloc.rs>
```rust
// Enclave-side
impl<T: ?Sized> User<T>
where
T: UserSafe,
{
// This function returns memory that is practically uninitialized, but is
// not considered "unspecified" or "undefined" for purposes of an
// optimizing compiler. This is achieved by returning a pointer from
// from outside as obtained by `super::alloc`.
fn new_uninit_bytes(size: usize) -> Self {
unsafe {
// Mustn't call alloc with size 0.
let ptr = if size > 0 {
// `copy_to_userspace` is more efficient when data is 8-byte aligned
let alignment = cmp::max(T::align_of(), 8); // <------------------------- HERE
rtunwrap!(Ok, super::alloc(size, alignment)) as _
} else {
T::align_of() as _ // dangling pointer ok for size 0
};
if let Ok(v) = crate::panic::catch_unwind(|| T::from_raw_sized(ptr, size)) {
User(NonNull::new_userref(v))
} else {
rtabort!("Got invalid pointer from alloc() usercall")
}
}
}
// ...
}
// ...
impl<T: ?Sized> Drop for User<T>
where
T: UserSafe,
{
fn drop(&mut self) {
unsafe {
let ptr = (*self.0.as_ptr()).0.get();
// vvvvvvvvvvvvv------------------ HERE
super::free(ptr as _, size_of_val(&mut *ptr), T::align_of());
}
}
}
```
This min. alignment optimization was introduced in 6f7d1937e2. See below for more details on why.
The two usercalls, `super::alloc` and `super::free`, are eventually handled by the host runner. They just delegate to the `System` allocator:
See: <https://github.com/fortanix/rust-sgx/blob/master/intel-sgx/enclave-runner-sgx/src/usercalls/mod.rs>
```rust
// Host-side / userspace
impl<'tcs> IOHandlerInput<'tcs> {
// ...
#[inline(always)]
fn alloc(&self, size: usize, alignment: usize) -> IoResult<*mut u8> {
unsafe {
// vvvvvvvvv--------------- UNCHANGED
let layout = Layout::from_size_align(size, alignment)
.map_err(|_| IoErrorKind::InvalidInput)?;
if layout.size() == 0 {
return Err(IoErrorKind::InvalidInput.into());
}
let ptr = System.alloc(layout);
if ptr.is_null() {
Err(IoErrorKind::Other.into())
} else {
Ok(ptr)
}
}
}
#[inline(always)]
fn free(&self, ptr: *mut u8, size: usize, alignment: usize) -> IoResult<()> {
unsafe {
// vvvvvvvvv--------------- UNCHANGED
let layout = Layout::from_size_align(size, alignment)
.map_err(|_| IoErrorKind::InvalidInput)?;
if size == 0 {
return Ok(());
}
Ok(System.dealloc(ptr, layout))
}
}
// ...
}
```
It also appears that `enclave-runner-sgx` assumes that there's no `#[global_allocator]` override (<https://github.com/fortanix/rust-sgx/blob/master/intel-sgx/enclave-runner-sgx/src/usercalls/interface.rs#L333>).
For most enclave hosts running stock x86_64-unknown-linux-gnu (glibc malloc), I don't believe this mismatch is currently an issue, since posix `free` ignores the alignment anyway.
If you did swap in jemalloc, which does care about the dealloc alignment, then something would definitely go wrong elsewhere, as the you'd have mismatched allocators (`System` above vs `Box<_>`/`Vec<_>` using `Global`).
### Solutions
It's not clear that we can round-up the alignment on `free`, since `User::from_raw` exists, and there's various places that call it outside std.
We should probably just remove the in-enclave min. alignment until we come up with a more satisfactory solution. My guess is that the right place to do the min. alignment optimization is on enclave-runner-sgx side: <https://github.com/fortanix/rust-sgx/blob/master/intel-sgx/enclave-runner-sgx/src/usercalls/mod.rs#L1596> and other places that hand memory to the SGX enclave.
### Why over-align in the first place?
The min. alignment exists for performance reasons (see: `copy_from_userspace`). It's highly preferable if all memory copied from userspace is at least 8 byte aligned, otherwise we have to fallback to a super slow copy routine for the unaligned prefix (and suffix).
`User::new_uninit_bytes` and `User::drop` are asking the host to
alloc/dealloc memory with potentially mismatched alignment, as the
enclave side is unconditionally over-aligning on allocation but not
doing the same on free.
- Ex: `User::<ByteBuffer>` -> `alloc(_, align=8)` -> `drop()` -> `free(_, align=1)`
For most hosts running stock x86_64-linux + glibc malloc, I don't
believe this mismatch is an issue, since posix `free` ignores the
alignment anyway. My guess is that if you're using jemalloc, which does
care about the dealloc alignment, then something _might_ go wrong.
It's also not clear that we can just round-up the alignment on `free`,
since `User::from_raw` exists, and there's various places that call it
outside std.
We should probably just remove the min. alignment until we come up with
a more satisfactory solution. My guess is that the right place to do the
min. alignment optimization is in the host-side enclave-runner:
<be93e7abe9/intel-sgx/enclave-runner-sgx/src/usercalls/mod.rs (L1596)>
and other places that hand memory to the SGX enclave.
NB. The min. alignment exists for performance reasons (see:
`copy_from_userspace`). It's highly preferable if all memory copied from
userspace is at least 8 byte aligned, otherwise we have to fallback to a
super slow copy routine for the unaligned prefix (and suffix).
Windows: add fallback if `canonicalize` fails
This attempts a partial workaround for issues such as: https://github.com/rust-lang/rust/issues/59392, https://github.com/rust-lang/rust/issues/79449, https://github.com/rust-lang/rust/issues/59107, https://github.com/rust-lang/rust/issues/54875, https://github.com/rust-lang/rust/issues/52440, https://github.com/rust-lang/rust/issues/52377, https://github.com/rust-lang/rust/issues/48249, https://github.com/rust-lang/rust/issues/74327, https://github.com/rust-lang/rust/issues/55812
This may require a bit of explanation depending on how familiar you are with Windows paths, I'll try to keep it brief. The short version is that the above issues are cases where third party devices don't integrate with the system sufficiently so Windows isn't aware of the canonical drive for a particular path, causing our `canonicalize` function to fail. This PR works around it by manually search for the drive letter that corresponds to the root of the path. This only works in cases where there is a drive letter assigned but that is the majority of cases. It won't work when the device is only mounted to a directory in another filesystem or isn't mounted at all.
To explain the implementation of this PR you should be aware that Windows on Windows NT is more like WINE on Linux then many people realise. You have a kernel (NT) and then you have an implementation of the Win32 APIs on top (this is why `kernel32.dll` is nothing to do with the real kernel, it's like an implementation of Win95's kernel API on top of another OS). Admittedly the boundaries have become fuzzier over the years but there still remains a clear distinction between the Win32 API and the NT kernel API in many places.
Paths are one place where this distinction is made clear. You have the familiar Win32 paths like `C:\path\to\file` that date back to the time of DOS. And then you have the low-level NT kernel paths that look like `\Device\HarddiskVolume6\path\to\file` (which aren't really meant to be user-visible). To bridge the gap, the NT namespace has a special `??` directory containing mappings (i.e. symlinks) from drives like `C:` to paths like `\Device\HarddiskVolume6`. In that way translating between Win32 and NT paths is made simpler as you can replace `C:` with `\??\C:` and it'll get resolved to the right path and vice versa (the actual translation from win32 to NT is more complicated but I've already spent too many words on this).
So back to canonicalisation. Resolving the canonical NT path should always succeed. The problem comes when mapping that to a Win32 drive path. When the drive is managed by the system then when resolving paths it knows which drive to pick. However, if the drive mapping is added manually then it doesn't.
So the way to workaround this is to manually look at the drive mappings and see which one is the root of the NT path we have.
std: don't reference `libc::O_NOFOLLOW` on VxWorks in `set_perm_nofollow`
`set_permissions_nofollow` was consolidated into `sys/fs/unix.rs::set_perm_nofollow` by rust-lang/rust#160170, which dropped the `not(target_os = "vxworks")` guard the previous `sys/fs/mod.rs` implementation carried. VxWorks' libc defines no `O_NOFOLLOW` (the platform's `<sys/fcntlcom.h>` stops at `O_CLOEXEC`, and `rust-lang/libc` correctly does not bind it for `vxworks`), so building `std` for `x86_64-wrs-vxworks` now fails:
```
error[E0425]: cannot find value `O_NOFOLLOW` in crate `libc`
--> library/std/src/sys/fs/unix.rs:1916
|
| options.read(true).custom_flags(libc::O_NOFOLLOW);
| ^^^^^^^^^^ not found in `libc`
```
`x86_64-wrs-vxworks` is tier 3 and isn't built in CI, so this wasn't caught. `set_perm_nofollow` is the only `O_NOFOLLOW` reference compiled for VxWorks — the `remove_dir_all` "modern" path already lists `vxworks` in its fallback set, and the remaining occurrences are a doc example and comments.
Unlike ESP-IDF and Horizon (which skip `O_NOFOLLOW` because their filesystems have no symbolic links), VxWorks *does* have symlinks, so it can't just drop `O_NOFOLLOW` and follow the link silently. This returns `ErrorKind::Unsupported`, matching the existing Android stub.
## `Unsupported` is the platform-correct result
Verified on-target against the shipped VxWorks 7 SDK (`wrsdk-vxworks7-qemu-1.17.0`, the QEMU BSP). VxWorks has no way to express a no-follow permission change:
- No `O_NOFOLLOW`. The only related flag is `O_NOLINK` ("open the symlink itself"), which is different semantics and not what the `open` + `fchmod` path wants.
- `fchmodat` *is* provided — by the UTILS_UNIX component in `libunix`, not core `libc` — and `AT_SYMLINK_NOFOLLOW` is defined as `0x100`. But the shipped `libunix.so` **rejects the flag with `ENOTSUP`**:
```asm
0000000000009300 <fchmodat>: ; (dirfd=edi, path=rsi, mode=edx, flag=ecx)
cmpl $0x100,-0x18(%rbp) ; flag == AT_SYMLINK_NOFOLLOW ?
jne 9340 <fchmodat+0x40>
mov $0x23,%edi ; errno = 0x23 (35 = ENOTSUP)
call errnoSet
movl $0xffffffff,-0x4(%rbp) ; return -1
...
9340: ; flag == 0
call taskSafe
... atCatPath(dirfd, path)
call chmod ; plain chmod -> follows the symlink
```
So `fchmodat(.., AT_SYMLINK_NOFOLLOW)` returns `-1`/`ENOTSUP`, and `flag == 0` degrades to `chmod`, which follows symlinks. A `fchmodat`-based implementation is not viable on this release — the platform's own `fchmodat` reports `ENOTSUP` for exactly this request, which is why `Unsupported` is correct rather than merely conservative. cc @biabbas @hax0kartik
## Build verification
On `1.100.0-nightly (908501772 2026-08-30)` + `rust-src` (stock `libc` 0.2.189):
- Before: `cargo +nightly build -Zbuild-std=std,panic_abort --target x86_64-wrs-vxworks` fails with the E0425 above (1 error).
- After this patch: the same command finishes successfully.
std: improve safety documentation in UNIX stack overflow code
The UNIX stack overflow handling code was only partially documented, and applied `#![forbid(unsafe_op_in_unsafe_fn)]` inconsistently. Also, the existing safety documentation wasn't very clear on the assumptions made by `std` and the reasoning behind those assumptions. I've tried to rectify all that here by adding some `unsafe`, removing some `unsafe` and writing a lot of comments. There are no functional changes however, I'll get started on those once this is merged.
Revert "Use `drop_guard` in some places in {core,alloc,std}"
cc @panstromek @GrigorenkoPV
Reverts this PR due to perf issues, so that a fix can be verified to not affect perf. Apologies for not initially running perf; kinda tunnel-visioned "this just does the same thing" without considering the changes from non-generic functions to generic closures.
Change some `Infallible` to `!` in std
I believe this desirable since we recommend `!` over `Infallible`, so std follows its own advice. Most changes are to unstable features, but not all. Similar changes in compiler have to wait for a bootstrap update.
Make sin, cos, exp, exp2, log, log2, log10 generic
Rebased and smaller version of rust-lang/rust#153934
Following `fabs`, make the `sin`, `cos`, `exp`, `exp2`, `log`, `log2` and `log10` intrinsics generic over the float type, rather than having four variants per float type.
The first two commits are purely stylistic:
- reorganised Cranelift code to make following changes simpler
- moved a misplaced comment in `compiler/rustc_codegen_llvm/src/intrinsic.rs` that caused `x fmt` to give up
The last commit actually makes them generic! Most code is a bit simpler, ~~and this will also hopefully simplify adding support for these intrinsics for the future [`bf16` type](https://github.com/rust-lang/rust/pull/160859)~~ :)
Unfortunately both GCC and Cranelift backend changes are a bit churny. Their code is a bit, opaque, to put it kindly, and I didn't want to refactor those here.
r? @folkertdev
cc @RalfJung
VxWorks' libc defines no `O_NOFOLLOW`, so building std for
x86_64-wrs-vxworks stopped compiling once `set_perm_nofollow` was
consolidated into `sys/fs/unix.rs` without a vxworks guard. VxWorks also
has no way to express a no-follow permission change: its `fchmodat`
rejects `AT_SYMLINK_NOFOLLOW` with `ENOTSUP`. Return `Unsupported`,
matching the existing Android stub.
Fix a compile error on the ESP-IDF target
PR rust-lang/rust#160848 accidentally broke the Tier-3 ESP-IDF target by leaving out one reference to `attr.as_ptr()` which should've been changed to `attr.get()`.
This PR does the absolute minimum to restore correct behavior for the ESP-IDF target (and Nuttx).
CC
@joboet
@nia-e
Use better generic type parameter names for `Extend` and `FromIterator`
Change
```rs
pub trait Extend<A> {
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T);
…
}
```
to
```rs
pub trait Extend<T> {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I);
…
}
```
to be more consistent with common use of `T` as the item type in containers, and their `Extend` impls; and use `I` as the name for the `IntoIterator` type.
also do the basically the same thing for `FromIterator<A>`→`FromIterator<T>` as well
cases of these parameters in trait impls for the abovementioned traits.
These changes obviously don't change/break behavior of the traits and its users, but the improve the way the documentation of the traits renders (the improvement is the more sensible and more consistent names for the parameters). The only downside I'm aware of (besides that this is touching quite a few files..) is that this does affect some link anchor names in *some* cases. E.g.
```diff
- impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
+ impl<T, V: FromIterator<T>> FromIterator<Option<T>> for Option<V> {
```
would mean that [doc.rust-lang.org/core/iter/trait.FromIterator.html#impl-FromIterator<Option\<A>>-for-Option\<V>](https://doc.rust-lang.org/core/iter/trait.FromIterator.html#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E) no longer works, as it changes `…#impl-FromIterator<Option<A>>-for-Option<V>` to `…#impl-FromIterator<Option<T>>-for-Option<V>`
Use `drop_guard` in some places in {core,alloc,std}
- Tracking issue: rust-lang/rust#144426
- Will conflict with rust-lang/rust#161520
- rust-lang/rust#161550 would also be cool occasionally
Didn't touch the places where manual `impl Drop`s had `#[inline]` on their `fn drop` or where the guard type had other `impl`s beside `Drop` and/or was named a lot.
No LLMs used, only pure human slop.
Handle multiple action records in EH personality function
LSDA encodes actions are a linked list, we currently only decode the first one. Action records are used for catching specific exception types and for exception specifications, and none of these are present in Rust. However we can still have of multiple of them being present due to LLVM inlining. When this happens, "Catch" is the correct action to execute.
We haven't had issues with this because LLVM orders cleanup record last; however GCC doesn't use the same order, so we do need to explicitly handle this case to support both LLVM and GCC codegen.
See https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/Possible.20bug.20in.20unwind.20function.20in.20std/with/615883393
Refactored docs for `std::fs::set_permissions_nofollow` + fix BSD-based systems to use fchmodat with AT_SYMLINK_NOFOLLOW flag
Original Tracking Issue: https://github.com/rust-lang/rust/issues/141607
Fixes mistake made in rust-lang/rust#158168
This PR refactors documentations for `std::fs::set_permissions_nofollow` and fixes BSD-based systems + Android to use `fchmodat` with `AT_SYMLINK_NOFOLLOW` flag (instead of no flag set) and refactors all other platforms to defer to `OpenOptions` with `O_NOFOLLOW` behavior.
r? @clarfonthey
Since they looked at the original `set_permissions_nofollow` PR I made
cc @RalfJung
std::sys::sgx::tls: fix TLS destructor pointer provenance
Storing the TLS entry destructor as an `AtomicUsize` loses the pointer provenance and makes miri cry :'(
Instead, store an `AtomicPtr<()>`. I also find the SAFETY proof more convincing when the transmute from `*mut ()` to `Option<unsafe extern "C" fn(*mut u8)>` is exactly mirrored.
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2024&gist=c6da201f269c5f3115039177a43bcdd4
```
Compiling playground v0.0.1 (/playground)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.70s
Running `/playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/bin/cargo-miri runner target/miri/x86_64-unknown-linux-gnu/debug/playground`
error: Undefined Behavior: pointer not dereferenceable: pointer must point to some allocation, but got 0x26b51[noalloc] which is a dangling pointer (it has no provenance)
--> src/tls-bad.rs:73:30
|
73 | unsafe { dtor(value) }
| ^^^^^^^^^^^ Undefined Behavior occurred here
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
= note: stack backtrace:
0: <tls::ActiveTls<'_> as std::ops::Drop>::drop
at src/tls-bad.rs:73:30: 73:41
1: std::ptr::drop_glue::<tls::ActiveTls<'_>> - shim(Some(tls::ActiveTls<'_>))
at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:848:1: 850:25
2: main
at src/main.rs:50:1: 50:2
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
error: aborting due to 1 previous error
```
Windows: document that `normalize_lexically` converts `/` to `\`
To be clear, this is the current behaviour and what we want so we should document it.
Tracking issue: rust-lang/rust#134694
std: uefi: fix File::seek returning the EOF sentinel
seek(SeekFrom::End(0)) special-cased the offset to the UEFI 0xFFFFFFFFFFFFFFFF "set position to end of file" sentinel, then returned that value as the new stream position. so seek reported u64::MAX instead of the file size, and the default Seek::stream_len did too. compute the offset from the file size in every End case instead.
std: optimise IO error formatting
The current OS error formatting logic goes through a bit of trouble (the `format!` macro, temporary allocations and unnecessary copying) to create a `String` for `Formatter::write_str`. It's more efficient and arguably simpler to have the formatting logic write into the `Formatter` directly instead.
bind to [::1] instead of 127.0.0.1 in documentation examples for v6 UDP methods
My first contribution towards rust-lang/rust#161832
I think this is reasonable to do despite the ongoing discussion, as it's IPv6-specific methods and likely resulted from copy-pasting the code blocks.
std: avoid aliasing violations when wrapping opaque C types
Fixesrust-lang/rust#160815 (and some other instances of the same problem)
See the new documentation of `COpaque` for a detailed description of the kinds of issues solved by this. In short: creating mutable references to the opaque types from pthread is unsound since some platforms (at least AIX) store an intrinsically list of these types and the creation of the mutable reference (e.g. in the drop glue) invalidates the other pointers to the type.
This doesn't just apply to the internal pthread `Condvar` and `Mutex` abstraction as described in the issue, but also to all other opaque types – nobody is promising us that these are not internally aliased. Hence this PR adds an internal `COpaque` helper type which uses a combination of `UnsafePinned` and `MaybeUninit` to relax all relevant requirements added by Rust's operational semantics.
CC @RalfJung I'd love to hear your opinion on this
r? libs
seek(SeekFrom::End(0)) special-cased the offset to the UEFI
0xFFFFFFFFFFFFFFFF "set position to end of file" sentinel, then returned
that value as the new stream position. so seek reported u64::MAX instead
of the file size, and the default Seek::stream_len did too. compute the
offset from the file size in every End case instead.
UEFI status codes are usize-wide with the high bit set for errors
(e.g. DEVICE_ERROR is 0x8000000000000007 on 64-bit). the previous
`as i32` cast silently dropped the upper bits, losing all error
information. stripping the error high bit to extract the error number
and negating it, so errors (negative) are distinguishable from
success/warning codes (non-negative).