Commit Graph

3651 Commits

Author SHA1 Message Date
Guillaume Gomez
ef81fca760
Rollup merge of #94247 - saethlin:chunksmut-aliasing, r=the8472
Fix slice::ChunksMut aliasing

Fixes https://github.com/rust-lang/rust/issues/94231, details in that issue.
cc `@RalfJung`

This isn't done just yet, all the safety comments are placeholders. But otherwise, it seems to work.

I don't really like this approach though. There's a lot of unsafe code where there wasn't before, but as far as I can tell the only other way to uphold the aliasing requirement imposed by `__iterator_get_unchecked` is to use raw slices, which I think require the same amount of unsafe code. All that would do is tie the `len` and `ptr` fields together.

Oh I just looked and I'm pretty sure that `ChunksExactMut`, `RChunksMut`, and `RChunksExactMut` also need to be patched. Even more reason to put up a draft.
2022-07-27 17:55:01 +02:00
Yuki Okushi
28b44ff5d4
Rollup merge of #99704 - fee1-dead-contrib:add_self_tilde_const_trait, r=oli-obk
Add `Self: ~const Trait` to traits with `#[const_trait]`

r? `@oli-obk`
2022-07-27 19:05:33 +09:00
Ben Kimock
746afe8952 Clarify safety comments 2022-07-26 21:25:56 -04:00
Ben Kimock
e2e3a88771 Explain how *mut [T] helps, and how we rely on the check in split_at_mut 2022-07-26 18:37:00 -04:00
Matthias Krüger
a739e28aea
Rollup merge of #99757 - asquared31415:patch-1, r=Dylan-DPC
Make `transmute_copy` docs read better
2022-07-26 16:57:52 +02:00
Deadbeef
a6f9826979 Add Self: ~const Trait to traits with #[const_trait] 2022-07-26 14:14:21 +00:00
asquared31415
e241d5a093
Make transmute_copy docs read better 2022-07-26 05:59:44 -04:00
Dylan DPC
deab13c681
Rollup merge of #99692 - RalfJung:too-far, r=oli-obk
interpret, ptr_offset_from: refactor and test too-far-apart check

We didn't have any tests for the "too far apart" message, and indeed that check mostly relied on the in-bounds check and was otherwise probably not entirely correct... so I rewrote that check, and it is before the in-bounds check so we can test it separately.
2022-07-26 14:26:58 +05:30
Yuki Okushi
aeca079d7e
Rollup merge of #99084 - RalfJung:write_bytes, r=thomcc
clarify how write_bytes can lead to UB due to invalid values

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

Cc ``@5225225``
2022-07-26 07:14:46 +09:00
Yuki Okushi
c1647e10ad
Rollup merge of #92390 - fee1-dead-contrib:const_cmp, r=oli-obk
Constify a few `(Partial)Ord` impls

Only a few `impl`s are constified for now, as #92257 has not landed in the bootstrap compiler yet and quite a few impls would need that fix.

This unblocks #92228, which unblocks marking iterator methods as `default_method_body_is_const`.
2022-07-26 07:14:43 +09:00
Ralf Jung
58f2ede15f interpret, ptr_offset_from: refactor and test too-far-apart check 2022-07-24 19:35:40 -04:00
Ralf Jung
d10a7b1243 add miri-track-caller to some intrinsic-exposing methods 2022-07-24 14:49:33 -04:00
Deadbeef
65fca6db19 add const hack comment 2022-07-24 12:01:23 +00:00
Deadbeef
a89510e5f9 Add issue numbers 2022-07-24 12:01:22 +00:00
Deadbeef
9fc5463c18 Constify a few const (Partial)Ord impls 2022-07-24 12:01:22 +00:00
bors
35a0617248 Auto merge of #98674 - RalfJung:miri-stacktrace-pruning, r=Mark-Simulacrum
miri: prune some atomic operation and raw pointer details from stacktrace

