kmc-solid: Fix `is_interrupted`
Follow-up to #115228. Fixes a build error in [`*-kmc-solid_*`](https://doc.rust-lang.org/nightly/rustc/platform-support/kmc-solid.html) Tier 3 targets.
```
error[E0603]: function `is_interrupted` is private
--> library\std\src\sys\solid\mod.rs:77:12
|
77 | error::is_interrupted(code)
| ^^^^^^^^^^^^^^ private function
|
note: the function `is_interrupted` is defined here
--> library\std\src\sys\solid\error.rs:35:1
|
35 | fn is_interrupted(er: abi::ER) -> bool {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Add alignment to the NPO guarantee
This PR [changes](https://github.com/rust-lang/rust/pull/114845#discussion_r1294363357) "same size" to "same size and alignment" in the option module's null pointer optimization docs in <https://doc.rust-lang.org/std/option/#representation>.
As far as I know, this has been true for a long time in the actual rustc implementation, but it's not in the text of those docs, so I figured I'd bring this up to FCP it.
I also see no particular reason that we'd ever *want* to have higher alignment on these. In many of the cases it's impossible, as the minimum alignment is already the size of the type, but even if we *could* do things like on 32-bit we could say that `NonZeroU64` is 4-align but `Option<NonZeroU64>` is 8-align, I just don't see any value in doing that, so feel completely fine closing this door for the few things on which the NPO is already guaranteed. These are basically all primitives, and should end up with the same size & alignment as those primitives.
(There's no layout guarantee for something like `Option<[u8; 3]>`, where it'd be at least plausible to consider raising the alignment from 1 to 4 on, say, some hypothetical target that doesn't have efficient unaligned 4-byte load/stores. And even if we ever did start to offer some kind of guarantee around such a type, I doubt we'd put it under the "null pointer" optimization header.)
Screenshots for the new examples:
![image](https://github.com/rust-lang/rust/assets/18526288/a7dbff42-50b4-462e-9e27-00d511b58763)
![image](https://github.com/rust-lang/rust/assets/18526288/dfd55288-80fb-419a-bc11-26198c27f9f9)
Implement Step for ascii::Char
This allows iterating over ranges of `ascii::Char`, similarly to ranges of `char`.
Note that `ascii::Char` is still unstable, tracked in #110998.
docs: improve std::fs::read doc
#### What does this PR do
1. Rephrase a confusing sentence in the document of `std::fs::read()`
-----
Closes#114432
cc `@Dexus0` `@saethlin`
Add note that Vec::as_mut_ptr() does not materialize a reference to the internal buffer
See discussion on https://github.com/thomcc/rust-typed-arena/issues/62 and [t-opsem](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/is.20this.20typed_arena.20code.20sound.20under.20stacked.2Ftree.20borrows.3F)
This method already does the correct thing here, but it is worth guaranteeing that it does so it can be used more freely in unsafe code without having to worry about potential Stacked/Tree Borrows violations. This moves one more unsafe usage pattern from the "very likely sound but technically not fully defined" box into "definitely sound", and currently our surface area of the latter is woefully small.
I'm not sure how best to word this, opening this PR as a way to start discussion.
Fix implementation of `Duration::checked_div`
I ran across this while running some sanity checks on `time`. Quickcheck immediately found a bug, and as I'd modified the code from `std` I knew there was a bug here as well.
tl;dr this code fails ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1189a3efcdfc192c27d6d87815359353))
```rust
use std::time::Duration;
fn main() {
assert_eq!(
Duration::new(1, 1).checked_div(7),
Some(Duration::new(0, 142_857_143)),
);
}
```
The existing code determines that 1/7 = 0 (seconds), 1/7 = 0 (nanoseconds), 1 billion / 7 = 142,857,142 (extra nanoseconds). The billion comes from multiplying the remainder of the seconds (1) by the number of nanoseconds in a second. However, **this wrongly ignores any remaining nanoseconds**. This PR takes that into consideration, adds a test, and also changes the roundabout way of calculating the remainder into directly computing it.
Note: This is _not_ a rounding error. This result divides evenly.
`@rustbot` label +A-time +C-bug +S-waiting-on-reviewer +T-libs
Document that SystemTime does not count leap seconds
Fixes#77994
This may not be entirely uncontroversial. I know that `@Ekleog` is going to disagree. However, in support of this docs change:
This documents the current behaviour. The alternative would be to plan to *change* the behaviour.
There are many programs which need to get a POSIX time (a `time_t`). Right now, `duration_since(UNIX_EPOCH)` is the only facility in std that does that. So, that is what programs use. Changing the behaviour would break[1] all of those programs. We would need to define a new API that can be used to get a POSIX time, and get everyone to use it. This seems highly unpalatable.
And, even if we wanted to do that, time with leap seconds is a lot less easy to work with. We would need to arrange to have a leap seconds table available to `std` somehow, and make sure that it was kept up to date. Currently we don't offer to do that for timezone data, which has similar needs. There are other complications. So it seems it would be awkwarrd to *implement* a facility that provides time including leap seconds, and the resulting value would be hard for applications to work with.
Therefore, I think it's clear that we don't want to plan to ever change `SystemTime`. We should plan to keep it the way it is. Providing TAI (for example) should be left to external crates, or additional APIs we may add in the future.
For more discussion see #77994 and in particular `@fanf2's` https://github.com/rust-lang/rust/issues/77994#issuecomment-1409448174
[1] Of course, by "break" we really only mean *future* breakage in the case where there is, in fact, ever another leap second. There may well not be: they are in the process of being abolished (although this is of course being contested). But if we decide that `SystemTime::now().duraton_since(UNIX_EPOCH)` counts leap seconds, it would start to return `Durations`s that are 27s different to the current answers. That's clearly unacceptable. And we can hardly change `UNIX_EPOCH` by 27s.
wasi: round up the size for `aligned_alloc`
C11 `aligned_alloc` requires that the size be a multiple of the
alignment. This is enforced in the wasi-libc emmalloc implementation,
which always returns NULL if the size is not a multiple.
(The default `MALLOC_IMPL=dlmalloc` does not currently check this.)
Correct and expand documentation of `handle_alloc_error` and `set_alloc_error_hook`.
The primary goal of this change is to remove the false claim that `handle_alloc_error` always aborts; instead, code should be prepared for `handle_alloc_error` to possibly unwind, and be sound under that condition.
I saw other opportunities for improvement, so I have added all the following information:
* `handle_alloc_error` may panic instead of aborting. (Fixes#114898)
* What happens if a hook returns rather than diverging.
* A hook may panic. (This was already demonstrated in an example, but not stated in prose.)
* A hook must be sound to call — it cannot assume that it is only called by the runtime, since its function pointer can be retrieved by safe code.
I've checked these statements against the source code of `alloc` and `std`, but there may be nuances I haven't caught, so a careful review is welcome.
Go into more detail about panicking in drop.
This patch was sitting around in my drafts. I don't recall the motivation, but I think it was someone expressing confusion over “will likely abort” (since, in fact, a panicking drop _not_ caused by dropping while panicking will predictably _not_ abort).
I hope that the new text will leave people well-informed about why not to panic and when it is reasonable to panic.
C11 `aligned_alloc` requires that the size be a multiple of the
alignment. This is enforced in the wasi-libc emmalloc implementation,
which always returns NULL if the size is not a multiple.
(The default `MALLOC_IMPL=dlmalloc` does not currently check this.)
Make `rustc_on_unimplemented` std-agnostic for `alloc::rc`
See https://github.com/rust-lang/rust/issues/112923
Just a few lines related to `alloc:rc` for `Send` and `Sync`.
That seems to be all of the `... = "std::..."` issues found, but there a few notes with `std::` inside them still.
r? `@WaffleLapkin`
Add a new helper to avoid calling io::Error::kind
On `cfg(unix)`, `Error::kind` emits an enormous jump table that LLVM seems unable to optimize out. I don't really understand why, but see for yourself: https://godbolt.org/z/17hY496KG
This change lets us check for `ErrorKind::Interrupted` without going through a big match. I've checked the codegen locally, and it has the desired effect on the codegen for `BufReader::read_exact`.
This implements the ability to add arbitrary attributes to a command on Windows targets using a new `raw_attribute` method on the [`CommandExt`](https://doc.rust-lang.org/stable/std/os/windows/process/trait.CommandExt.html) trait. Setting these attributes provides extended configuration options for Windows processes.
Co-authored-by: Tyler Ruckinger <t.ruckinger@gmail.com>
kmc-solid: Import `std::sync::PoisonError` in `std::sys::solid::os`
Follow-up to #114968. Fixes a missing import in [`*-kmc-solid_*`](https://doc.rust-lang.org/nightly/rustc/platform-support/kmc-solid.html) Tier 3 targets.
```
error[E0433]: failed to resolve: use of undeclared type `PoisonError`
C:\Users\xxxxx\.rustup\toolchains\nightly-2023-08-23-x86_64-pc-windows-gnu\lib\rustlib\src\rust\library\std\src\sys\solid\os.rs(85,36)
|
85 | ENV_LOCK.read().unwrap_or_else(PoisonError::into_inner)
| ^^^^^^^^^^^ use of undeclared type `PoisonError`
|
```
Add support for `ptr::write`s for the `invalid_reference_casting` lint
This PR adds support for `ptr::write` and others for the `invalid_reference_casting` lint.
Detecting instances where instead of using the deref (`*`) operator to assign someone uses `ptr::write`, `ptr::write_unaligned` or `ptr::write_volatile`.
```rust
let data_len = 5u64;
std::ptr::write(
std::mem::transmute::<*const u64, *mut u64>(&data_len),
new_data_len,
);
```
r? ``@est31``
Add `suggestion` for some `#[deprecated]` items
Consider code:
```rust
fn main() {
let _ = ["a", "b"].connect(" ");
}
```
Currently it shows deprecated warning:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
```
This PR adds `suggestion` for `connect` and some other deprecated items, so the warning will be changed to this:
```rust
warning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to join
--> src/main.rs:2:24
|
2 | let _ = ["a", "b"].connect(" ");
| ^^^^^^^
|
= note: `#[warn(deprecated)]` on by default
help: replace the use of the deprecated method
|
2 | let _ = ["a", "b"].join(" ");
| ^^^^
```
custom_mir: change Call() terminator syntax to something more readable
I find our current syntax very hard to read -- I cannot even remember the order of arguments, and having the "next block" *before* the actual function call is very counter-intuitive IMO. So I suggest we use `Call(ret_val = function(v), next_block)` instead.
r? `@JakobDegen`
Fix UB in `std::sys::os::getenv()`
Fixes#114949.
Reduced the loops to 1k iterations (100k was taking way too long), Miri no longer shows any UB.
`@rustbot` label +A-process +C-bug +I-unsound +O-unix
rustdoc: Add lint `redundant_explicit_links`
Closes#87799.
- Lint warns by default
- Reworks link parser to cache original link's display text
r? `@jyn514`
Usage zero as language id for `FormatMessageW()`
This switches the language selection from using system language (note that this might be different than application language, typically stored as thread ui language) to use `FormatMessageW` default search strategy, which is `neutral` first, then `thread ui lang`, then `user language`, then `system language`, then `English`. (See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-formatmessagew)
This allows the Rust program to take more control of `std::io::Error`'s message field, by setting up thread ui language themselves before hand (which many programs already do).
Inline strlen_rt in CStr::from_ptr
This enables LLVM to optimize this function as if it was strlen (LLVM knows what it does, and can avoid calling it in certain situations) without having to enable std-aware LTO. This is essentially doing what https://github.com/rust-lang/rust/pull/90007 did, except updated for this function being `const`.
Pretty sure it's safe to roll-up, considering last time I did make this change it didn't affect performance (`CStr::from_ptr` isn't really used all that often in Rust code that is checked by rust-perf).
Increase clarity about Hash - Eq consistency in HashMap and HashSet docs
As discussed [here](https://users.rust-lang.org/t/what-hapens-if-hash-and-partialeq-dont-match-when-using-hashmap/98052/13) the description of logic errors in `HashMap` and `HashSet` does not explicitly apply to
```text
k1 == k2 -> hash(k1) == hash(k2)
```
but this is likely what is intended.
This PR is a small doc change to correct this.
r? rust-lang/libs
Add the following facts:
* `handle_alloc_error` may panic instead of aborting.
* What happens if a hook returns rather than diverging.
* A hook may panic. (This was already demonstrated in an example,
but not stated in prose.)
* A hook must be sound to call — it cannot assume that it is only
called by the runtime, since its function pointer can be retrieved by
safe code.
Add `modulo` and `mod` as doc aliases for `rem_euclid`.
When I was learning Rust I looked for “a modulo function” and couldn’t find one, so thought I had to write my own; it wasn't at all obvious that a function with “rem” in the name was the function I wanted. Hopefully this will save the next learner from that.
However, it does have the disadvantage that the top results in rustdoc for “mod” are now these aliases instead of the Rust keyword, which probably isn't ideal.
Add doc aliases for trigonometry and other f32,f64 methods.
These are common alternate names, usually a less-abbreviated form, for the operation; e.g. `arctan` instead of `atan`. Prompted by <https://users.rust-lang.org/t/64-bit-trigonometry/98599>
When I was learning Rust I looked for “a modulo function” and couldn’t
find one, so thought I had to write my own; it wasn't at all obvious
that a function with “rem” in the name was the function I wanted.
Hopefully this will save the next learner from that.
However, it does have the disadvantage that the top results in rustdoc
for “mod” are now these aliases instead of the Rust keyword, which
probably isn't ideal.
Synchronize with all calls to `unpark` in id-based thread parker
[The documentation for `thread::park`](https://doc.rust-lang.org/nightly/std/thread/fn.park.html#memory-ordering) guarantees that "park synchronizes-with all prior unpark operations". In the id-based thread parking implementation, this is not implemented correctly, as the state variable is reset with a simple store, so there will not be a *synchronizes-with* edge if an `unpark` happens just before the reset. This PR corrects this, replacing the load-check-reset sequence with a single `compare_exchange`.