Clarify UB in `get_unchecked(_mut)`
Inspired by #116915, it was unclear to me what exactly "out-of-bounds index" means in `get_unchecked`.
One could [potentially](https://rust.godbolt.org/z/hxM764orW) interpret it that `get_unchecked` is just another way to write `offset`, but I think `get_unchecked(len)` is supposed to be UB even though `.offet(len)` is well-defined (as is `.get_unchecked(..len)`), so write that more directly in the docs.
**libs-api folks**: Can you confirm whether this is what you expect this to mean? And is the situation any different for `<*const [T]>::get_unchecked`?
patterns: reject raw pointers that are not just integers
Matching against `0 as *const i32` is fine, matching against `&42 as *const i32` is not.
This extends the existing check against function pointers and wide pointers: we now uniformly reject all these pointer types during valtree construction, and then later lint because of that. See [here](https://github.com/rust-lang/rust/pull/116930#issuecomment-1784654073) for some more explanation and context.
Also fixes https://github.com/rust-lang/rust/issues/116929.
Cc `@oli-obk` `@lcnr`
Documentation cleanup for core::error::Request.
This part of the documentation currently render like this:
![image](https://github.com/rust-lang/rust/assets/249196/b34cb907-4ce4-4e85-beca-510d8aa1fefb)
The new version renders like this:
![image](https://github.com/rust-lang/rust/assets/249196/fe18398a-15fb-42a7-82a4-f1856d48bd79)
Fixes:
* Add missing closing back tick.
* Remove spurious double back ticks.
* Add missing newline to render bullet point correctly.
* Fix grammar "there are methods calledrequest_ref and request_value are available" -> "there are methods calledrequest_ref and request_value".
* Change "methods" to "functions", which seems more appropriate for free functions.
document that the null pointer has the 0 address
Fixes https://github.com/rust-lang/rust/issues/116895
Will need t-lang FCP, but I think this is fairly uncontroversial -- there's probably already tons of code out there that relies on this.
Override `Waker::clone_from` to avoid cloning `Waker`s unnecessarily
This would be very useful for futures — I think it’s pretty much always what they want to do instead of `*waker = cx.waker().clone()`.
Tracking issue: https://github.com/rust-lang/rust/issues/98287
r? rust-lang/libs-api `@rustbot` label +T-libs-api -T-libs
Avoid unnecessary comparison in partition_equal
The branchy Hoare partition `partition_equal` as part of `slice::sort_unstable` has a bug that makes it perform a comparison of the last element twice.
Measuring inputs with a Zipfian distribution with characterizing exponent s == 1.0, yields a ~0.05% reduction in the total number of comparisons performed.
Rollup of 4 pull requests
Successful merges:
- #116017 (Don't pass `-stdlib=libc++` when building C files on macOS)
- #117524 (bootstrap/setup: create hooks directory if non-existing)
- #117588 (Remove unused LoadResult::DecodeIncrCache variant)
- #117596 (Add diagnostic items for a few of core's builtin macros)
r? `@ghost`
`@rustbot` modify labels: rollup
Add diagnostic items for a few of core's builtin macros
Specifically, `env`, `option_env`, and `include`. There are a number of reasons why people might want to look at these in lints (For example, to ensure that things behave consistently, detect things that might make builds less reproducible, etc).
Concretely, in PL/Rust (well, `plrustc`) we have lints that forbid these (which I'd like to [add to clippy as restriction lints](https://rust-lang.zulipchat.com/#narrow/stream/257328-clippy/topic/Landing.20a.20flotilla.20of.20lints.3F) eventually), and `dylint` also has [lints that look for `env!`/`option_env!`](109a07e9f2/examples/general/env_cargo_path/src/lib.rs) (although perhaps not `include`), which would benefit from this.
My experience is that it's pretty annoying to (robustly) check uses of builtin macros without these IME, although that's perhaps just my own fault (e.g. I could be doing it wrong).
At `@Nilstrieb's` suggestion, I've added a comment that explains why these are here, even though they are not used in the compiler. This is mostly to discourage removal, although it's not a big deal if it happens (I'm certainly not suggesting the presence of these be in any way stable).
---
In theory this is a library PR (in that it's in library/core), but I'm going to roll compiler because the existence of this or not is much more likely something they care about rather than libs. Hopefully nobody objects to this.
r? compiler
Remove obsolete support for linking unwinder on Android
Linking libgcc is no longer supported (see #103673), so remove the related link attributes and the check in unwind's build.rs. The check was the last remaining significant piece of logic in build.rs, so remove build.rs as well.
Stabilize `const_maybe_uninit_zeroed` and `const_mem_zeroed`
Make `MaybeUninit::zeroed` and `mem::zeroed` const stable. Newly stable API:
```rust
// core::mem
pub const unsafe fn zeroed<T>() ->;
impl<T> MaybeUninit<T> {
pub const fn zeroed() -> MaybeUninit<T>;
}
```
This relies on features based around `const_mut_refs`. Per `@RalfJung,` this should be OK since we do not leak any `&mut` to the user.
For this to be possible, intrinsics `assert_zero_valid` and `assert_mem_uninitialized_valid` were made const stable.
Tracking issue: #91850
Zulip discussion: https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/.60const_mut_refs.60.20dependents
r? libs-api
`@rustbot` label -T-libs +T-libs-api +A-const-eval
cc `@RalfJung` `@oli-obk` `@rust-lang/wg-const-eval`
Hint optimizer about try-reserved capacity
This is #116568, but limited only to the less-common `try_reserve` functions to reduce bloat in debug binaries from debug info, while still addressing the main use-case #116570
Deref docs: expand and remove "smart pointer" qualifier
**Ready for review**
~~This is an unpolished draft to be sanity-checked~~
Fixes#91004
~~Comments on substance and content of this are welcome. This is deliberately unpolished until ready to review so please try to stay focused on the big-picture.~~
~~Once this has been sanity checked, I will similarly update `DerefMut` and polish for review.~~
Make `core::mem::zeroed` const stable. Newly stable API:
// core::mem
pub const unsafe fn zeroed<T>() -> T;
This is stabilized with `const_maybe_uninit_zeroed` since it is a simple
wrapper.
In order to make this possible, intrinsics `assert_zero_valid` was made
const stable under `const_assert_type2`.
`assert_mem_uninitialized_valid` was also made const stable since it is
under the same gate.
Make `MaybeUninit::zeroed` const stable. Newly stable API:
// core::mem
impl<T> MaybeUninit<T> {
pub const fn zeroed() -> MaybeUninit<T>;
}
Use of `const_mut_refs` should be acceptable since we do not leak the
mutability.
Tracking issue: #91850
Re-draft Deref docs
Make general advice more explicit and note the difference between
generic and specific implementations.
Re-draft DerefMut docs in-line with Deref
Fix Deref docs typos
Fix broken links
Clarify advice for specific-over-generic impls
Add comment addressing Issue #73682
x fmt
Copy faillibility warning to DerefMut
The initial probe-for-empty-source by stack_buffer_copy only detected EOF
if the source was empty but not when it was merely small which lead to
additional calls to read() after Ok(0) had already been returned
in the stack copy routine
It now keeps track of initialized bytes to avoid reinitialization.
It also keeps track of read sizes to avoid initializing more bytes
than the reader needs. This is important when passing a huge vector to a
Read that only has a few bytes to offer and doesn't implement read_buf().
Remove support for compiler plugins.
They've been deprecated for four years.
This commit includes the following changes.
- It eliminates the `rustc_plugin_impl` crate.
- It changes the language used for lints in `compiler/rustc_driver_impl/src/lib.rs` and `compiler/rustc_lint/src/context.rs`. External lints are now called "loaded" lints, rather than "plugins" to avoid confusion with the old plugins. This only has a tiny effect on the output of `-W help`.
- E0457 and E0498 are no longer used.
- E0463 is narrowed, now only relating to unfound crates, not plugins.
- The `plugin` feature was moved from "active" to "removed".
- It removes the entire plugins chapter from the unstable book.
- It removes quite a few tests, mostly all of those in `tests/ui-fulldeps/plugin/`.
Closes#29597.
r? `@ghost`
They've been deprecated for four years.
This commit includes the following changes.
- It eliminates the `rustc_plugin_impl` crate.
- It changes the language used for lints in
`compiler/rustc_driver_impl/src/lib.rs` and
`compiler/rustc_lint/src/context.rs`. External lints are now called
"loaded" lints, rather than "plugins" to avoid confusion with the old
plugins. This only has a tiny effect on the output of `-W help`.
- E0457 and E0498 are no longer used.
- E0463 is narrowed, now only relating to unfound crates, not plugins.
- The `plugin` feature was moved from "active" to "removed".
- It removes the entire plugins chapter from the unstable book.
- It removes quite a few tests, mostly all of those in
`tests/ui-fulldeps/plugin/`.
Closes#29597.
Guarantee representation of None in NPO
This allows users to soundly transmute zeroes into `Option` types subject to the null pointer optimization (NPO). It unblocks https://github.com/google/zerocopy/issues/293.
Add track_caller to transmute_copy
Currently if `size_of::<Src>() < size_of::<Dst>()` you will see the following error:
```rust
thread 'test' panicked at /rustc/cc66ad468955717ab92600c770da8c1601a4ff33/library/core/src/mem/mod.rs:1056:5:
cannot transmute_copy if Dst is larger than Src
```
This fixes it so it will show the invocation location
Linking libgcc is no longer supported (see #103673), so remove the
related link attributes and the check in unwind's build.rs. The check
was the last remaining significant piece of logic in build.rs, so
remove build.rs as well.
Clarify `Unsize` documentation
The documentation erroneously says that:
```rust
/// - Types implementing a trait `Trait` also implement `Unsize<dyn Trait>`.
/// - Structs `Foo<..., T, ...>` implement `Unsize<Foo<..., U, ...>>` if all of these conditions
/// are met:
/// - `T: Unsize<U>`.
/// - Only the last field of `Foo` has a type involving `T`.
/// - `Bar<T>: Unsize<Bar<U>>`, where `Bar<T>` stands for the actual type of that last field.
```
Specifically, `T: Unsize<U>` is not required to hold -- only the final field must implement `FinalField<T>: Unsize<FinalField<U>>`. This can be demonstrated by the test I added.
---
Second commit fleshes out the documentation a lot more.
Fix switch_stdout_to on Windows7
The `switch_stdout_to` test was broken on Windows7, as deleting the temporary test folder would fail since the `switch-stdout-output` file we redirected the stdout to is never closed, and it's impossible on Win7 to delete an opened file.
To fix this issue, we make `switch_stdout_to` return the previous handle. Using this, we add a new `switch_stdout_to` call at the end of the test to return the stdio handles to their original state, and recover the handle to the file we opened. This handle is automatically closed at the end of the function, which should allow the temporary test folder to be deleted properly.
Support enum variants in offset_of!
This MR implements support for navigating through enum variants in `offset_of!`, placing the enum variant name in the second argument to `offset_of!`. The RFC placed it in the first argument, but I think it interacts better with nested field access in the second, as you can then write things like
```rust
offset_of!(Type, field.Variant.field)
```
Alternatively, a syntactic distinction could be made between variants and fields (e.g. `field::Variant.field`) but I'm not convinced this would be helpful.
[RFC 3308 # Enum Support](https://rust-lang.github.io/rfcs/3308-offset_of.html#enum-support-offset_ofsomeenumstructvariant-field_on_variant)
Tracking Issue #106655.
Clean up unchecked_math, separate out unchecked_shifts
Tracking issue: #85122
Changes:
1. Remove `const_inherent_unchecked_arith` flag and make const-stability flags the same as the method feature flags. Given the number of other unsafe const fns already stabilised, it makes sense to just stabilise these in const context when they're stabilised.
2. Move `unchecked_shl` and `unchecked_shr` into a separate `unchecked_shifts` flag, since the semantics for them are unclear and they'll likely be stabilised separately as a result.
3. Add an `unchecked_neg` method exclusively to signed integers, under the `unchecked_neg` flag. This is because it's a new API and probably needs some time to marinate before it's stabilised, and while it *would* make sense to have a similar version for unsigned integers since `checked_neg` also exists for those there is absolutely no case where that would be a good idea, IMQHO.
The longer-term goal here is to prepare the `unchecked_math` methods for an FCP and stabilisation since they've existed for a while, their semantics are clear, and people seem in favour of stabilising them.
Rollup of 5 pull requests
Successful merges:
- #113241 (rustdoc: Document lack of object safety on affected traits)
- #117388 (Turn const_caller_location from a query to a hook)
- #117417 (Add a stable MIR visitor)
- #117439 (prepopulate opaque ty storage before using it)
- #117451 (Add support for pre-unix-epoch file dates on Apple platforms (#108277))
r? `@ghost`
`@rustbot` modify labels: rollup
Time in UNIX system calls counts from the epoch, 1970-01-01. The timespec
struct used in various system calls represents this as a number of seconds and
a number of nanoseconds. Nanoseconds are required to be between 0 and
999_999_999, because the portion outside that range should be represented in
the seconds field; if nanoseconds were larger than 999_999_999, the seconds
field should go up instead.
Suppose you ask for the time 1969-12-31, what time is that? On UNIX systems
that support times before the epoch, that's seconds=-86400, one day before the
epoch. But now, suppose you ask for the time 1969-12-31 23:59:00.1. In other
words, a tenth of a second after one minute before the epoch. On most UNIX
systems, that's represented as seconds=-60, nanoseconds=100_000_000. The macOS
bug is that it returns seconds=-59, nanoseconds=-900_000_000.
While that's in some sense an accurate description of the time (59.9 seconds
before the epoch), that violates the invariant of the timespec data structure:
nanoseconds must be between 0 and 999999999. This causes this assertion in the
Rust standard library.
So, on macOS, if we get a Timespec value with seconds less than or equal to
zero, and nanoseconds between -999_999_999 and -1 (inclusive), we can add
1_000_000_000 to the nanoseconds and subtract 1 from the seconds, and then
convert. The resulting timespec value is still accepted by macOS, and when fed
back into the OS, produces the same results. (If you set a file's mtime with
that timestamp, then read it back, you get back the one with negative
nanoseconds again.)
Co-authored-by: Josh Triplett <josh@joshtriplett.org>
The switch_stdout_to test was broken on Windows7, as the test
infrastructure would refuse to delete the temporary test folder because
the switch-stdout-output file we redirected the stdout to was still
opened.
To fix this issue, we make switch_stdout_to return the previous handle,
and add a new switch_stdout_to call at the end of the test to return the
stdio handles to their original state. The handle the second
switch_stdout_to returns will be automatically closed, which should
allow the temporary test folder to be deleted properly.
Allows `#[diagnostic::on_unimplemented]` attributes to have multiple
notes
This commit extends the `#[diagnostic::on_unimplemented]` (and `#[rustc_on_unimplemented]`) attributes to allow multiple `note` options. This enables emitting multiple notes for custom error messages. For now I've opted to not change any of the existing usages of `#[rustc_on_unimplemented]` and just updated the relevant compile tests.
r? `@compiler-errors`
I'm happy to adjust any of the existing changed location to emit the old error message if that's desired.
Increase the reach of panic_immediate_abort
I wanted to use/abuse this recently as part of another project, and I was surprised how many panic-related things were left in my binaries if I built a large crate with the feature enabled along with LTO. These changes get all the panic-related symbols that I could find out of my set of locally installed Rust utilities.
memcpy assumptions: link to source showing that GCC makes the same assumption
I finally stumbled upon a source showing that GCC also generates overlapping `memcpy`. So if we're linking major C compilers making such assumptions here, let's have both clang and GCC.
Don't use LFS64 symbols on musl
Supersedes #106246
~~Note to packagers: If your distro's musl package has already been updated, then you won't be able to build a newer version of rust until a new rust release is made with these changes merged (which can be used to bootstrap). I'm using a super hacky method to bypass this by creating a stub library with LFS64 symbols and building a patched rust, so the symbols satisfy the build requirements while the final compiler build has no references to LFS64 symbols, example: https://codeberg.org/kiss-community/repo/pulls/160/files~~ Doesn't seem to be necessary with new rustup nightly builds, likely due to updates to vendored crates
cc ```@alyssais```
Bump stdarch submodule and remove special handling for LLVM intrinsics that are no longer needed
Bumps stdarch to pull https://github.com/rust-lang/stdarch/pull/1477, which reimplemented some functions with portable SIMD intrinsics instead of arch specific LLVM intrinsics.
Handling of those LLVM intrinsics is removed from cranelift codegen and miri.
cc `@RalfJung` `@bjorn3`
Create `windows/api.rs` for safer FFI
FFI is inherently unsafe. For memory safety we need to assert that some contract is being upheld on both sides of the FFI, though of course we can only ever check our side. In Rust, `unsafe` blocks are used to assert safety and `// SAFETY` comments describing why it is safe. Currently in sys/windows we have a lot of this unsafety spread all over the place, with variations on the same unsafe patterns repeated. And because of the repitition and frequency, we're a bit lax with the safety comments.
This PR aims to fix this and to make FFI safety more auditable by creating an `api` module with the goal of centralising and consolidating this unsafety. It contains thin wrappers around the Windows API that make most functions safe to call or, if that's not possible, then at least safer. Note that its goal is *only* to address safety. It does not stray far from the Windows API and intentionally does not attempt to make higher lever wrappers around, for example, file handles. This is better left to the existing modules. The windows/api.rs file has a top level comment to help future contributors understand the intent of the module and the design decisions made.
I chose two functions as a first tentative step towards the above goal:
- [`GetLastError`](https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror) is trivially safe. There's no reason to wrap it in an `unsafe` block every time. So I simply created a safe `get_last_error` wrapper.
- [`SetFileInformationByHandle`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfileinformationbyhandle) is more complex. It essentially takes a generic type but over a C API which necessitates some amount of ceremony. Rather than implementing similar unsafe patterns in multiple places, I provide a safe `set_file_information_by_handle` that takes a Rusty generic type and handles converting that to the form required by the C FFI.
r? libs