Since Miri removes `track_caller` frames from the stacktrace, adding that attribute can help make backtraces more readable (similar to how it makes panic locations better). I made them only show up with `cfg(miri)` to make sure the extra arguments induced by `track_caller` do not cause any runtime performance trouble.

This is also testing the waters for whether the libs team is okay with having these attributes in their code, or whether you'd prefer if we find some other way to do this. If you are fine with this, we will probably want to add it to a lot more functions (all the other atomic operations, to start).

Before:
```
error: Undefined Behavior: Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
    --> /home/r/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:2594:23
     |
2594 |             SeqCst => intrinsics::atomic_load_seqcst(dst),
     |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
     |
     = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
     = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

     = note: inside `std::sync::atomic::atomic_load::<usize>` at /home/r/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:2594:23
     = note: inside `std::sync::atomic::AtomicUsize::load` at /home/r/.rustup/toolchains/miri/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:1719:26
note: inside closure at ../miri/tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
    --> ../miri/tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
     |
22   |             (&*c.0).load(Ordering::SeqCst)
     |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```

After:
```
error: Undefined Behavior: Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
  --> tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
   |
22 |             (&*c.0).load(Ordering::SeqCst)
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Data race detected between Atomic Load on Thread(id = 2) and Write on Thread(id = 1) at alloc1727 (current vector clock = VClock([9, 0, 6]), conflicting timestamp = VClock([0, 6]))
   |
   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information

   = note: inside closure at tests/fail/data_race/atomic_read_na_write_race1.rs:22:13
```
2022-07-24 06:46:46 +00:00
bors
ed793d86da Auto merge of #93397 - joshtriplett:sort-floats, r=Amanieu
Add `[f32]::sort_floats` and `[f64]::sort_floats`

It's inconvenient to sort a slice or Vec of floats, compared to sorting integers. To simplify numeric code, add a convenience method to `[f32]` and `[f64]` to sort them using `sort_unstable_by` with `total_cmp`.
2022-07-23 02:47:54 +00:00
Ralf Jung
35c6dec921 adjust UnsafeCell documentation 2022-07-22 14:25:41 -04:00
bors
41419e7036 Auto merge of #99491 - workingjubilee:sync-psimd, r=workingjubilee
Sync in portable-simd subtree

r? `@ghost`
2022-07-22 09:48:00 +00:00
Dylan DPC
5df3b98321
Rollup merge of #99579 - CleanCut:expect-warning, r=joshtriplett
Add same warning to Result::expect as Result::unwrap

