Commit Graph

3862 Commits

Author SHA1 Message Date
Yuki Okushi
919d6bf446
Rollup merge of #102589 - RalfJung:scoped-threads-dangling, r=m-ou-se
scoped threads: pass closure through MaybeUninit to avoid invalid dangling references

The `main` function defined here looks roughly like this, if it were written as a more explicit stand-alone function:
```rust
// Not showing all the `'lifetime` tracking, the point is that
// this closure might live shorter than `thread`.
fn thread(control: ..., closure: impl FnOnce() + 'lifetime) {
    closure();
    control.signal_done();
    // A lot of time can pass here.
}
```
Note that `thread` continues to run even after `signal_done`! Now consider what happens if the `closure` captures a reference of lifetime `'lifetime`:
- The type of `closure` is a struct (the implicit unnameable closure type) with a `&'lifetime mut T` field. References passed to a function are marked with `dereferenceable`, which is LLVM speak for *this reference will remain live for the entire duration of this function*.
- The closure runs, `signal_done` runs. Then -- potentially -- this thread gets scheduled away and the main thread runs, seeing the signal and returning to the user. Now `'lifetime` ends and the memory the reference points to might be deallocated.
- Now we have UB! The reference that as passed to `thread` with the promise of remaining live for the entire duration of the function, actually got deallocated while the function still runs. Oops.

Long-term I think we should be able to use `ManuallyDrop` to fix this without `unsafe`, or maybe a new `MaybeDangling` type. I am working on an RFC for that. But in the mean time it'd be nice to fix this so that Miri with `-Zmiri-retag-fields` (which is needed for "full enforcement" of all the LLVM flags we generate) stops erroring on scoped threads.

Fixes https://github.com/rust-lang/rust/issues/101983
r? `@m-ou-se`
2022-10-11 18:37:54 +09:00
Yuki Okushi
e0954cadc8
Rollup merge of #102412 - joboet:dont_panic, r=m-ou-se
Never panic in `thread::park` and `thread::park_timeout`

fixes #102398

`@rustbot` label +T-libs +T-libs-api
2022-10-11 18:37:53 +09:00
Yuki Okushi
387df55f26
Rollup merge of #102277 - mgeisler:rwlock, r=m-ou-se
Consistently write `RwLock`

Before the documentation sometimes referred to an "rwlock" and sometimes to "`RwLock`".
2022-10-11 18:37:52 +09:00
Dylan DPC
302bf31826
Rollup merge of #102794 - dtolnay:termination, r=thomcc
Make tests capture the error printed by a Result return

An error returned by tests previously would get written directly to stderr, instead of to the capture buffer set up by the test harness. This PR makes it write to the capture buffer so that it can be integrated as part of the test output by build tools such as `buck test`, since being able to read the error message returned by a test is pretty critical to debugging why the test failed.

<br>

**Before:**

```rust
// tests/test.rs

#[test]
fn test() -> Result<(), &'static str> {
    println!("STDOUT");
    eprintln!("STDERR");
    Err("RESULT")
}
```

```console
$ cargo build --test test
$ target/debug/deps/test-???????????????? -Z unstable-options --format=json
{ "type": "suite", "event": "started", "test_count": 1 }
{ "type": "test", "event": "started", "name": "test" }
Error: "RESULT"
{ "type": "test", "name": "test", "event": "failed", "stdout": "STDOUT\nSTDERR\n" }
{ "type": "suite", "event": "failed", "passed": 0, "failed": 1, "ignored": 0, "measured": 0, "filtered_out": 0, "exec_time": 0.00040313 }
```

**After:**

