Dir: fix fallback impl for remove_dir
This completely ignored the `self` parameter...
r? @Mark-Simulacrum
Cc @Qelxiros please check your other PRs to ensure we don't have this mistake more often
Windows: don't error if `access_mode` is set on `OpenOptions`
In [RFC 1252] it was decided to artificially restrict the combination of `File` access modes and creation modes for the sake of cross-platform compatibility. This is tested in [`library/std/src/fs/tests.rs`]. As the RFC says, using platform specific function should allow overriding this.
On Windows, [`access_mode`] does indeed override `read`, `write` and `append`. However currently `OpenOptions` can still error if you don't use `read`, `write` or `append`. For example:
```rust
use std::os::windows::fs::OpenOptionsExt;
File::options()
.create_new(true)
.write(true) // useless except it prevents std from erroring
.access_mode(0)
```
This PR makes it so you don't need the misleading `write(true)`.
I also cleaned up the error handling for the access mode a bit. It was unnecessarily split between two functions.
[RFC 1252]: https://rust-lang.github.io/rfcs/1252-open-options.html#combination-of-access-modes-and-creation-modes
[`library/std/src/fs/tests.rs`]: 420ed2a0c3/library/std/src/fs/tests.rs (L1517)
[`access_mode`]: https://doc.rust-lang.org/stable/std/os/windows/fs/trait.OpenOptionsExt.html#tymethod.access_mode
std: fix unix socket address panic on a full sun_path
linux reports an address length one byte past sockaddr_un when the path fills sun_path without a NUL, which made address() slice out of bounds since e96993c68f. cap the length at the size of sockaddr_un.
add Dir::try_clone
There's no `try_clone` listed on https://github.com/rust-lang/rust/issues/120426 but I assume that's a standard operation for all kinds of file descriptors?
Cc @the8472 @ChrisDenton
Add .seek_read_exact(), .seek_write_all() to std::os::windows::fs::FileExt
Tracking issue: https://github.com/rust-lang/rust/issues/162868
This adds `.seek_read_exact()` to `std::os::windows::fs::FileExt`, an exact port of `read_exact_at()` for `std::os::unix::fs::FileExt`.
And it adds `.seek_write_all()` to `std::os::windows::fs::FileExt`, an exact port of `write_all_at()` for `std::os::unix::fs::FileExt`.
Finally, it adds six tests.
First there is a smoke test for `seek_read_exact()`, `seek_write_all()`, an exact port of the test for the `.seek_read()`, `.seek_write()` methods. This is to make sure we are getting the same pass-through behavior through the lens of established tests.
Then there are five tests for the `windows::fs::FileExt` trait itself, covering all `seek_read_exact()`, `seek_write_all()` corner cases except `io::ErrorKind::Interrupted` (advise welcome on that one). These tests use mock implementations of the traits `seek_read()` and `seek_write()` methods.
No LLMs were used in writing this PR.
* First pass at windows::fs::FileExt.seek_read_exact()
* First pass at windows::fs::FileExt.seek_write_all()
* Fix function signature in seek_read_exact(), duh
* First pass at tests for .seek_read_exact(), seek_write_all()
* Whitespace fix
* Use hypothetical seek_read_exact_seek_write_all feature also for .seek_read_exact()
* Tracking issues 162868
* Oops, fix seek_write_all() doc example, was using write_all_at() still
* Add mocked test for windows FileExt trait
* Spelling fixes
* Expand test for windows FileExt trait to include almost all scenarios
* Split three tests out of file_test_windows_fileext_trait()
* Remove old versions of those 3 tests
* Split remaining file_test_windows_fileext_trait() into case 4, 5
* More test cleanup, always test expected_offset where possible
* Test read first for consistency
* Use same doctsring examples as seek_read(), seek_write()
* Missing period
* Oops: actually call _exact(), _all() methods in case 2, 3
* Add missing seek_read_exact_seek_write_all feature flags in doc examples
Add performance notes for the floating-point round method
This update has revised the documentation for f32::round and f64::round, stating that round_ties_even typically offers better performance on most hardware platforms, and reminding readers that the rounding rules at the midpoint are different for the two methods. This update addresses the unfinished documentation task in issue rust-lang/rust#55107.
Stabilize CommandExt::show_window
Stabilize `std::os::windows::process::CommandExt::show_window`.
The final comment period of rust-lang/rust#127544 was completed.
https://github.com/rust-lang/rust/issues/127544#issuecomment-4697341189
I have been using this function for 2 years. I want to use this function on stable Rust.
So, I open a pull request.
`windows_process_extensions_show_window` feature appears only in the location I modified.
```
> rg 'windows_process_extensions_show_window'
src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs
17165: label: "windows_process_extensions_show_window",
17166: description: r##"# `windows_process_extensions_show_window`
library/std/src/os/windows/process.rs
191: #[stable(feature = "windows_process_extensions_show_window", since = "CURRENT_RUSTC_VERSION")]
```
LLM disclosure: I asked an ChatGPT for the steps and manually created a commit. I handled the searching for the code to modify (using `rg`) and the actual editing (using `nano`) myself.
Add `must_use` lint to `ExitCode`
An [`ExitCode`](https://doc.rust-lang.org/nightly/std/process/struct.ExitCode.html) is intended to be returned from `main` (or used in other ways of terminating a process). It's also a `Result` like type in that it has success and error values. It's *probably* a mistake if it's ignored but if not it makes sense to require users to explicitly acknowledge that ignoring it is intentional (e.g. with `let _ = ...`).
Stabilize `feature(trim_prefix_suffix)` (`{str, [T], Path}::trim_prefix` and `{str, [T]}::trim_suffix`)
Closesrust-lang/rust#142312 (tracking issue)
FCP completed [here](https://github.com/rust-lang/rust/issues/142312#issuecomment-4920020056). There was discussion during FCP about a possibly adding `strip_circumfix`, but that wasn't mentioned as blocking.
r? libs-api
Stabilize `windows_process_extensions_main_thread_handle`
I propose we stabilize the library feature `windows_process_extensions_main_thread_handle` (tracking issue https://github.com/rust-lang/rust/issues/96723).
## Stabilization Report
### Implementation History
This feature was added in https://github.com/rust-lang/rust/pull/96725, and not changed since.
### API Summary
```rust
// std::os::windows::process
pub trait ChildExt: Sealed {
fn main_thread_handle(&self) -> BorrowedHandle<'_>;
}
```
This method gives access to the handle to the main thread of a spawned child process on Windows. It is not possible to get after spawning using documented APIs, and it's useful for example for resuming a process that started as suspended (while it's possible to enumerate all threads and resume them all, that's slower and more complicated).
### Experience Report
My personal reason for this is wanting to use it for this case exactly (resuming a suspended process) in rust-analyzer, see https://github.com/rust-lang/rust-analyzer/pull/22763#issuecomment-4997862266. Other people seem to want this for the same reason as well (for example in the tracking issue). [Searching GitHub for `.main_thread_handle()` gives 269 results](https://github.com/search?q=%22.main_thread_handle%28%29%22+language%3Arust&type=code). Some are for resuming processes, but there are also others - for example, [injecting a DLL](a1e26958d8/crates/launcher/src/game.rs (L98)). I [even found a project](3684d2dc84/datasets/repositories/repo_020_hyperfine/code/src/timer/windows_timer.rs (L71)) that gates using this method behind a feature, and if it's not set, uses an undocumented Windows API instead.
### Unresolved Questions
There are two unresolved questions:
- The naming - should it be the "main thread" or the "primary thread". Microsoft's documentation refers to it as the "primary thread", but our own docs mention "main thread" (https://doc.rust-lang.org/std/thread/index.html), as stated in https://github.com/rust-lang/rust/issues/96723#issuecomment-1869909355. I left it as "main thread".
- Should it return `Option<BorrowedHandle<'_>>`? This will enable conversion from a handle to `std::process::Child` (such conversion is not supported currently). Such conversion is not supported for any OS currently though, and making this function returning `Option` will complicate code using it, so I chose to not do that.
r? libs-api
Windows: cache the stdio write mode for the duration of a lock session
On Windows, every write to stdout/stderr calls `GetStdHandle` and `GetConsoleMode` (and `GetConsoleOutputCP` for consoles) to decide how to write. For bulk writes through a locked handle that is most of the work; rust-lang/rust#154071 measured 14% of CPU time in `is_console` alone.
This caches the handle and the console verdict in the sys-level `Stdout`/`Stderr` and re-queries when a new lock session begins, as [suggested in the issue](https://github.com/rust-lang/rust/issues/154071#issuecomment-4092410339). Holding a `StdoutLock` pins the stream; unlocked writes acquire the lock per call, so they re-query per write exactly as before, and `SetStdHandle` calls made between lock sessions keep working (the rust-lang/rust#40490 behavior is preserved).
Numbers from the issue's workload shape (16 KiB chunks to `NUL`, 4 GiB total, Windows 11):
| mode | before | after |
|---|---|---|
| `stdout().lock()` | 0.478 s (8,561 MiB/s) | 0.120 s (34,350 MiB/s) |
| unlocked | 0.467 s | 0.293 s |
The unlocked case also improves because one implicit lock session can contain several sys-level writes when `LineWriter` splits a chunk at newlines.
The console path cannot run in CI, so it was verified under a pseudoconsole: several writes through one lock session on a CP437 console came through `WriteConsoleW` intact (non-ASCII included), and after `SetConsoleOutputCP` plus a new lock session the refresh picked up the change.
The `refresh` hook is a small `#[cfg(windows)]` shim on `StdoutRaw`/`StderrRaw`; happy to change it to a method on every platform's sys type instead if that is preferred.
Fixesrust-lang/rust#154071
Use File::*lock*() in rustc_data_structures::flock when possible
And only fallback to `fcntl(F_SETLK)` on Unix when `flock()` is not supported. `flock()` is a lot more sane than `fcntl(F_SETLK)` as it is fd scoped rather than process-scoped and reentrant. `fcntl(F_SETLK)` risks multiple instances of rustc inside the same process acquiring a lock on the same file even when an exclusive lock is requested. Using `File::*lock*()` also allows removing a fair amount of platform specific code for the file locking.
Fixes https://github.com/rust-lang/rust/issues/161361
* Windows: cache the stdio write mode for the duration of a lock session
Every write to stdout/stderr re-queried GetStdHandle and GetConsoleMode
(and GetConsoleOutputCP for consoles) to decide how to write, which
dominates bulk writes through a locked handle. Cache the handle and the
console verdict in the sys-level Stdout/Stderr and re-query when a new
lock session begins, so SetStdHandle calls made between lock sessions
keep working.
* Gate the stdio lock-session refresh to Windows
On targets where refresh is a no-op, lock() now compiles to exactly
the code it had before, instead of relying on the borrow-flag dance
optimizing out.
Fix `path_trailing_sep` methods for Windows verbatim paths
Normally on Windows the path separator is either `\` or `/` but for verbatim paths it is only `\`. Currently the unstable `path_trailing_sep` methods (rust-lang/rust#142503) do not take that into account and just use the general `is_sep_byte` method.
This PR changes it to use the internal `Components::is_sep(self, b)` method that takes into account verbatim paths.
Most of them don't need to be public, but there are scenarios where
thing is private on one platform but public on the other, so having a
lint on all the time gets complicated.
Added #![warn(unreachable_pub)] in library/std/src/lib.rs
Added #[allow(unreachable_pub)] on top of std::os and std::sys specifically.
linux reports an address length one byte past sockaddr_un when the path
fills sun_path without a NUL, which made address() slice out of bounds
since e96993c68f. cap the length at the size of sockaddr_un.
Update `windows-bindgen` to 0.100.0
This release represents a major change in the way bindings are generated. See https://github.com/microsoft/windows-rs/issues/4867 for details.
In short, it now more directly follows the C headers. For the standard library's purposes this is mostly reflected in relatively minor type changes or with some `const` pointers becoming `mut`.
There is however one big change that affects a lot of types. In the headers there are a lot of `#define`s like this:
```c
#define GENERIC_READ (0x80000000L)
#define GENERIC_WRITE (0x40000000L)
```
These are constants for the access mode. In this case they're explicitly declared as `L` (aka signed long) integer types (in other cases there's no type at all). However, this conflicts with how access mode constants are actually used. E.g., see `CreateFileW`:
```c
WINBASEAPI
HANDLE
WINAPI
CreateFileW(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
```
Here `dwDesiredAccess` is a `DWORD`, which in rust equates to `u32`. The constant being signed but the usage being unsigned is not a problem for C/C++. They will happily convert between types at the drop of a hat. Rust however is stricter, as you know.
The old metadata used by `windows-bindgen` tried to try to fixup this mismatch but the new one goes strictly by what can be inferred from the headers. The hope in the future is that the headers themselves will be updated so better bindings can be directly derived from them.
Mingw used to have an incorrect import library for the synchronization functions `WaitOnAddress`, `WakeByAddressSingle` and `WakeByAddressAll`. This was fixed a long time ago and our windows-gnu targets require a much newer mingw in any case.
Update wasip2/wasip3 libstd crate dependencies
Picks up the latest version of the `wit-bindgen` dependency which has improved compatibility for `wasm32-wasip3`.
Fix soundness issues in std::sys::pal::sgx::waitqueue::unsafe_list
Replace invalid uses of references in `std::sys::pal::sgx::waitqueue::unsafe_list` internals with raw pointers. I tried to keep the code structure the same as much as possible. In addition to the use of references flagged in the original issue, it turns out the head/tail (raw) pointer stored in the linked list caused provenance issues in miri. Switched to using UnsafePinned for that.
PR organization:
* Commit 1: Main soundness fix.
* Commit 2: Use pinning in the `pub(crate)` API for UnsafeList. This code predates pinning in Rust. I believe this change isn't strictly necessary as I believe it's valid to document pinning requirements in the unsafe methods on UnsafeList. However, I felt it's better to be explicit about this now that pinning is available in the language.
* Commit 3: Move UnsafeList to a platform-agnostic location so miri can be run on the test suite. This also adds some tests.
This PR was developed with Claude Fable 5 through extensive interactive use, where I directed a detailed plan for making the changes needed for this fix. My input includes keeping the structure the same and the new internal abstraction for dealing with raw pointers. I'm not familiar with miri, I used Claude to test the changes with miri. It said the test suite was failing before the changes (both stacked borrows and tree borrows) but passing after. The additional tests developed this way have been added in the third commit. The head/tail pointer provenance issue was found with Claude. I thoroughly reviewed all the code, including comments, and made manual changes/deletions where necessary/appropriate. The PR description was written by me.
r? @nia-e
Fixesrust-lang/rust#114581Fixesrust-lang/rust#160603Fixesrust-lang/rust#161060
Supersedes rust-lang/rust#160641