Add repr(align(2)) to RcInner and ArcInner
`Rc` currently assumes that `RcInner` has at least 2-byte alignment, but on AVR, `usize` has 1-byte alignment (this is because the AVR has 1-byte register sizes, so having 2-byte alignment is generally useless), breaking this assumption.
9f32ccf35f/library/alloc/src/rc.rs (L3005-L3008)
This PR adds `repr(align(2))` to force `RcInner` to always have at least 2-byte alignment.
Note that `ArcInner` doesn't need `repr(align(2))` because atomic types have the alignment same as its size. This PR adds a comment about this.
Remove most `#[track_caller]` from allocating Vec methods
They cause significant binary size overhead while contributing little value.
closesrust-lang/rust#146963, see that issue for more details.
BTreeMap: Don't leak allocators when initializing nodes
Memory was allocated via `Box::leak` and thence intended to be tracked and deallocated manually, but the allocator was also leaked, not tracked, and never dropped. Now it is dropped immediately.
According to my reading of the `Allocator` trait, if a copy of the allocator remains live, then its allocations must remain live. Since the B-tree has a copy of the allocator that will only be dropped after the nodes, it's safe to not store the allocator in each node (which would be a much more intrusive change).
Fixes: rust-lang/rust#106203
avoid violating `slice::from_raw_parts` safety contract in `Vec::extract_if`
The implementation of the `Vec::extract_if` iterator violates the safety contract adverized by `slice::from_raw_parts` by always constructing a mutable slice for the entire length of the vector even though that span of memory can contain holes from items already drained. The safety contract of `slice::from_raw_parts` requires that all elements must be properly
initialized.
As an example we can look at the following code:
```rust
let mut v = vec![Box::new(0u64), Box::new(1u64)];
for item in v.extract_if(.., |x| **x == 0) {
drop(item);
}
```
In the second iteration a `&mut [Box<u64>]` slice of length 2 will be constructed. The first slot of the slice contains the bitpattern of an already deallocated box, which is invalid.
This fixes the issue by only creating references to valid items and using pointer manipulation for the rest. I have also taken the liberty to remove the big `unsafe` blocks in place of targetted ones with a SAFETY comment. The approach closely mirrors the implementation of `Vec::retain_mut`.
**Note to reviewers:** The diff is easier to follow with whitespace hidden.
RawVecInner: add missing `unsafe` to unsafe fns
Some (module-private) functions in `library/alloc/src/raw_vec/mod.rs` are unsafe (i.e. may cause UB when called from safe code) but are not marked `unsafe`. Specifically:
- `RawVecInner::grow_exact` causes UB if called with `len` and `additional` arguments such that `len + additional` is less than the current capacity. Indeed, in that case it calls [Allocator::grow](https://doc.rust-lang.org/std/alloc/trait.Allocator.html#method.grow) with a `new_layout` that is smaller than `old_layout`, which violates a safety precondition.
- The RawVecInner methods for resizing the buffer cause UB if called with an `elem_layout` different from the one used to initially allocate the buffer, because in that case `Allocator::grow` or `Allocator::shrink` are called with an `old_layout` that does not *fit* the allocated block, which violates a safety precondition.
- `RawVecInner::current_memory` might cause UB if called with an `elem_layout` different from the one used to initially allocate the buffer, because the `unchecked_mul` might overflow.
- Furthermore, these methods cause UB if called with an `elem_layout` where the size is not a multiple of the alignment. This is because `Layout::repeat` is used (in `layout_array`) to compute the allocation's layout when allocating, which includes padding to ensure alignment of array elements, but simple multiplication is used (in `current_memory`) to compute the old allocation's layout when resizing or deallocating, which would cause the layout used to resize or deallocate to not *fit* the allocated block, which violates a safety precondition.
I discovered these issues while performing formal verification of `library/alloc/src/raw_vec/mod.rs` per [Challenge 19](https://model-checking.github.io/verify-rust-std/challenges/0019-rawvec.html) of the [AWS Rust Standard Library Verification Contest](https://aws.amazon.com/blogs/opensource/verify-the-safety-of-the-rust-standard-library/).
Memory was allocated via `Box::leak` and thence intended to be tracked
and deallocated manually, but the allocator was also leaked, not
tracked, and never dropped. Now it is dropped immediately.
According to my reading of the `Allocator` trait, if a copy of the
allocator remains live, then its allocations must remain live. Since
the B-tree has a copy of the allocator that will only be dropped after
the nodes, it's safe to not store the allocator in each node (which
would be a much more intrusive change).
Add panic=immediate-abort
MCP: https://github.com/rust-lang/compiler-team/issues/909
This adds a new panic strategy, `-Cpanic=immediate-abort`. This panic strategy essentially just codifies use of `-Zbuild-std-features=panic_immediate_abort`. This PR is intended to just set up infrastructure, and while it will change how the compiler is invoked for users of the feature, there should be no other impacts.
In many parts of the compiler, `PanicStrategy::ImmediateAbort` behaves just like `PanicStrategy::Abort`, because actually most parts of the compiler just mean to ask "can this unwind?" so I've added a helper function so we can say `sess.panic_strategy().unwinds()`.
The panic and unwind strategies have some level of compatibility, which mostly means that we can pre-compile the sysroot with unwinding panics then the sysroot can be linked with aborting panics later. The immediate-abort strategy is all-or-nothing, enforced by `compiler/rustc_metadata/src/dependency_format.rs` and this is tested for in `tests/ui/panic-runtime/`. We could _technically_ be more compatible with the other panic strategies, but immediately-aborting panics primarily exist for users who want to eliminate all the code size responsible for the panic runtime. I'm open to other use cases if people want to present them, but not right now. This PR is already large.
`-Cpanic=immediate-abort` sets both `cfg(panic = "immediate-abort")` _and_ `cfg(panic = "abort")`. bjorn3 pointed out that people may be checking for the abort cfg to ask if panics will unwind, and also the sysroot feature this is replacing used to require `-Cpanic=abort` so this seems like a good back-compat step. At least for the moment. Unclear if this is a good idea indefinitely. I can imagine this being confusing.
The changes to the standard library attributes are purely mechanical. Apart from that, I removed an `unsafe` we haven't needed for a while since the `abort` intrinsic became safe, and I've added a helpful diagnostic for people trying to use the old feature.
To test that `-Cpanic=immediate-abort` conflicts with other panic strategies, I've beefed up the core-stubs infrastructure a bit. There is now a separate attribute to set flags on it.
I've added a test that this produces the desired codegen, called `tests/run-make-cargo/panic-immediate-abort-codegen/` and also a separate run-make-cargo test that checks that we can build a binary.
Remove unused #![feature(get_mut_unchecked)] in Rc and Arc examples
https://github.com/rust-lang/rust/pull/93109 removed the use of APIs enabled by this feature in these examples, but the `#![feature]` attributes ware not removed.
The implementation of the `Vec::extract_if` iterator violates the safety
contract adverized by `slice::from_raw_parts` by always constructing a
mutable slice for the entire length of the vector even though that span
of memory can contain holes from items already drained. The safety
contract of `slice::from_raw_parts` requires that all elements must be
properly initialized.
As an example we can look at the following code:
```rust
let mut v = vec![Box::new(0u64), Box::new(1u64)];
for item in v.extract_if(.., |x| **x == 0) {
drop(item);
}
```
In the second iteration a `&mut [Box<u64>]` slice of length 2 will be
constructed. The first slot of the slice contains the bitpattern of an
already deallocated box, which is invalid.
This fixes the issue by only creating references to valid items and
using pointer manipulation for the rest. I have also taken the liberty
to remove the big `unsafe` blocks in place of targetted ones with a
SAFETY comment. The approach closely mirrors the implementation of
`Vec::retain_mut`.
Signed-off-by: Petros Angelatos <petrosagg@gmail.com>
Add unstable attribute to BTreeMap-related allocator generics
Although these types aren't directly constructable externally, since they're pub, I think this omission was an oversight.
r? libs-api
Stabilize `new_zeroed_alloc`
The corresponding `new_uninit` and `new_uninit_slice` functions were stabilized in rust-lang/rust#129401, but the zeroed counterparts were left for later out of a [desire](https://github.com/rust-lang/rust/issues/63291#issuecomment-2161039756) to stabilize only the minimal set. These functions are straightforward mirrors of the uninit functions and well-established. Since no blockers or design questions have surfaced in the past year, I think it's time to stabilize them.
Tracking issue: rust-lang/rust#129396
Stabilize `btree_entry_insert` feature
This stabilises `btree_map::VacantEntry::insert_entry` and `btree_map::Entry::insert_entry`, following the FCP in [tracking issue](https://github.com/rust-lang/rust/issues/65225).
New stable API:
```rust
impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> {
pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, A>;
}
impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> {
pub fn insert_entry(mut self, value: V) -> OccupiedEntry<'a, K, V, A>;
}
```
(FCP ended almost a year ago, so if it's needed for process we could rerun it)
Closes: https://github.com/rust-lang/rust/issues/65225
The ASCII subset of Unicode is fixed and will never change, so we don't
need to generate tables for it with every new Unicode version. This
saves a few bytes of static data and speeds up `char::is_control` and
`char::is_grapheme_extended` on ASCII inputs.
Since the table lookup functions exported from the `unicode` module will
give nonsensical errors on ASCII input (and in fact will panic in debug
mode), I had to add some private wrapper methods to `char` which check
for ASCII-ness first.
- RawVecInner::grow_exact causes UB if called with len and additional
arguments such that len + additional is less than the current
capacity. Indeed, in that case it calls Allocator::grow with a
new_layout that is smaller than old_layout, which violates a safety
precondition.
- All RawVecInner methods for resizing the buffer cause UB
if called with an elem_layout different from the one used to initially
allocate the buffer, because in that case Allocator::grow/shrink is called with
an old_layout that does not fit the allocated block, which violates a
safety precondition.
- RawVecInner::current_memory might cause UB if called with an elem_layout
different from the one used to initially allocate the buffer, because
the unchecked_mul might overflow.
- Furthermore, these methods cause UB if called with an elem_layout
where the size is not a multiple of the alignment. This is because
Layout::repeat is used (in layout_array) to compute the allocation's
layout when allocating, which includes padding to ensure alignment of
array elements, but simple multiplication is used (in current_memory) to
compute the old allocation's layout when resizing or deallocating, which
would cause the layout used to resize or deallocate to not fit the
allocated block, which violates a safety precondition.
raw_vec.rs: Remove superfluous fn alloc_guard
`alloc_guard` checks that its argument is at most `isize::MAX`, but it is called only with layout sizes, which are already guaranteed to be at most `isize::MAX`.
Constify conversion traits (part 1)
This is the first part of rust-lang/rust#144289 being split into smaller pieces. It adds/moves constness of several traits under the `const_convert` feature:
* `From`
* `Into`
* `TryFrom`
* `TryInto`
* `FromStr`
* `AsRef`
* `AsMut`
* `Borrow`
* `BorrowMut`
* `Deref`
* `DerefMut`
There are a few methods that are intrinsically tied to these traits which I've included in the feature. Particularly, those which are wrappers over `AsRef`:
* `ByteStr::new` (unstable under `bstr` feature)
* `OsStr::new`
* `Path::new`
Those which directly use `Into`:
* `Result::into_ok`
* `Result::into_err`
And those which use `Deref` and `DerefMut`:
* `Pin::as_ref`
* `Pin::as_mut`
* `Pin::as_deref_mut`
* `Option::as_deref`
* `Option::as_deref_mut`
* `Result::as_deref`
* `Result::as_deref_mut`
(note: the `Option` and `Result` methods were suggested by ``@npmccallum`` initially as rust-lang/rust#146101)
The parts which are missing from this PR are:
* Anything that involves heap-allocated types
* Making any method const than the ones listed above
* Anything that could rely on the above, *or* could rely on system-specific code for `OsStr` or `Path` (note: this mostly makes these methods useless since `str` doesn't implement `AsRef<OsStr>` yet, but it's better to track the method for now and add impls later, IMHO)
r? ``@tgross35`` (who mostly already reviewed this)
Fix format string grammar in docs and improve alignment error message for #144023
This PR improves error messages and documentation for format strings involving alignment and formatting traits.
Highlights:
- Clearer error messages for invalid alignment specifiers (e.g., `{0:#X>18}`), showing the expected `<`, `^`, or `>` and a working example:
println!("{0:>#18X}", value);
- Updated UI test `format-alignment-hash.rs` to reflect the improved error output.
- Documentation clarification: ensures examples correctly show how width, alignment, and traits like `x`, `X`, `#` combine.
Motivation:
Previously, using `#` with alignment and width produced confusing errors. This PR guides users on the correct syntax and provides actionable examples.
Testing:
- Built the compiler (`./x build`)
- Blessed and ran UI tests (`./x. test src/test/ui/fmt/format-alignment-hash.rs --bless`)
- Verified full test suite passes (`./x test`)
Issue: rust-lang/rust#144023