```console
$ target/debug/deps/test-???????????????? -Z unstable-options --format=json
{ "type": "suite", "event": "started", "test_count": 1 }
{ "type": "test", "event": "started", "name": "test" }
{ "type": "test", "name": "test", "event": "failed", "stdout": "STDOUT\nSTDERR\nError: \"RESULT\"" }
{ "type": "suite", "event": "failed", "passed": 0, "failed": 1, "ignored": 0, "measured": 0, "filtered_out": 0, "exec_time": 0.000261894 }
```
2022-10-10 13:43:41 +05:30
bors
81f3919303 Auto merge of #102850 - JohnTitor:rollup-lze1w03, r=JohnTitor
Rollup of 8 pull requests

Successful merges:

 - #101118 (fs::get_mode enable getting the data via fcntl/F_GETFL on major BSD)
 - #102072 (Add `ptr::Alignment` type)
 - #102799 (rustdoc: remove hover gap in file picker)
 - #102820 (Show let-else suggestion on stable.)
 - #102829 (rename `ImplItemKind::TyAlias` to `ImplItemKind::Type`)
 - #102831 (Don't use unnormalized type in `Ty::fn_sig` call in rustdoc `clean_middle_ty`)
 - #102834 (Remove unnecessary `lift`/`lift_to_tcx` calls from rustdoc)
 - #102838 (remove cfg(bootstrap) from Miri)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-10-09 18:15:26 +00:00
Yuki Okushi
d0f1cf5de7
Rollup merge of #101118 - devnexen:fs_getmode_bsd, r=Mark-Simulacrum
fs::get_mode enable getting the data via fcntl/F_GETFL on major BSD

supporting this flag.
2022-10-10 00:09:39 +09:00
bors
1b225414f3 Auto merge of #93668 - SUPERCILEX:path_alloc, r=joshtriplett
Reduce CString allocations in std as much as possible

Currently, every operation involving paths in `fs` allocates memory to hold the path before sending it through the syscall. This PR instead uses a stack allocation (chosen size is somewhat arbitrary) when the path is short before falling back to heap allocations for long paths.

Benchmarks show that the stack allocation is ~2x faster for short paths:

```
test sys::unix::fd::tests::bench_heap_path_alloc                  ... bench:          34 ns/iter (+/- 2)
test sys::unix::fd::tests::bench_stack_path_alloc                 ... bench:          15 ns/iter (+/- 1)
```

For long paths, I couldn't find any measurable difference.

---

I'd be surprised if I was the first to think of this, so I didn't fully flush out the PR. If this change is desirable, I'll make use of `run_with_cstr` across all platforms in every fs method (currently just unix open for testing). I also added an `impl From<FromBytesWithNulError>` which is presumably a no-no (or at least needs to be done in another PR).

---

Also see https://github.com/nix-rust/nix/pull/1655 with a bunch of discussion where I'm doing something similar.
2022-10-09 15:07:10 +00:00
Michael Howell
c58886d428
Rollup merge of #102812 - est31:remove_lazy, r=dtolnay
Remove empty core::lazy and std::lazy

PR #98165 with commits 7c360dc117 and c1a2db3372 has moved all of the components of these modules into different places, namely {std,core}::sync and {std,core}::cell. The empty modules remained. As they are unstable, we can simply remove them.
2022-10-08 18:15:01 -07:00
est31
4d9d7bf312 Remove empty core::lazy and std::lazy
PR #98165 with commits 7c360dc117 and c1a2db3372
has moved all of the components of these modules into different places,
namely {std,core}::sync and {std,core}::cell. The empty
modules remained. As they are unstable, we can simply remove them.
2022-10-08 15:55:15 +02:00
bors
a688a0305f Auto merge of #99505 - joboet:futex_once, r=thomcc
std: use futex in `Once`

Now that we have efficient locks, let's optimize the rest of `sync` as well. This PR adds a futex-based implementation for `Once`, which drastically simplifies the implementation compared to the generic version, which is provided as fallback for platforms without futex (Windows only supports them on newer versions, so it uses the fallback for now).

