Commit graph

2264 commits

Author SHA1 Message Date
bors
aa4cfd0809 Auto merge of #134424 - 1c3t3a:null-checks, r=saethlin
Insert null checks for pointer dereferences when debug assertions are enabled

Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a `MirPass`.

This inserts checks in the same places as the `CheckAlignment` pass and additionally
also inserts checks for `Borrows`, so code like
```rust
let ptr: *const u32 = std::ptr::null();
let val: &u32 = unsafe { &*ptr };
```
will have a check inserted on dereference. This is done because null references
are UB. The alignment check doesn't cover these places, because in `&(*ptr).field`,
the exact requirement is that the final reference must be aligned. This is something to
consider further enhancements of the alignment check.

For now this is implemented as a separate `MirPass`, to make it easy to disable
this check if necessary.

This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.

r? `@saethlin`
2025-01-31 15:56:53 +00:00
Bastian Kersting
b151b513ba Insert null checks for pointer dereferences when debug assertions are enabled
Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a MirPass.

This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.
2025-01-31 11:13:34 +00:00
bors
c37fbd873a Auto merge of #135318 - compiler-errors:vtable-fixes, r=lcnr
Fix deduplication mismatches in vtables leading to upcasting unsoundness

We currently have two cases where subtleties in supertraits can trigger disagreements in the vtable layout, e.g. leading to a different vtable layout being accessed at a callsite compared to what was prepared during unsizing. Namely:

### #135315

In this example, we were not normalizing supertraits when preparing vtables. In the example,

```
trait Supertrait<T> {
    fn _print_numbers(&self, mem: &[usize; 100]) {
        println!("{mem:?}");
    }
}
impl<T> Supertrait<T> for () {}

trait Identity {
    type Selff;
}
impl<Selff> Identity for Selff {
    type Selff = Selff;
}

trait Middle<T>: Supertrait<()> + Supertrait<T> {
    fn say_hello(&self, _: &usize) {
        println!("Hello!");
    }
}
impl<T> Middle<T> for () {}

trait Trait: Middle<<() as Identity>::Selff> {}
impl Trait for () {}

fn main() {
    (&() as &dyn Trait as &dyn Middle<()>).say_hello(&0);
}
```

When we prepare `dyn Trait`, we see a supertrait of `Middle<<() as Identity>::Selff>`, which itself has two supertraits `Supertrait<()>` and `Supertrait<<() as Identity>::Selff>`. These two supertraits are identical, but they are not duplicated because we were using structural equality and *not* considering normalization. This leads to a vtable layout with two trait pointers.

When we upcast to `dyn Middle<()>`, those two supertraits are now the same, leading to a vtable layout with only one trait pointer. This leads to an offset error, and we call the wrong method.

### #135316

This one is a bit more interesting, and is the bulk of the changes in this PR. It's a bit similar, except it uses binder equality instead of normalization to make the compiler get confused about two vtable layouts. In the example,

```
trait Supertrait<T> {
    fn _print_numbers(&self, mem: &[usize; 100]) {
        println!("{mem:?}");
    }
}
impl<T> Supertrait<T> for () {}

trait Trait<T, U>: Supertrait<T> + Supertrait<U> {
    fn say_hello(&self, _: &usize) {
        println!("Hello!");
    }
}
impl<T, U> Trait<T, U> for () {}

fn main() {
    (&() as &'static dyn for<'a> Trait<&'static (), &'a ()>
        as &'static dyn Trait<&'static (), &'static ()>)
        .say_hello(&0);
}
```

When we prepare the vtable for `dyn for<'a> Trait<&'static (), &'a ()>`, we currently consider the PolyTraitRef of the vtable as the key for a supertrait. This leads two two supertraits -- `Supertrait<&'static ()>` and `for<'a> Supertrait<&'a ()>`.

However, we can upcast[^up] without offsetting the vtable from `dyn for<'a> Trait<&'static (), &'a ()>` to `dyn Trait<&'static (), &'static ()>`. This is just instantiating the principal trait ref for a specific `'a = 'static`. However, when considering those supertraits, we now have only one distinct supertrait -- `Supertrait<&'static ()>` (which is deduplicated since there are two supertraits with the same substitutions). This leads to similar offsetting issues, leading to the wrong method being called.