I was reading a recent blog post by Jimmy Hartzell and [he noted](https://www.thecodedmessage.com/posts/2022-07-14-programming-unwrap/#context):

> I will however note that the documentation of `unwrap` comes with [a warning not to use it](https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap). The warning is framed in terms of the fact that `unwrap` may panic, but the [documentation of `expect`](https://doc.rust-lang.org/std/result/enum.Result.html#method.expect), where this is equally true, does not come with such a warning.

It _is_ equally true. Let's add the same warning to `expect`. This PR is a copy-and-paste of the warning text from the docstring for `unwrap`.
2022-07-22 11:53:43 +05:30
Dylan DPC
ad31d5c6a5
Rollup merge of #98174 - Kixunil:rename_ptr_as_mut_const_to_cast, r=scottmcm
Rename `<*{mut,const} T>::as_{const,mut}` to `cast_`

This renames the methods to use the `cast_` prefix instead of `as_` to
make it more readable and avoid confusion with `<*mut T>::as_mut()`
which is `unsafe` and returns a reference.

Sorry, didn't notice ACP process exists, opened https://github.com/rust-lang/libs-team/issues/51

See #92675
2022-07-22 11:53:39 +05:30
bors
aa01891700 Auto merge of #99420 - RalfJung:vtable, r=oli-obk
make vtable pointers entirely opaque

This implements the scheme discussed in https://github.com/rust-lang/unsafe-code-guidelines/issues/338: vtable pointers should be considered entirely opaque and not even readable by Rust code, similar to function pointers.

- We have a new kind of `GlobalAlloc` that symbolically refers to a vtable.
- Miri uses that kind of allocation when generating a vtable.
- The codegen backends, upon encountering such an allocation, call `vtable_allocation` to obtain an actually dataful allocation for this vtable.
- We need new intrinsics to obtain the size and align from a vtable (for some `ptr::metadata` APIs), since direct accesses are UB now.

I had to touch quite a bit of code that I am not very familiar with, so some of this might not make much sense...
r? `@oli-obk`
2022-07-22 01:33:49 +00:00
Nathan Stocks
7ba0be832a add same warning to Result::expect as Result::unwrap 2022-07-21 18:15:24 -06:00
Matthias Krüger
9610c71b1e
Rollup merge of #99454 - benluelo:control-flow/continue-combinators, r=scottmcm
Add map_continue and continue_value combinators to ControlFlow

As suggested in this comment: https://github.com/rust-lang/rust/issues/75744#issuecomment-1188549494

Related tracking issue: https://github.com/rust-lang/rust/issues/75744

r? ``````@scottmcm``````
2022-07-21 18:42:04 +02:00
Martin Habovstiak
eb5acc9b9b Rename <*{mut,const} T>::as_{const,mut} to cast_
This renames the methods to use the `cast_` prefix instead of `as_` to
make it more readable and avoid confusion with `<*mut T>::as_mut()`
which is `unsafe` and returns a reference.

See #92675
2022-07-21 18:30:05 +02:00
Jubilee Young
f8aa494c69 Introduce core::simd trait imports in tests 2022-07-20 18:08:20 -07:00
Ralf Jung
0318f07bdd various nits from review 2022-07-20 17:12:08 -04:00
Ralf Jung
114da84996 use extern type for extra opaqueness 2022-07-20 17:12:07 -04:00
Ralf Jung
5e840c5c8c incorporate some review feedback 2022-07-20 17:12:07 -04:00
Ralf Jung
8affef2ccb add intrinsic to access vtable size and align 2022-07-20 17:12:07 -04:00
Ralf Jung
13877a965d prune raw pointer read and write methods from Miri backtraces 2022-07-20 16:42:20 -04:00
Ralf Jung
2b269cad43 miri: prune some atomic operation details from stacktrace 2022-07-20 16:34:24 -04:00
benluelo
1993a5f7a8
Add map_continue and continue_value combinators to ControlFlow
Fix type error

Fix continue_value doc comment
2022-07-20 16:32:09 -04:00
Dylan DPC
feebc5f4d5
Rollup merge of #99452 - Stargateur:fix/typo, r=JohnTitor
int_macros was only using to_xe_bytes_doc and not from_xe_bytes_doc

typo in doc [here](https://doc.rust-lang.org/std/primitive.isize.html#method.from_ne_bytes) "returns" => "takes"

`@rustbot` label +T-rustdoc
2022-07-20 11:29:40 +05:30
bors
9a7b7d5e50 Auto merge of #98180 - notriddle:notriddle/rustdoc-fn, r=petrochenkov,GuillaumeGomez
Improve the function pointer docs

This is #97842 but for function pointers instead of tuples. The concept is basically the same.

* Reduce duplicate impls; show `fn (T₁, T₂, …, Tₙ)` and include a sentence saying that there exists up to twelve of them.
* Show `Copy` and `Clone`.
* Show auto traits like `Send` and `Sync`, and blanket impls like `Any`.

https://notriddle.com/notriddle-rustdoc-test/std/primitive.fn.html
2022-07-19 19:36:57 +00:00
Michael Howell
ddb5a2638a Use T for all the function primitive docs lists 2022-07-19 08:52:25 -07:00
Michael Howell
5271e32c46 Improve the function pointer docs
* Reduce duplicate impls; show only the `fn (T)` and include a sentence
  saying that there exists up to twelve of them.
* Show `Copy` and `Clone`.
* Show auto traits like `Send` and `Sync`, and blanket impls like `Any`.
2022-07-19 08:52:24 -07:00
bors
a289cfcfb3 Auto merge of #99462 - matthiaskrgr:rollup-ihhwaru, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #98028 (Add E0790 as more specific variant of E0283)
 - #99384 (use body's param-env when checking if type needs drop)
 - #99401 (Avoid `Symbol` to `&str` conversions)
 - #99419 (Stabilize `core::task::ready!`)
 - #99435 (Revert "Stabilize $$ in Rust 1.63.0")
 - #99438 (Improve suggestions for `NonZeroT` <- `T` coercion error)
 - #99441 (Update mdbook)
 - #99453 (⬆️ rust-analyzer)
 - #99457 (use `par_for_each_in` in `par_body_owners` and `collect_crate_mono_items`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-07-19 13:49:56 +00:00
Matthias Krüger
e6a100baa2
Rollup merge of #99438 - WaffleLapkin:dont_wrap_in_non_zero, r=compiler-errors
Improve suggestions for `NonZeroT` <- `T` coercion error

Currently, when encountering a type mismatch error with `NonZeroT` and `T` (for example `NonZeroU8` and `u8`) we errorneusly suggest wrapping expression in `NonZeroT`:
```text
error[E0308]: mismatched types
 --> ./t.rs:7:35
  |
7 |     let _: std::num::NonZeroU64 = 1;
  |            --------------------   ^ expected struct `NonZeroU64`, found integer
  |            |
  |            expected due to this
  |
help: try wrapping the expression in `std::num::NonZeroU64`
  |
7 |     let _: std::num::NonZeroU64 = std::num::NonZeroU64(1);
  |                                   +++++++++++++++++++++ +
```

I've removed this suggestion and added suggestions to call `new` (for `Option<NonZeroT>` <- `T` case) or `new` and `unwrap` (for `NonZeroT` <- `T` case):

```text
error[E0308]: mismatched types
 --> ./t.rs:7:35
  |
7 |     let _: std::num::NonZeroU64 = 1;
  |            --------------------   ^ expected struct `NonZeroU64`, found integer
  |            |
  |            expected due to this
  |
help: Consider calling `NonZeroU64::new`
  |
7 |     let _: std::num::NonZeroU64 = NonZeroU64::new(1).unwrap();
  |                                   ++++++++++++++++ ++++++++++

error[E0308]: mismatched types
 --> ./t.rs:8:43
  |
8 |     let _: Option<std::num::NonZeroU64> = 1;
  |            ----------------------------   ^ expected enum `Option`, found integer
  |            |
  |            expected due to this
  |
  = note: expected enum `Option<NonZeroU64>`
             found type `{integer}`
help: Consider calling `NonZeroU64::new`
  |
8 |     let _: Option<std::num::NonZeroU64> = NonZeroU64::new(1);
  |                                           ++++++++++++++++ +
```

r? `@compiler-errors`
2022-07-19 13:30:49 +02:00
Matthias Krüger
7d754976c4
Rollup merge of #99419 - yoshuawuyts:stabilize-task-ready, r=Mark-Simulacrum
Stabilize `core::task::ready!`

This stabilizes `core::task::ready!` for Rust 1.64. The FCP for stabilization was just completed here https://github.com/rust-lang/rust/issues/70922#issuecomment-1186231855. Thanks!

Closes #70922

cc/ ``@rust-lang/libs-api``
2022-07-19 13:30:47 +02:00
bors
8bd12e8cca Auto merge of #98912 - nrc:provider-it, r=yaahc
core::any: replace some generic types with impl Trait

This gives a cleaner API since the caller only specifies the concrete type they usually want to.

r? `@yaahc`
2022-07-19 11:28:20 +00:00
Antoine PLASKOWSKI
94f633b002 int_macros was only using to_xe_bytes_doc and not from_xe_bytes_doc 2022-07-19 08:32:08 +02:00
Dylan DPC
e301cd39ad
Rollup merge of #99434 - timvermeulen:skip_next_non_fused, r=scottmcm
Fix `Skip::next` for non-fused inner iterators

`iter.skip(n).next()` will currently call `nth` and `next` in succession on `iter`, without checking whether `nth` exhausts the iterator. Using `?` to propagate a `None` value returned by `nth` avoids this.
2022-07-19 11:38:58 +05:30
Dylan DPC
9f6a2fde34
Rollup merge of #99335 - Dav1dde:fromstr-docs, r=JohnTitor
Use split_once in FromStr docs

Current implementation:

```rust
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
                                 .split(',')
                                 .collect();

        let x_fromstr = coords[0].parse::<i32>()?;
        let y_fromstr = coords[1].parse::<i32>()?;

        Ok(Point { x: x_fromstr, y: y_fromstr })
    }
```

Creating the vector is not necessary, `split_once` does the job better.

Alternatively we could also remove `trim_matches` with `strip_prefix` and `strip_suffix`:

```rust
        let (x, y) = s
            .strip_prefix('(')
            .and_then(|s| s.strip_suffix(')'))
            .and_then(|s| s.split_once(','))
            .unwrap();
```

The question is how much 'correctness' is too much and distracts from the example. In a real implementation you would also not unwrap (or originally access the vector without bounds checks), but implementing a custom Error and adding a `From<ParseIntError>` and implementing the `Error` trait adds a lot of code to the example which is not relevant to the `FromStr` trait.
2022-07-19 11:38:53 +05:30
Maybe Waffle
7163e7ff65 Suggest a fix for NonZero* <- * coercion error 2022-07-19 00:13:29 +04:00
Tim Vermeulen
e52837c362 Add note to test about Unfuse 2022-07-18 21:53:35 +02:00
Tim Vermeulen
50c612faef Fix Skip::next for non-fused inner iterators 2022-07-18 21:10:47 +02:00
Dylan DPC
5ccdf1f6f7
Rollup merge of #98839 - 5225225:assert_transmute_copy_size, r=thomcc
Add assertion that `transmute_copy`'s U is not larger than T

This is called out as a safety requirement in the docs, but because knowing this can be done at compile time and constant folded (just like the `align_of` branch is removed), we can just panic here.

I've looked at the asm (using `cargo-asm`) of a function that both is correct and incorrect, and the panic is completely removed, or is unconditional, without needing build-std.

I don't expect this to cause much breakage in the wild. I scanned through https://miri.saethlin.dev/ub for issues that would look like this (error: Undefined Behavior: memory access failed: alloc1768 has size 1, so pointer to 8 bytes starting at offset 0 is out-of-bounds), but couldn't find any.

That doesn't rule out it happening in crates tested that fail earlier for some other reason, though, but it indicates that doing this is rare, if it happens at all. A crater run for this would need to be build and test, since this is a runtime thing.

Also added a few more transmute_copy tests.
2022-07-18 21:14:42 +05:30
Yoshua Wuyts
454313fe83 stabilize core::task::ready! 2022-07-18 16:04:52 +02:00
bors
9ed0bf9f2b Auto merge of #99223 - saethlin:panicless-split-mut, r=Mark-Simulacrum
Rearrange slice::split_mut to remove bounds check

Closes https://github.com/rust-lang/rust/issues/86313

Turns out that all we need to do here is reorder the bounds checks to convince LLVM that all the bounds checks can be removed. It seems like LLVM just fails to propagate the original length information past the first bounds check and into the second one. With this implementation it doesn't need to, each check can be proven inbounds based on the one immediately previous.

I've gradually convinced myself that this implementation is unambiguously better based on the above logic, but maybe this is still deserving of a codegen test?

Also the mentioned borrowck limitation no longer seems to exist.
2022-07-18 10:16:58 +00:00