Instead of storing a linked list of waiters, the new implementation adds another state (`QUEUED`), which is set when there are waiting threads. These now use `futex_wait` on that state and are woken by the running thread when it finishes and notices the `QUEUED` state, thereby avoiding unnecessary calls to `futex_wake_all`.
2022-10-08 03:50:07 +00:00
David Tolnay
293f662ca9
Make tests capture the error printed by a Result return 2022-10-07 18:25:32 -07:00
Dylan DPC
fe4200365e
Rollup merge of #102760 - saethlin:dont-reinit-buffer, r=Mark-Simulacrum
Avoid repeated re-initialization of the BufReader buffer

Fixes https://github.com/rust-lang/rust/issues/102727

We accidentally removed this in https://github.com/rust-lang/rust/pull/98748. It looks so redundant. But it isn't.

The default `Read::read_buf` will defensively initialize the whole buffer, if any of it is indicated to be uninitialized. In uses where reads from the wrapped `Read` impl completely fill the `BufReader`, `initialized` and `filled` are the same, and this extra member isn't required. But in the reported issue, the `BufReader` wraps a `Read` impl which will _never_ fill the whole buffer. So the default `Read::read_buf` implementation repeatedly re-initializes the extra space in the buffer.

This adds back the extra `initialized` member, which ensures that the default `Read::read_buf` only zero-initialized the buffer once, and I've tried to add a comment which explains this whole situation.
2022-10-07 22:05:31 +05:30
Dylan DPC
e461e94165
Rollup merge of #102475 - RalfJung:unsafe, r=dtolnay
unsafe keyword: trait examples and unsafe_op_in_unsafe_fn update

Having a safe `fn` in an `unsafe trait` vs an `unsafe fn` in a safe `trait` are pretty different situations, but the distinction is subtle and can confuse even seasoned Rust developers. So let's have explicit examples of both. I also removed the existing `unsafe trait` example since it was rather strange.

Also the `unsafe_op_in_unsafe_fn` lint can help disentangle the two sides of `unsafe`, so update the docs to account for that.
2022-10-07 22:05:30 +05:30
Ralf Jung
c30dcff97a review feedback 2022-10-07 15:21:47 +02:00
joboet
5d0211dc03
std: use futex in Once 2022-10-07 12:12:36 +02:00
Ben Kimock
95ae993bd8 Avoid defensive re-initialization of the BufReader buffer 2022-10-06 23:31:57 -04:00
bors
2d46584fae Auto merge of #99497 - vladimir-ea:stdlib_os_api_watchos, r=thomcc
Standard library OS support for Apple WatchOS

This PR was split from https://github.com/rust-lang/rust/pull/98101
2022-10-06 12:14:21 +00:00
Matthias Krüger
6d8cea63db
Rollup merge of #102693 - BlackHoleFox:revert-apple-entropy-changes, r=thomcc
Revert "Use getentropy when possible on all Apple platforms"

Per https://github.com/rust-lang/rust/issues/102643, This reverts commit 3fc35b5b93 to avoid breaking any Rust on iOS users.

Closes https://github.com/rust-lang/rust/issues/102643
2022-10-06 07:07:36 +02:00
BlackHoleFox
a955ef2c8c Revert "Use getentropy when possible on all Apple platforms"
This reverts commit 3fc35b5b93.
2022-10-05 00:48:22 -05:00
Michael Howell
4025e95113
Rollup merge of #102574 - aDotInTheVoid:const_collections_with_hasher, r=oli-obk,fee1-dead
Make Hash{Set,Map}::with_hasher unstably const