[^up]: I say upcast but this is a cast that is allowed on stable, since it's not changing the vtable at all, just instantiating the binder of the principal trait ref for some lifetime.

The solution here is to recognize that a vtable isn't really meaningfully higher ranked, and to just treat a vtable as corresponding to a `TraitRef` so we can do this deduplication more faithfully. That is to say, the vtable for `dyn for<'a> Tr<'a>` and `dyn Tr<'x>` are always identical, since they both would correspond to a set of free regions on an impl... Do note that `Tr<for<'a> fn(&'a ())>` and `Tr<fn(&'static ())>` are still distinct.

----

There's a bit more that can be cleaned up. In codegen, we can stop using `PolyExistentialTraitRef` basically everywhere. We can also fix SMIR to stop storing `PolyExistentialTraitRef` in its vtable allocations.

As for testing, it's difficult to actually turn this into something that can be tested with `rustc_dump_vtable`, since having multiple supertraits that are identical is a recipe for ambiguity errors. Maybe someone else is more creative with getting that attr to work, since the tests I added being run-pass tests is a bit unsatisfying. Miri also doesn't help here, since it doesn't really generate vtables that are offset by an index in the same way as codegen.

r? `@lcnr` for the vibe check? Or reassign, idk. Maybe let's talk about whether this makes sense.

<sup>(I guess an alternative would also be to not do any deduplication of vtable supertraits (or only a really conservative subset) rather than trying to normalize and deduplicate more faithfully here. Not sure if that works and is sufficient tho.)</sup>

cc `@steffahn` -- ty for the minimizations
cc `@WaffleLapkin` -- since you're overseeing the feature stabilization :3

Fixes #135315
Fixes #135316
2025-01-31 04:09:11 +00:00
Michael Goulet
d98b99af56 More assertions, tests, and miri coverage 2025-01-30 17:44:28 +00:00
Lukas Markeffsky
ca3ff832e3 add comments 2025-01-30 18:13:16 +01:00
Lukas Markeffsky
10fc0b159e introduce ty::Value
Co-authored-by: FedericoBruzzone <federico.bruzzone.i@gmail.com>
2025-01-30 17:47:44 +01:00
Michael Goulet
739ef83f31 Normalize vtable entries before walking and deduplicating them 2025-01-30 15:34:00 +00:00
Michael Goulet
fdc4bd22b7 Do not treat vtable supertraits as distinct when bound with different bound vars 2025-01-30 15:33:58 +00:00
bors
5e5567993d Auto merge of #136035 - SpecificProtagonist:miri-zeroed-alloc, r=oli-obk
miri: optimize zeroed alloc

When allocating zero-initialized memory in MIR interpretation, rustc allocates zeroed memory, marks it as initialized and then re-zeroes it. Remove the last step.

I don't expect this to have much of an effect on performance normally, but in my case in which I'm creating a large allocation via mmap it gets in the way.
2025-01-30 01:27:21 +00:00
León Orell Valerian Liehr
bde47b7ae8
Rollup merge of #136166 - RalfJung:interpet-is-alloc-live, r=compiler-errors
interpret: is_alloc_live: check global allocs last

See https://github.com/rust-lang/rust/pull/136105#discussion_r1930609553.

(A perf run makes no sense as this is only used by Miri.)
2025-01-29 06:03:23 +01:00
bors
bf1b174e7d Auto merge of #136203 - matthiaskrgr:rollup-1k0f44l, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #135869 (Make docs for AtomicUsize::from_mut platform-independent)
 - #135892 (-Znext-solver: "normalize" signature before checking it mentions self in `deduce_closure_signature`)
 - #136055 (Implement MIR const trait stability checks)
 - #136066 (Pass spans to `perform_locally_in_new_solver`)
 - #136071 ([Clippy] Add vec_reserve & vecdeque_reserve diagnostic items)
 - #136124 (Arbitrary self types v2: explain test.)
 - #136149 (Flip the `rustc-rayon`/`indexmap` dependency order)
 - #136173 (Update comments and sort target_arch in c_char_definition)
 - #136178 (Update username in build helper example)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-28 20:15:51 +00:00
Matthias Krüger
4cb1342199
Rollup merge of #136055 - fee1-dead-contrib:push-ovmyztlkptmk, r=RalfJung
Implement MIR const trait stability checks

Addresses https://github.com/rust-lang/project-const-traits/issues/16

cc ``@rust-lang/project-const-traits``
r? ``@RalfJung``
2025-01-28 18:17:24 +01:00
SpecificProtagonist
eee9df43e6
miri: optimize zeroed alloc
Co-authored-by: Ralf Jung <post@ralfj.de>
2025-01-28 12:50:02 +01:00
Deadbeef
4aaf467e26 Implement MIR const trait stability checks 2025-01-28 05:01:12 +00:00
Ralf Jung
bc135aaa98 interpret: is_alloc_live: check global allocs last 2025-01-28 02:58:44 +01:00
Michael Goulet
eeecb56b73 Represent the raw pointer for a array length check as a new kind of fake borrow 2025-01-28 00:00:33 +00:00
Michael Goulet
057313b7a6 Reapply "Auto merge of #133734 - scottmcm:lower-indexing-to-ptrmetadata, r=davidtwco,RalfJung"
This reverts commit 122a55bb44.
2025-01-27 23:42:47 +00:00
FedericoBruzzone
cef97bce7b Add TooGeneric variant to LayoutError and emit Unknown one
- `check-pass` test for a MRE of #135020
- fail test for #135138
- switch to `TooGeneric` for checking CMSE fn signatures
- switch to `TooGeneric` for compute `SizeSkeleton` (for transmute)
- fix broken tests
2025-01-27 00:37:34 +01:00
Deadbeef
626d3ba514 Fix typo in const stability error message 2025-01-25 21:43:22 +08:00
Guillaume Gomez
4842ff4a85
Rollup merge of #134858 - estebank:issue-81370, r=Noratrieb
Provide structured suggestion for `#![feature(..)]` in more cases

Fix #81370.
2025-01-19 11:48:15 +01:00
bors
c62b732724 Auto merge of #135709 - lqd:bring-back-len, r=compiler-errors
Temporarily bring back `Rvalue::Len`

r? `@compiler-errors` as requested in https://github.com/rust-lang/rust/issues/135671#issuecomment-2599580364

> However, in the mean time, I'd rather we not crunch trying to find and more importantly validate the soundness of a solution 🤔

Agreed. To fix the IMO P-critical #135671 for which we somehow didn't have test coverage, this PR temporarily reverts:
- https://github.com/rust-lang/rust/pull/133734
- its bugfix https://github.com/rust-lang/rust/pull/134371
- https://github.com/rust-lang/rust/pull/134330

cc `@scottmcm`

I added the few samples from that issue as a test, but we can add more in the future, in particular it seems `@steffahn` [will work on that](https://github.com/rust-lang/rust/issues/135671#issuecomment-2599714354).

Fixes #135671. And if we want to land this, it should also be nominated for beta backport.
2025-01-19 06:09:51 +00:00
Rémy Rakic
122a55bb44 Revert "Auto merge of #133734 - scottmcm:lower-indexing-to-ptrmetadata, r=davidtwco,RalfJung"
This reverts commit b57d93d8b9, reversing
changes made to 0aeaa5eb22.
2025-01-18 22:09:35 +00:00
Rémy Rakic
ca1c17c88d Revert "Auto merge of #134330 - scottmcm:no-more-rvalue-len, r=matthewjasper"
This reverts commit e108481f74, reversing
changes made to 303e8bd768.
2025-01-18 22:09:34 +00:00
Esteban Küber
e7ac2eabd0 Deduplicate logic 2025-01-18 21:15:42 +00:00
Esteban Küber
7175da59d3 Structured suggestion for "missing feature intrinsic"
```
error: `size_of_val` is not yet stable as a const intrinsic
  --> $DIR/const-unstable-intrinsic.rs:17:9
   |
LL |         unstable_intrinsic::size_of_val(&x);
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = help: add `#![feature(unstable)]` to the crate attributes to enable
help: add `#![feature(unstable)]` to the crate attributes to enable
   |
LL + #![feature("unstable")]
   |
```
2025-01-18 21:15:37 +00:00
Esteban Küber
a47fee50bd Structured suggestion for "missing feature in unstable fn call"
When encountering a call corresponding to an item marked as unstable behind a feature flag, provide a structured suggestion pointing at where in the crate the `#![feature(..)]` needs to be written.

```
error: `foobar` is not yet stable as a const fn
  --> $DIR/const-stability-attribute-implies-no-feature.rs:12:5
   |
LL |     foobar();
   |     ^^^^^^^^
   |
help: add `#![feature(const_foobar)]` to the crate attributes to enable
   |
LL + #![feature(const_foobar)]
   |
```

Fix #81370.
2025-01-18 21:13:27 +00:00
Ralf Jung
e1dda10057 const-eval: detect more pointers as definitely not-null 2025-01-18 08:51:28 +01:00
Oli Scherer
a61cd86a4e Methods of const traits are const 2025-01-15 15:57:06 +00:00
Michael Goulet
2669f2a7c7 Do not consider traits that have unsatisfied const conditions to be conditionally const 2025-01-14 18:52:42 +00:00
Michael Goulet
9bf9f5db9b Assert that Instance::try_resolve is only used on body-like things 2025-01-13 02:20:08 +00:00
Rémy Rakic
a13354bea0 rename BitSet to DenseBitSet
This should make it clearer that this bitset is dense, with the
advantages and disadvantages that it entails.
2025-01-11 11:34:01 +00:00
Michael Goulet
924000d70e Unify conditional and non const call error reporting 2025-01-09 16:20:10 +00:00
Michael Goulet
5a9f0be0bd Make the non-const part swappable in the diagnostic 2025-01-09 16:15:19 +00:00
Michael Goulet
b321cd5573 Add note back to conditionally-const error message 2025-01-09 16:15:19 +00:00
Josh Triplett
bb6bbfa13f Avoid naming variables str
This renames variables named `str` to other names, to make sure `str`
always refers to a type.

It's confusing to read code where `str` (or another standard type name)
is used as an identifier. It also produces misleading syntax
highlighting.
2025-01-07 14:30:02 +02:00
Ralf Jung
3cd3649c6c rustc_intrinsic: support functions without body; they are implicitly marked as must-be-overridden 2025-01-04 11:41:51 +01:00
bors
4e5fec2f1e Auto merge of #134757 - RalfJung:const_swap, r=scottmcm
stabilize const_swap

libs-api FCP passed in https://github.com/rust-lang/rust/issues/83163.

However, I only just realized that this actually involves an intrinsic. The intrinsic could be implemented entirely with existing stable const functionality, but we choose to make it a primitive to be able to detect more UB. So nominating for `@rust-lang/lang`  to make sure they are aware; I leave it up to them whether they want to FCP this.

While at it I also renamed the intrinsic to make the "nonoverlapping" constraint more clear.

Fixes #83163
2024-12-30 23:46:42 +00:00
许杰友 Jieyou Xu (Joe)
72ef16f519
Rollup merge of #134787 - fmease:spruce-up-queries, r=compiler-errors
Spruce up the docs of several queries related to the type/trait system and const eval

- Editorial
  - Proper rustdoc summary/synopsis line by making use of extra paragraphs: Leads to better rendered output on module pages, in search result lists and overall, too
  - Use rustdoc warning blocks for admonitions of the form "do not call / avoid calling this query directly"
  - Use intra-doc links of the form ``[`Self::$query`]`` to cross-link queries. Indeed, such links are generally a bit brittle due to the existence of `TyCtxtFeed` which only contains a subset of queries. Therefore the docs of `feedable` queries cannot cross-link to non-`feedable` ones. I'd say it's fine to use intra-doc links despite the potential/unlikely occasional future breakage (if a query with the aforementioned characteristics becomes `feedable`). `Self::` is nicer than `TyCtxt::` (which would be more stable) since it accounts for other contexts like `TyCtxt{Feed,At,Ensure{,WithValue}}`
- Informative
  - Generally add, flesh out and correct some doc comments
  - Add *Panic* sections (to a few selected queries only). The lists of panics aren't necessarily exhaustive and focus on the more "obvious" or "important" panics.
  - Where applicable add a paragraph calling attention to the relevant [`#[rustc_*]` TEST attribute](https://rustc-dev-guide.rust-lang.org/compiler-debugging.html#rustc_-test-attributes)

The one non-doc change (it's internal and not observable):
Be even more defensive in `query constness`'s impl (spiritual follow-up to #134122) (see self review comment).

Fixes #133494.

r\? **any**(compiler-errors, oli-obk)
2024-12-27 20:44:13 +08:00
许杰友 Jieyou Xu (Joe)
b9df376189
Rollup merge of #134606 - RalfJung:ptr-copy-docs, r=Mark-Simulacrum
ptr::copy: fix docs for the overlapping case

Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/549

As discussed in that issue, it doesn't make any sense for `copy` to read a byte via `src` after it was already written via `dst`. The entire point of this method is that is copies correctly even if they overlap, and that requires always reading any given location before writing it.

Cc `@rust-lang/opsem`
2024-12-27 20:44:11 +08:00
León Orell Valerian Liehr
454c09e355
Spruce up the docs of several queries related to the type/trait system and const eval 2024-12-27 11:44:23 +01:00
Ralf Jung
335f7f59c1 swap_typed_nonoverlapping: properly detect overlap even when swapping scalar values 2024-12-25 16:01:26 +01:00
Ralf Jung
7291b1eaf7 rename typed_swap → typed_swap_nonoverlapping 2024-12-25 10:53:03 +01:00
Ralf Jung
00dfa3ba2d miri: add test for overlapping typed_swap 2024-12-25 10:45:48 +01:00
bors
d3e71fd2d3 Auto merge of #134716 - Zalathar:rollup-1h4q8cc, r=Zalathar
Rollup of 5 pull requests

Successful merges:

 - #134638 (Fix effect predicates from item bounds in old solver)
 - #134662 (Fix safety docs for `dyn Any + Send {+ Sync}`)
 - #134689 (core: fix const ptr::swap_nonoverlapping when there are pointers at odd offsets)
 - #134699 (Belay new reviews for workingjubilee)
 - #134701 (Correctly note item kind in `NonConstFunctionCall` error message)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-24 03:33:09 +00:00
bors
f3343420c8 Auto merge of #134625 - compiler-errors:unsafe-binders-ty, r=oli-obk
Begin to implement type system layer of unsafe binders

Mostly TODOs, but there's a lot of match arms that are basically just noops so I wanted to split these out before I put up the MIR lowering/projection part of this logic.

r? oli-obk

Tracking:

- https://github.com/rust-lang/rust/issues/130516
2024-12-24 00:51:51 +00:00
Michael Goulet
92f93f6d11 Note def descr in NonConstFunctionCall 2024-12-23 22:15:32 +00:00
Michael Goulet
9a1c5eb5b3 Begin to implement type system layer of unsafe binders 2024-12-22 21:57:57 +00:00
Scott McMurray
5ba54c9e31 Delete Rvalue::Len
Everything's moved to `PtrMetadata` instead.
2024-12-22 06:12:39 -08:00
Ralf Jung
526d29865c ptr::copy: fix docs for the overlapping case 2024-12-21 08:34:55 +01:00
bors
8a1f8039a7 Auto merge of #134550 - jhpratt:rollup-wsfmo59, r=jhpratt
Rollup of 6 pull requests

Successful merges:

 - #126118 (docs: Mention `spare_capacity_mut()` in `Vec::set_len`)
 - #132830 (Rename `elem_offset` to `element_offset`)
 - #133103 (Pass FnAbi to find_mir_or_eval_fn)
 - #134321 (Hide `= _` as associated constant value inside impl blocks)
 - #134518 (fix typos in the example code in the doc comments of `Ipv4Addr::from_bits()`, `Ipv6Addr::from_bits()` & `Ipv6Addr::to_bits()`)
 - #134521 (Arbitrary self types v2: roll loop.)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-20 07:27:15 +00:00