Enable Non-determinism of float operations in Miri and change std tests
Links to [#4208](https://github.com/rust-lang/miri/issues/4208) and [#3555](https://github.com/rust-lang/miri/issues/3555) in Miri.
Non-determinism of floating point operations was disabled in rust-lang/rust#137594 because it breaks the tests and doc-tests in core/coretests and std. This PR enables some of them.
This pr includes the following changes:
- Enables the float non-determinism but with a lower relative error of 4ULP instead of 16ULP
- These operations now have a fixed output based on the C23 standard, except the pow operations, this is tracked in [#4286](https://github.com/rust-lang/miri/issues/4286#issue-3010677983)
- Changes tests that made incorrect assumptions about the operations, not to make that assumption anymore (from `assert_eq!` to `assert_approx_eq!`.
- Changed the doctests of the stdlib of these operations to compare against fixed constants instead of `f*::EPSILON`, which now succeed with Miri and `-Zmiri-many-seeds`
- Added a constant `APPROX_DELTA` in `std/tests/floats/f32.rs` which is used for approximation tests, but with a different value when run in Miri. This is to make these tests succeed.
- Added tests in the float tests of Miri to test the C23 behaviour.
Fixes https://github.com/rust-lang/miri/issues/4208
De-duplicate f16 & f128 doctest attributes
Now that rustdoc supports `#[doc(test(attr(...)))]` at every level, thanks to https://github.com/rust-lang/rust/pull/140560, we can de-duplicate the f16 & f128 doctest attributes.
Unfortunately we can de-duplicate the `cfg`s attribute as rustdoc would complain about missing `main`, but it's already much better than before.
Addresses https://github.com/rust-lang/rust/pull/140323/files#r2062702761
r? `@tgross35`
Stabilize `tcp_quickack`
to stabilise the quickack part for now, tcp_deferaccept had been added at a later stage.
The related API calls are the following
```rust
// std::os::linux::net
// sealed trait, implemented for std::net::TcpStream
pub trait TcpStreamExt: Sealed{
fn quickack(&self) -> io::Result<bool>;
fn set_quickack(&self, quickack: bool) -> io::Result<()>;
}
```
Closes: https://github.com/rust-lang/rust/issues/96256
Avoid a gratuitous 10s wait in a stress test
`stress_recv_timeout_two_threads`, in the mpmc and mpsc testsuites, is a stress test of the `recv_timeout` function. This test processes and ignores timeouts, and just ensures that every sent value gets received. As such, the exact length of the timeouts is not critical, only that the timeout and sleep durations ensure that at least one timeout occurred.
The current tests have 100 iterations, half of which sleep for 200ms, causing the test to take 10s. This represents around 2/3rds of the *total* runtime of the `library/std` testsuite, and is the only standard library test that takes more than a second.
Reduce this to 50 iterations where half of them sleep for 10ms, causing the test to take 0.25s.
Add a check that at least one timeout occurred.
`stress_recv_timeout_two_threads`, in the mpmc and mpsc testsuites,
is a stress test of the `recv_timeout` function. This test processes and
ignores timeouts, and just ensures that every sent value gets received.
As such, the exact length of the timeouts is not critical, only that
the timeout and sleep durations ensure that at least one timeout
occurred.
The current tests have 100 iterations, half of which sleep for 200ms,
causing the test to take 10s. This represents around 2/3rds of the
*total* runtime of the `library/std` testsuite.
Reduce this to 50 iterations where half of them sleep for 10ms, causing
the test to take 0.25s.
Add a check that at least one timeout occurred.
Many of `std`'s dependency have a dependency on the crates.io
`compiler-builtins` when used with the feature
`rustc-std-workspace-core`. Use a Cargo patch to select the in-tree
version instead.
`compiler-builtins` is also added as a dependency of
`rustc-std-workspace-core` so these crates can remove their crates.io
dependency in the future.
unsafe keyword docs: emphasize that an unsafe fn in a trait does not get to choose its safety contract
Inspired by discussion in https://github.com/rust-lang/rust/issues/139368.
Cc `@hanna-kruppe`
Reexport types from `c_size_t` in `std`
These are unstably available in `core` and should be in `std` too, but are not currently reexported. Resolve this here.
Tracking issue: https://github.com/rust-lang/rust/issues/88345
Fix AIX build
Fixrust-lang/rust#141543.
`getenv` was moved out of this file to `sys::env::getenv` in rust-lang/rust#140143. Replace its usage with `std::env::var_os`, the publicly exposed version. This matches the other usages of the same function in this file.
It uses the file metadata on Unix with a fallback for files incorrectly
reported as zero-sized. It uses `GetFileSizeEx` on Windows.
This reduces the number of syscalls needed for determining the file size
of an open file from 3 to 1.
make `OsString::new` and `PathBuf::new` unstably const
Since #129041, `String::into_bytes` is `const`, which allows making `OsString::new` and `PathBuf::new` unstably const now.
Not sure what the exact process for this is; does it need an ACP?
Remove bootstrap cfgs from library/
These `cfg(bootstrap)` are always false now that rust-lang/rust#119899 has landed, and likewise `cfg(not(bootstrap))` is always true. Therefore, we don't need to wait for the usual stage0 bump to clean these up.
std: abort the process on failure to allocate a TLS key
The panic machinery uses TLS, so panicking if no TLS keys are left can lead to infinite recursion (see https://github.com/rust-lang/rust/issues/140798#issuecomment-2872307377). Rather than having separate logic for the panic count and the thread name, just always abort the process if a TLS key allocation fails. This also has the benefit of aligning the key-based TLS implementation with the documentation, which does not mention that a panic could also occur because of resource exhaustion.
Clarify &mut-methods' docs on sync::OnceLock
Three small changes to the docs of `sync::OnceLock`:
* The docs for `OnceLock::take()` used to [say](https://doc.rust-lang.org/std/sync/struct.OnceLock.html#method.take) "**Safety** is guaranteed by requiring a mutable reference." (emphasis mine). While technically correct, imho its not necessary to even mention safety - as opposed to unsafety - here: Safety never comes up wrt `OnceLock`, as there is (currently) no way to interact with a `OnceLock` in an unsafe way; there are no unsafe methods on `OnceLock`, so there is "safety" guarantee required anywhere. What we simply meant to say is "**Synchronization** is guaranteed...".
* I've add that phrase to the other methods of `OnceLock` which take a `&mut self`, to highlight the fact that having a `&mut OnceLock` guarantees that synchronization with other threads is not required. This is the same as with [`Mutex::get_mut()`](https://doc.rust-lang.org/std/sync/struct.Mutex.html#method.get_mut), [`Cell::get_mut()`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get_mut), and others.
* In that spirit, the half-sentence "or being initialized" was removed from `get_mut()`, as there is no way that the `OnceLock` is being initialized while we are holding `&mut` to it. Probably a copy&paste from `.get()`
Add `const` support for float rounding methods
# Add `const` support for float rounding methods
This PR makes the following float rounding methods `const`:
- `f64::{floor, ceil, trunc, round, round_ties_even}`
- and the corresponding methods for `f16`, `f32` and `f128`
Tracking issue: https://github.com/rust-lang/rust/issues/141555
## Procedure
I followed c09ed3e767 as closely as I could in making float methods `const`, and also received great guidance from https://internals.rust-lang.org/t/const-rounding-methods-in-float-types/22957/3?u=ruancomelli.
## Note
This is my first code contribution to the Rust project, so please let me know if I missed anything - I'd be more than happy to revise and learn more. Thank you for taking the time to review it!
In the previous description it said there was a TOCTOU race but did not
explain exactly what the problem was. I sat down with the CVE, reviewed
its text, and created this explanation. This context should hopefully
help people understand the actual risk as-such.
Incidentally, it also fixes the capitalization on the name of Redox OS.
Add const support for the float rounding methods floor, ceil, trunc,
fract, round and round_ties_even.
This works by moving the calculation logic from
src/tools/miri/src/intrinsics/mod.rs
into
compiler/rustc_const_eval/src/interpret/intrinsics.rs.
All relevant method definitions were adjusted to include the `const`
keyword for all supported float types: f16, f32, f64 and f128.
The constness is hidden behind the feature gate
feature(const_float_round_methods)
which is tracked in
https://github.com/rust-lang/rust/issues/141555
This commit is a squash of the following commits:
- test: add tests that we expect to pass when float rounding becomes const
- feat: make float rounding methods `const`
- fix: replace `rustc_allow_const_fn_unstable(core_intrinsics)` attribute with `#[rustc_const_unstable(feature = "f128", issue = "116909")]` in `library/core/src/num/f128.rs`
- revert: undo update to `library/stdarch`
- refactor: replace multiple `float_<mode>_intrinsic` rounding methods with a single, parametrized one
- fix: add `#[cfg(not(bootstrap))]` to new const method tests
- test: add extra sign tests to check `+0.0` and `-0.0`
- revert: undo accidental changes to `round` docs
- fix: gate `const` float round method behind `const_float_round_methods`
- fix: remove unnecessary `#![feature(const_float_methods)]`
- fix: remove unnecessary `#![feature(const_float_methods)]` [2]
- revert: undo changes to `tests/ui/consts/const-eval/float_methods.rs`
- fix: adjust after rebase
- test: fix float tests
- test: add tests for `fract`
- chore: add commented-out `const_float_round_methods` feature gates to `f16` and `f128`
- fix: adjust NaN when rounding floats
- chore: add FIXME comment for de-duplicating float tests
- test: remove unnecessary test file `tests/ui/consts/const-eval/float_methods.rs`
- test: fix tests after upstream simplification of how float tests are run
Rollup of 8 pull requests
Successful merges:
- rust-lang/rust#140787 (Note expr being cast when encounter NonScalar cast error)
- rust-lang/rust#141112 (std: note that `std::str::from_utf8*` functions are aliases to `<str>::from_utf8*` methods)
- rust-lang/rust#141646 (Document what `distcheck` is intended to exercise)
- rust-lang/rust#141740 (Hir item kind field order)
- rust-lang/rust#141793 (`tests/ui`: A New Order [1/N])
- rust-lang/rust#141805 (Update `compiler-builtins` to 0.1.160)
- rust-lang/rust#141815 (Enable non-leaf Frame Pointers for mingw-w64 Arm64 Windows)
- rust-lang/rust#141819 (Fixes for building windows-gnullvm hosts)
r? `@ghost`
`@rustbot` modify labels: rollup
Do not move thread-locals before dropping
Fixesrust-lang/rust#140816. I also (potentially) improved the speed of `get_or_init` a bit by having an explicit hot/cold path.
We still move the value before dropping in the event of a recursive initialization (leading to double-initialization with one value being silently dropped). This is the old behavior, but changing this to panic instead would involve changing tests and also the other OS-specific `thread_local/os.rs` implementation, which is more than I'd like in this PR.
The float modules in `std` are currently top-level but for `core`, they
are nested within the `num` directory and referenced by `#[path = ...]`.
For consistency, adjust `std` to use the same structure as `core`.
Also change the `f16` and `f128` gates from outer attributes to inner
attributes like `core` has.
Add `rustc_diagnostic_item` to `sys::Mutex` methods
For an ongoing project for adding a concurrency model checker to Miri we need to be able to intercept locking/unlocking operations on standard library mutexes.
This PR adds diagnostic items to the relevant calls `lock`, `try_lock` and `unlock` for the `sys::Mutex` implementation on the targets we care about.
This PR also makes the internals of `pthread::Mutex` less public, to reduce the chance of anyone locking/unlocking a mutex without going through the intercepted methods.
r? ``@RalfJung``
Path::with_extension: show that it adds an extension where one did no…
…t exist
I think the times I encountered this, I had to check first if files without extensions were added, since all examples only had files with existing extensions.
Also, this replaced example already has a similar example below.
Test(fs): Fix `test_eq_windows_file_type` for Windows 7
Would otherwise fail on:
```
thread 'fs::tests::test_eq_windows_file_type' panicked at library/std/src/test_helpers.rs:53:20:
called `Result::unwrap()` on an `Err` value: Os { code: 5, kind: PermissionDenied, message: "Access is denied." }
```
This came from the read-only attribute set on the test file. In order to fix this, instead of simply disabling the test, the attribute is reset before the test's end so it may still run successfully.
`@rustbot` label T-libs A-filesystem A-testsuite O-windows-7 O-windows-msvc