Makes  [`HashMap::with_hasher`](https://doc.rust-lang.org/stable/std/collections/hash_map/struct.HashMap.html#method.with_hasher) and [`HashSet::with_hasher`](https://doc.rust-lang.org/stable/std/collections/hash_set/struct.HashSet.html#method.with_hasher) `const`.

This allows

```rust
static GlobalState: Mutex<HashMap<i32, i32, SomeHasher>> = Mutex::new(HashMap::with_hasher(SomeHasher::new()))
```

Tracking issue: #102575
2022-10-04 20:45:12 -07:00
bors
d4846f9d03 Auto merge of #101768 - sunfishcode:sunfishcode/wasi-stdio-lock-asfd, r=joshtriplett
Add `AsFd` implementations for stdio lock types on WASI.

This mirrors the implementations on Unix platforms, and also mirrors the existing `AsRawFd` impls.

This is similar to #100892, but is for the `*Lock` types.
2022-10-04 23:22:16 +00:00
Alex Saveau
86974b83af
Reduce CString allocations in std as much as possible
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
2022-10-03 11:13:17 -07:00
Josh Triplett
905ebc31b1 Add SAFETY comments for AsFd implementations on stdin/stdout/stderr 2022-10-03 08:30:58 -07:00
Dan Gohman
625ebf603d Add stability attributes. 2022-10-03 08:30:55 -07:00
Ralf Jung
78b577c065 scoped threads: pass closure through MaybeUninit to avoid invalid dangling references 2022-10-03 15:35:29 +02:00
bors
91931ec2fc Auto merge of #98354 - camsteffen:is-some-and-by-value, r=m-ou-se
Change `is_some_and` to take by value

Consistent with other function-accepting `Option` methods.

Tracking issue: #93050

r? `@m-ou-se`
2022-10-02 12:48:15 +00:00
Nixon Enraght-Moony
346a49fe48 Make Hash{Set,Map}::with_hasher unstably const 2022-10-02 13:07:13 +01:00
Matthias Krüger
649c09996f
Rollup merge of #102313 - anirudh24seven:update_sleep_ms_doc, r=Mark-Simulacrum
Update docs so that deprecated method points to relevant method

The docs for the deprecated 'park_timeout_ms' method suggests that the user 'use park_timeout' method instead (at https://doc.rust-lang.org/std/thread/index.html).

Making a similar change so that the docs for the deprecated `sleep_ms` method suggest that the user `use sleep` method instead.
2022-10-02 03:16:38 +02:00
Cameron Steffen
4f12de0660 Change feature name to is_some_and 2022-10-01 11:45:52 -05:00
beetrees
c66860ab3e
SetFileTime doesn't allow setting the file time to 0xFFFF_FFFF_FFFF_FFFF 2022-10-01 03:23:08 +01:00
beetrees
39c0b00cf9
Error instead of panicking when setting file times if the passed SystemTime doesn't fit into the required type 2022-10-01 03:22:55 +01:00
Vladimir Michael Eatwell
2edbcf7c23 Standard library OS support for Apple WatchOS 2022-09-30 11:25:38 +01:00
Ralf Jung
595e192274 unsafe keyword: trait examples and unsafe_op_in_unsafe_fn update 2022-09-29 16:03:07 +02:00
Yuki Okushi
5c731cd796
Rollup merge of #102433 - RalfJung:temp-dir-typo, r=thomcc
env::temp_dir: fix a typo
2022-09-29 11:42:06 +09:00
Yuki Okushi
8e4869e862
Rollup merge of #102368 - beetrees:nano-niche, r=joshtriplett
Add a niche to `Duration`, unix `SystemTime`, and non-apple `Instant`

As the nanoseconds fields is always between `0` and `(NANOS_PER_SEC - 1)` inclusive, use the `rustc_layout_scalar_valid_range` attributes to create a niche in the nanosecond field of `Duration` and `Timespec` (which is used to implement unix `SystemTime` and non-apple unix `Instant`; windows `Instant` is implemented with `Duration` and therefore will also benefit). This change has the benefit of making `Option<T>` the same size as `T` for the previously mentioned types. Also shrinks the nanoseconds field of `Timespec` to a `u32` as nanoseconds do not need the extra range of an `i64`, shrinking `Timespec` by 4 bytes on 32-bit platforms.

r? ```@joshtriplett```
2022-09-29 11:42:05 +09:00
Yuki Okushi
7cd4780c91
Rollup merge of #98368 - sunfishcode:sunfishcode/std-os-fd, r=joshtriplett
Make `std::os::fd` public.

`std::os::fd` defines types like `OwnedFd` and `RawFd` and is common
between Unix and non-Unix platforms that share a basic file-descriptor
concept. Rust currently uses this internally to simplify its own code,
but it would be useful for external users in the same way, so make it
public.

This means that `OwnedFd` etc. will all appear in three places, for
example on unix platforms:
 - `std::os::fd::OwnedFd`
 - `std::os::unix::io::OwnedFd`
 - `std::os::unix::prelude::OwnedFd`

r? `````@joshtriplett`````
2022-09-29 11:42:03 +09:00
Ralf Jung
5baceaf796 env::temp_dir: fix a typo 2022-09-28 21:51:09 +02:00
beetrees
a913277829
Add a niche to Duration, unix SystemTime, and non-apple Instant 2022-09-28 18:15:10 +01:00
joboet
b0b9f5bc26
std: never panic in thread::park and thread::park_timeout 2022-09-28 16:54:00 +02:00
Yuki Okushi
9436ffc226
Rollup merge of #102288 - mejrs:inner, r=compiler-errors
Suggest unwrapping `???<T>` if a method cannot be found on it but is present on `T`.

This suggests various ways to get inside wrapper types if the method cannot be found on the wrapper type, but is present on the wrappee.

For this PR, those wrapper types include `Localkey`, `MaybeUninit`, `RefCell`, `RwLock` and `Mutex`.
2022-09-28 13:07:17 +09:00
Yuki Okushi
07bb2e6527
Rollup merge of #102232 - Urgau:stabilize-bench_black_box, r=TaKO8Ki
Stabilize bench_black_box

This PR stabilize `feature(bench_black_box)`.

```rust
pub fn black_box<T>(dummy: T) -> T;
```

The FCP was completed in https://github.com/rust-lang/rust/issues/64102.

`@rustbot` label +T-libs-api -T-libs
2022-09-28 13:07:17 +09:00
Matthias Krüger
ad57d5f27c
Rollup merge of #101555 - jhpratt:stabilize-mixed_integer_ops, r=joshtriplett
Stabilize `#![feature(mixed_integer_ops)]`

Tracked and FCP completed in #87840.

````@rustbot```` label +T-libs-api +S-waiting-on-review +relnotes

r? rust-lang/t-libs-api
2022-09-27 21:42:21 +02:00
mejrs
f3ac328d58 Address feedback 2022-09-27 21:42:09 +02:00
mejrs
c4c9415132 Wrapper suggestions 2022-09-27 21:42:09 +02:00
Urgau
9ad2f00f6a Stabilize bench_black_box 2022-09-27 17:38:51 +02:00
Anirudh
4c42e3831f Update docs so that deprecated method points to relevant method 2022-09-26 19:28:51 +05:30
Pietro Albini
3975d55d98
remove cfg(bootstrap) 2022-09-26 10:14:45 +02:00
Pietro Albini
d0305b3d00
replace stabilization placeholders 2022-09-26 10:13:44 +02:00
Martin Geisler
f67184fdcb Consistently write RwLock
Before the documentation sometimes referred to an "rwlock" and sometimes to "`RwLock`".
2022-09-25 21:09:38 +02:00
bors
8e9c93df46 Auto merge of #99609 - workingjubilee:lossy-unix-strerror, r=thomcc
Recover error strings on Unix from_lossy_utf8

Some language settings can result in unreliable UTF-8 being produced.
This can result in failing to emit the error string, panicking instead.
from_lossy_utf8 allows us to assume these strings usually will be fine.

This fixes rust-lang#99535.
2022-09-25 06:53:14 +00:00