Commit Graph

3514 Commits

Author SHA1 Message Date
Chris Denton
8d4adad953
Windows: Use FindFirstFileW if metadata fails
Usually opening a file handle with access set to metadata only will always succeed, even if the file is locked. However some special system files, such as `C:\hiberfil.sys`, are locked by the system in a way that denies even that. So as a fallback we try reading the cached metadata from the directory.
2022-07-05 09:15:35 +01:00
Chris Denton
13ab7962ac
impl From<c::WIN32_FIND_DATAW> for FileAttr 2022-07-05 07:53:27 +01:00
Dylan DPC
d26ccf7067
Rollup merge of #97300 - ChayimFriedman2:patch-1, r=dtolnay
Implement `FusedIterator` for `std::net::[Into]Incoming`

They never return `None`, so they trivially fulfill the contract.

What should I put for the stability attribute of `Incoming`?
2022-07-05 10:42:52 +05:30
bors
b04bfb4aea Auto merge of #97437 - jyn514:impl-asrawfd-arc, r=dtolnay
`impl<T: AsRawFd> AsRawFd for {Arc,Box}<T>`

This allows implementing traits that require a raw FD on Arc and Box.

Previously, you'd have to add the function to the trait itself:

```rust
trait MyTrait {
    fn as_raw_fd(&self) -> RawFd;
}

impl<T: MyTrait> MyTrait for Arc<T> {
    fn as_raw_fd(&self) -> RawFd {
        (**self).as_raw_fd()
    }
}
```

In particular, this leads to lots of "multiple applicable items in scope" errors because you have to disambiguate `MyTrait::as_raw_fd` from `AsRawFd::as_raw_fd` at each call site. In generic contexts, when passing the type to a function that takes `impl AsRawFd` it's also sometimes required to use `T: MyTrait + AsRawFd`, which wouldn't be necessary if I could write `MyTrait: AsRawFd`.

After this PR, the code can be simpler:
```rust
trait MyTrait: AsRawFd {}

impl<T: MyTrait> MyTrait for Arc<T> {}
```
2022-07-03 12:17:19 +00:00
bors
ada8c80bed Auto merge of #98673 - pietroalbini:pa-bootstrap-update, r=Mark-Simulacrum
Bump bootstrap compiler

r? `@Mark-Simulacrum`
2022-07-03 06:55:50 +00:00
David Tolnay
76c0429d86
Bump std::net::Incoming FusedIterator impl to Rust 1.64 2022-07-02 11:02:54 -07:00
bors
6a10920564 Auto merge of #97235 - nbdd0121:unwind, r=Amanieu
Fix FFI-unwind unsoundness with mixed panic mode

UB maybe introduced when an FFI exception happens in a `C-unwind` foreign function and it propagates through a crate compiled with `-C panic=unwind` into a crate compiled with `-C panic=abort` (#96926).

To prevent this unsoundness from happening, we will disallow a crate compiled with `-C panic=unwind` to be linked into `panic-abort` *if* it contains a call to `C-unwind` foreign function or function pointer. If no such call exists, then we continue to allow such mixed panic mode linking because it's sound (and stable). In fact we still need the ability to do mixed panic mode linking for std, because we only compile std once with `-C panic=unwind` and link it regardless panic strategy.

For libraries that wish to remain compile-once-and-linkable-to-both-panic-runtimes, a `ffi_unwind_calls` lint is added (gated under `c_unwind` feature gate) to flag any FFI unwind calls that will cause the linkable panic runtime be restricted.

In summary:
```rust
#![warn(ffi_unwind_calls)]

mod foo {
    #[no_mangle]
    pub extern "C-unwind" fn foo() {}
}

extern "C-unwind" {
    fn foo();
}

fn main() {
    // Call to Rust function is fine regardless ABI.
    foo::foo();
    // Call to foreign function, will cause the crate to be unlinkable to panic-abort if compiled with `-Cpanic=unwind`.
    unsafe { foo(); }
    //~^ WARNING call to foreign function with FFI-unwind ABI
    let ptr: extern "C-unwind" fn() = foo::foo;
    // Call to function pointer, will cause the crate to be unlinkable to panic-abort if compiled with `-Cpanic=unwind`.
    ptr();
    //~^ WARNING call to function pointer with FFI-unwind ABI
}
```

Fix #96926

`@rustbot` label: T-compiler F-c_unwind
2022-07-02 14:06:27 +00:00
Mark Rousskov
d8bfae4f99 Adjust for rustfmt order change 2022-07-01 18:13:55 -04:00
Pietro Albini
6b2d3d5f3c
update cfg(bootstrap)s 2022-07-01 15:48:23 +02:00
Matthias Krüger
ebecc13106
Rollup merge of #98503 - RalfJung:scope-race, r=m-ou-se
fix data race in thread::scope

Puts the `ScopeData` into an `Arc` so it sticks around as long as we need it.
This means one extra `Arc::clone` per spawned scoped thread, which I hope is fine.

Fixes https://github.com/rust-lang/rust/issues/98498
r? `````@m-ou-se`````
2022-06-30 19:55:51 +02:00
Matthias Krüger
0e71d1f237
Rollup merge of #97629 - guswynn:exclusive_struct, r=m-ou-se
[core] add `Exclusive` to sync

(discussed here: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Adding.20.60SyncWrapper.60.20to.20std)

`Exclusive` is a wrapper that exclusively allows mutable access to the inner value if you have exclusive access to the wrapper. It acts like a compile time mutex, and hold an unconditional `Sync` implementation.

## Justification for inclusion into std
- This wrapper unblocks actual problems:
  - The example that I hit was a vector of `futures::future::BoxFuture`'s causing a central struct in a script to be non-`Sync`. To work around it, you either write really difficult code, or wrap the futures in a needless mutex.
- Easy to maintain: this struct is as simple as a wrapper can get, and its `Sync` implementation has very clear reasoning
- Fills a gap: `&/&mut` are to `RwLock` as `Exclusive` is to `Mutex`

## Public Api
```rust
// core::sync
#[derive(Default)]
struct Exclusive<T: ?Sized> { ... }

impl<T: ?Sized> Sync for Exclusive {}

impl<T> Exclusive<T> {
    pub const fn new(t: T) -> Self;
    pub const fn into_inner(self) -> T;
}

impl<T: ?Sized> Exclusive<T> {
    pub const fn get_mut(&mut self) -> &mut T;
    pub const fn get_pin_mut(Pin<&mut self>) -> Pin<&mut T>;
    pub const fn from_mut(&mut T) -> &mut Exclusive<T>;
    pub const fn from_pin_mut(Pin<&mut T>) -> Pin<&mut Exclusive<T>>;
}

impl<T: Future> Future for Exclusive { ... }

impl<T> From<T> for Exclusive<T> { ... }
impl<T: ?Sized> Debug for Exclusive { ... }
```

## Naming
This is a big bikeshed, but I felt that `Exclusive` captured its general purpose quite well.

## Stability and location
As this is so simple, it can be in `core`. I feel that it can be stabilized quite soon after it is merged, if the libs teams feels its reasonable to add. Also, I don't really know how unstable feature work in std/core's codebases, so I might need help fixing them

## Tips for review
The docs probably are the thing that needs to be reviewed! I tried my best, but I'm sure people have more experience than me writing docs for `Core`

### Implementation:
The API is mostly pulled from https://docs.rs/sync_wrapper/latest/sync_wrapper/struct.SyncWrapper.html (which is apache 2.0 licenesed), and the implementation is trivial:
- its an unsafe justification for pinning
- its an unsafe justification for the `Sync` impl (mostly reasoned about by ````@danielhenrymantilla```` here: https://github.com/Actyx/sync_wrapper/pull/2)
- and forwarding impls, starting with derivable ones and `Future`
2022-06-30 19:55:50 +02:00
joboet
f7ae92c6bd
std: use futex-based locks on Fuchsia 2022-06-30 11:48:54 +02:00
Matthias Krüger
a3bdd46431
Rollup merge of #98617 - ChrisDenton:const-unwrap, r=Mark-Simulacrum
Remove feature `const_option` from std

This is part of the effort to reduce the number of unstable features used by std. This one is easy as it's only used in one place.
2022-06-28 18:34:33 +02:00
Chris Denton
720c430822
Add a fixme comment 2022-06-28 12:18:16 +01:00
Chris Denton
2ee92419dd
Remove feature const_option from std 2022-06-28 11:37:48 +01:00
Dylan DPC
f181ae9946
Rollup merge of #98555 - mkroening:hermit-lock-init, r=m-ou-se
Hermit: Fix initializing lazy locks

Closes https://github.com/hermitcore/rusty-hermit/issues/322.

The initialization function of hermit's `Condvar` is not called since https://github.com/rust-lang/rust/pull/97647 and was erroneously removed in https://github.com/rust-lang/rust/pull/97879.

r? ``@m-ou-se``

CC: ``@stlankes``
2022-06-28 15:30:06 +05:30
bors
64eb9ab869 Auto merge of #98324 - conradludgate:write-vectored-vec, r=Mark-Simulacrum
attempt to optimise vectored write

benchmarked:

old:
```
test io::cursor::tests::bench_write_vec                     ... bench:          68 ns/iter (+/- 2)
test io::cursor::tests::bench_write_vec_vectored            ... bench:         913 ns/iter (+/- 31)
```

new:
```
test io::cursor::tests::bench_write_vec                     ... bench:          64 ns/iter (+/- 0)
test io::cursor::tests::bench_write_vec_vectored            ... bench:         747 ns/iter (+/- 27)
```

More unsafe than I wanted (and less gains) in the end, but it still does the job
2022-06-28 06:25:19 +00:00
Ralf Jung
af0c1fe83d fix data race in thread::scope 2022-06-27 16:50:42 -04:00
Martin Kröning
0c8860273c Hermit: Make Mutex::init a no-op 2022-06-26 23:20:41 +02:00
Martin Kröning
f954f7b23b Hermit: Fix initializing lazy locks 2022-06-26 23:19:38 +02:00
Matthias Krüger
935958e6e4
Rollup merge of #98541 - Veykril:patch-2, r=Dylan-DPC
Update `std::alloc::System` doc example code style

`return` on the last line of a block is unidiomatic so I don't think the example should be using that here
2022-06-26 19:47:09 +02:00
Matthias Krüger
c348beacea
Rollup merge of #97140 - joboet:solid_parker, r=m-ou-se
std: use an event-flag-based thread parker on SOLID

`Mutex` and `Condvar` are being replaced by more efficient implementations, which need thread parking themselves (see #93740). Therefore, the generic `Parker` needs to be replaced on all platforms where the new lock implementation will be used, which, after #96393, are SOLID, SGX and Hermit (more PRs coming soon).

SOLID, conforming to the [μITRON specification](http://www.ertl.jp/ITRON/SPEC/FILE/mitron-400e.pdf), has event flags, which are a thread parking primitive very similar to `Parker`. However, they do not make any atomic ordering guarantees (even though those can probably be assumed) and necessitate a system call even when the thread token is already available. Hence, this `Parker`, like the Windows parker, uses an extra atomic state variable.

I future-proofed the code by wrapping the event flag in a `WaitFlag` structure, as both SGX and Hermit can share the Parker implementation, they just have slightly different primitives (SGX uses signals and Hermit has a thread blocking API).

`````@kawadakk````` I assume you are the target maintainer? Could you test this for me?
2022-06-26 19:46:59 +02:00
Conrad Ludgate
803083a9d9 attempt to optimise vectored write 2022-06-26 17:15:31 +01:00
Lukas Wirth
756118e2b9
Update std::alloc::System docs 2022-06-26 16:31:29 +02:00
bors
8aab472d52 Auto merge of #98486 - matthiaskrgr:rollup-u7m508x, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #96412 (Windows: Iterative `remove_dir_all`)
 - #98126 (Mitigate MMIO stale data vulnerability)
 - #98149 (Set relocation_model to Pic on emscripten target)
 - #98194 (Leak pthread_{mutex,rwlock}_t if it's dropped while locked.)
 - #98298 (Point to type parameter definition when not finding variant, method and associated item)
 - #98311 (Reverse folder hierarchy)
 - #98401 (Add tracking issues to `--extern` option docs.)
 - #98429 (Use correct substs in enum discriminant cast)
 - #98431 (Suggest defining variable as mutable on `&mut _` type mismatch in pats)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-06-25 15:19:31 +00:00
Matthias Krüger
ecefccd8d2
Rollup merge of #98194 - m-ou-se:leak-locked-pthread-mutex, r=Amanieu
Leak pthread_{mutex,rwlock}_t if it's dropped while locked.

Fixes https://github.com/rust-lang/rust/issues/85434.
2022-06-25 15:14:09 +02:00
Matthias Krüger
a130521189
Rollup merge of #98126 - fortanix:raoul/mitigate_stale_data_vulnerability, r=cuviper
Mitigate MMIO stale data vulnerability

Intel publicly disclosed the MMIO stale data vulnerability on June 14. To mitigate this vulnerability, compiler changes are required for the `x86_64-fortanix-unknown-sgx` target.
cc: ````@jethrogb````
2022-06-25 15:14:07 +02:00
Matthias Krüger
d7388d1857
Rollup merge of #96412 - ChrisDenton:remove-dir-all, r=thomcc
Windows: Iterative `remove_dir_all`

This will allow better strategies for use of memory and File handles. However, fully taking advantage of that is left to future work.

Note to reviewer: It's probably best to view the `remove_dir_all_recursive` as a new function. The diff is not very helpful (imho).
2022-06-25 15:14:06 +02:00
bors
00ce47209d Auto merge of #96820 - r-raymond:master, r=cuviper
Make RwLockReadGuard covariant

Hi, first time contributor here, if anything is not as expected, please let me know.

`RwLockReadGoard`'s type constructor is invariant. Since it behaves like a smart pointer to an immutable reference, there is no reason that it should not be covariant. Take e.g.

```
fn test_read_guard_covariance() {
    fn do_stuff<'a>(_: RwLockReadGuard<'_, &'a i32>, _: &'a i32) {}
    let j: i32 = 5;
    let lock = RwLock::new(&j);
    {
        let i = 6;
        do_stuff(lock.read().unwrap(), &i);
    }
    drop(lock);
}
```
where the compiler complains that &i doesn't live long enough. If `RwLockReadGuard` is covariant, then the above code is accepted because the lifetime can be shorter than `'a`.

In order for `RwLockReadGuard` to be covariant, it can't contain a full reference to the `RwLock`, which can never be covariant (because it exposes a mutable reference to the underlying data structure). By reducing the data structure to the required pieces of `RwLock`, the rest falls in place.

If there is a better way to do a test that tests successful compilation, please let me know.

Fixes #80392
2022-06-25 13:03:53 +00:00
The 8472
b2c410ec57 scan mountinfo when hardcoded cgroupv1 mountpoints don't work 2022-06-24 20:29:36 +02:00
Michael Goulet
262382ff37
Rollup merge of #96173 - jmaargh:jmaargh/with-capacity-doc-fix, r=Dylan-DPC
Fix documentation for  `with_capacity` and `reserve` families of methods

Fixes #95614

Documentation for the following methods
 - `with_capacity`
 - `with_capacity_in`
 - `with_capacity_and_hasher`
 - `reserve`
 - `reserve_exact`
 - `try_reserve`
 - `try_reserve_exact`

was inconsistent and often not entirely correct where they existed on the following types
- `Vec`
- `VecDeque`
- `String`
- `OsString`
- `PathBuf`
- `BinaryHeap`
- `HashSet`
- `HashMap`
- `BufWriter`
- `LineWriter`

since the allocator is allowed to allocate more than the requested capacity in all such cases, and will frequently "allocate" much more in the case of zero-sized types (I also checked `BufReader`, but there the docs appear to be accurate as it appears to actually allocate the exact capacity).

Some effort was made to make the documentation more consistent between types as well.
2022-06-23 14:39:05 -07:00
Gus Wynn
029f9aa3bf add tracking issue for exclusive 2022-06-23 08:52:13 -07:00
Jiahao XU
516da4c93f
Use unwrap instead of unwrap_unchecked
Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-23 12:58:33 +10:00
Jiahao XU
d2211c9fdc
Add new unit test test_try_downcast_inner
Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-22 23:09:30 +10:00
Jiahao XU
e0ea0c2534
Add new unstable API Error::try_downgrade_inner
Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-22 22:44:30 +10:00
Jiahao XU
1713e25a41
Impl io::error::repr_bitpacked::Repr::new
that accepts `ErrorData<Box<Custom>>`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-22 22:01:51 +10:00
Jiahao XU
d11ff2a06e
Impl io::error::repr_unpacked::Repr::new
that accepts `ErrorData<Box<Custom>>`

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-22 22:01:21 +10:00
Raoul Strackx
6a6910e5a9 Address reviewer comments 2022-06-22 13:49:12 +02:00
Yuki Okushi
897745bf67
Rollup merge of #96768 - m-ou-se:futex-fuchsia, r=tmandry
Use futex based thread parker on Fuchsia.
2022-06-22 15:16:09 +09:00
Joshua Nelson
cf483a130c impl<T: AsFd> AsFd for {Arc,Box}<T> 2022-06-21 23:03:58 -05:00
Joshua Nelson
ed1e3512dc impl<T: AsRawFd> for {Arc,Box}<T>
This allows implementing traits that require a raw FD on Arc and Box.

Previously, you'd have to add the function to the trait itself:

```rust
trait MyTrait {
    fn as_raw_fd(&self) -> RawFd;
}

impl<T: MyTrait> MyTrait for Arc<T> {
    fn as_raw_fd(&self) -> RawFd {
        (**self).as_raw_fd()
    }
}
```
2022-06-21 23:03:55 -05:00
Yuki Okushi
e5092425eb
Rollup merge of #98330 - conradludgate:io-slice-mut-docs, r=Dylan-DPC
update ioslice docs to use shared slices

I noticed that IoSlice docs were taking unnecessary mut slices, when they only accept shared slices
2022-06-21 20:08:17 +09:00
Yuki Okushi
18b01d5ea0
Rollup merge of #98313 - m-ou-se:fix-comments, r=joshtriplett
Remove lies in comments.

> does not have a const constructor

> pub const fn new() -> Self

🤔
2022-06-21 20:08:14 +09:00
Yuki Okushi
84c17c200a
Rollup merge of #94033 - joshtriplett:documentation-is-running-better-go-catch-it, r=m-ou-se
Improve docs for `is_running` to explain use case
2022-06-21 20:08:07 +09:00
Mara Bos
ac38258dcc Use futex based thread parker on Fuchsia. 2022-06-21 11:49:59 +02:00
Conrad Ludgate
44dbd9808e update ioslice docs to use shared slices 2022-06-21 11:45:17 +02:00
Mara Bos
a171a6b7ec Remove lies in comments. 2022-06-20 23:02:21 +02:00
Josh Triplett
7098a714e8 Improve docs for is_running to explain use case 2022-06-20 13:42:49 -07:00
Dylan DPC
ce1151c04c
Rollup merge of #97837 - sunfishcode:sunfishcode/proc-self-mem, r=m-ou-se
Document Rust's stance on `/proc/self/mem`

Add documentation to `std::os::unix::io` describing Rust's stance on
`/proc/self/mem`, treating it as an external entity which is outside
the scope of Rust's safety guarantees.
2022-06-20 14:56:40 +02:00
Dylan DPC
2807f28de5
Rollup merge of #97150 - ChrisDenton:stdio-create_pipe, r=m-ou-se
`Stdio::makes_pipe`

Wrappers around `std::process::Command` may want to be able to override pipe creation. However, [`std::process::Stdio`](https://doc.rust-lang.org/std/process/struct.Stdio.html) is opaque so there's no way to tell if `Command` was told to create new pipes or not.

This is in some ways a more generic (and cross-platform) alternative to #97149. However, unlike that feature, this comes with the price of the user needing to actually create their own pipes rather than reusing the std one. So I think it stands (or not) on its own.

# Example

```rust
#![feature(stdio_makes_pipe)]
use std::process::Stdio;

let io = Stdio::piped();
assert_eq!(io.makes_pipe(), true);
```
2022-06-20 14:56:39 +02:00
Dylan DPC
85f1de20e7
Rollup merge of #97149 - ChrisDenton:win_async_pipes, r=m-ou-se
Windows: `CommandExt::async_pipes`

Discussed in https://github.com/tokio-rs/tokio/issues/4670 was the need for third party crates to be able to force `process::Command::spawn` to create pipes as async.

This implements the suggestion for a `async_pipes` method that gives third party crates that option.

# Example:

```rust
use std::process::{Command, Stdio};

Command::new("cmd")
    .async_pipes(true)
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .stderr(Stdio::piped())
    .spawn()
    .unwrap();
```
2022-06-20 14:56:38 +02:00
Dylan DPC
99620ad721
Rollup merge of #94855 - m-ou-se:advance-slice-panic-docs, r=kennytm
Panic when advance_slices()'ing too far and update docs.

This updates advance_slices() to panic when advancing too far, like advance() already does. And updates the docs to say so.

See https://github.com/rust-lang/rust/issues/62726#issuecomment-1065253213
2022-06-20 14:56:34 +02:00
Chris Denton
740a54c69b
Windows: CommandExt::async_pipes 2022-06-20 12:21:39 +01:00
Chris Denton
8b93147f7e
Stdio::make_pipe 2022-06-20 11:58:38 +01:00
Mara Bos
e642c5987e Leak pthreax_rwlock_t when it's dropped while locked. 2022-06-20 09:33:59 +02:00
nils
2ead0d7457 Fix typo in HashMap::drain docs
It's a map, not a vector.
2022-06-20 09:17:08 +02:00
Yuki Okushi
77316a4aaa
Rollup merge of #97912 - Kixunil:stabilize_path_try_exists, r=dtolnay
Stabilize `Path::try_exists()` and improve doc

This stabilizes the `Path::try_exists()` method which returns
`Result<bool, io::Error>` instead of `bool` allowing handling of errors
unrelated to the file not existing. (e.g permission errors)

Along with the stabilization it also:

* Warns that the `exists()` method is error-prone and suggests to use
  the newly stabilized one.
* Suggests it instead of `metadata()` to handle errors.
* Mentions TOCTOU bugs to avoid false assumption that `try_exists()` is
  completely safe fixed version of `exists()`.
* Renames the feature of still-unstable `std::fs::try_exists()` to
  `fs_try_exists` to avoid name conflict.

The tracking issue #83186 remains open to track `fs_try_exists`.
2022-06-20 07:37:41 +09:00
jmaargh
95dc353006 Fix documentation for with_capacity and reserve families of methods
Documentation for the following methods

    with_capacity
    with_capacity_in
    with_capacity_and_hasher
    reserve
    reserve_exact
    try_reserve
    try_reserve_exact

was inconsistent and often not entirely correct where they existed on the following types

    Vec
    VecDeque
    String
    OsString
    PathBuf
    BinaryHeap
    HashSet
    HashMap
    BufWriter
    LineWriter

since the allocator is allowed to allocate more than the requested capacity in all such cases, and will frequently "allocate" much more in the case of zero-sized types (I also checked BufReader, but there the docs appear to be accurate as it appears to actually allocate the exact capacity).

Some effort was made to make the documentation more consistent between types as well.

Fix with_capacity* methods for Vec

Fix *reserve*  methods for Vec

Fix docs for *reserve* methods of VecDeque

Fix docs for String::with_capacity

Fix docs for *reserve* methods of String

Fix docs for OsString::with_capacity

Fix docs for *reserve* methods on OsString

Fix docs for with_capacity* methods on HashSet

Fix docs for *reserve methods of HashSet

Fix docs for with_capacity* methods of HashMap

Fix docs for *reserve methods on HashMap

Fix expect messages about OOM in doctests

Fix docs for BinaryHeap::with_capacity

Fix docs for *reserve* methods of BinaryHeap

Fix typos

Fix docs for with_capacity on BufWriter and LineWriter

Fix consistent use of `hasher` between `HashMap` and `HashSet`

Fix warning in doc test

Add test for capacity of vec with ZST

Fix doc test error
2022-06-19 20:46:49 +01:00
Dylan DPC
6a2a56da45
Rollup merge of #98233 - RalfJung:ref-alloc, r=thomcc
Remove accidental uses of `&A: Allocator`

Cc https://github.com/rust-lang/rust/issues/98232

Fixes https://github.com/rust-lang/rust/issues/98176 (for real this time)
2022-06-19 15:26:31 +02:00
bors
15fc228d0d Auto merge of #97791 - m-ou-se:const-locks, r=m-ou-se
Make {Mutex, Condvar, RwLock}::new() const.

This makes it possible to have `static M: Mutex<_> = Mutex::new(..);` 🎉

Our implementations [on Linux](https://github.com/rust-lang/rust/pull/95035), [on Windows](https://github.com/rust-lang/rust/pull/77380), and various BSDs and some tier 3 platforms have already been using a non-allocating const-constructible implementation. As of https://github.com/rust-lang/rust/pull/97647, the remaining platforms (most notably macOS) now have a const-constructible implementation as well. This means we can finally make these functions publicly const.

Tracking issue: https://github.com/rust-lang/rust/issues/93740
2022-06-19 08:20:36 +00:00
Robin Raymond
09d937ed5f Add comment explaining why we use NonNull 2022-06-19 09:23:35 +02:00
Robin Raymond
fa1656e8ae Add safety comments 2022-06-19 09:23:35 +02:00
Robin Raymond
0157593c74 Documentation typo 2022-06-19 09:23:35 +02:00
Robin Raymond
08650fbb50 *const to NonNull plus documentation 2022-06-19 09:23:32 +02:00
Robin Raymond
cf1238e799 Address comments 2022-06-19 09:22:40 +02:00
Robin Raymond
391f800705 More formatting 2022-06-19 09:22:40 +02:00
Robin Raymond
0b6e6e3d63 Formatting 2022-06-19 09:22:32 +02:00
Robin Raymond
7cefa8f995 Make RwLockReadGuard covariant 2022-06-19 09:21:28 +02:00
Matthias Krüger
f351f347b8
Rollup merge of #98165 - WaffleLapkin:once_things_renamings, r=m-ou-se
once cell renamings

This PR does the renamings proposed in https://github.com/rust-lang/rust/issues/74465#issuecomment-1153703128

- Move/rename `lazy::{OnceCell, Lazy}` to `cell::{OnceCell, LazyCell}`
- Move/rename `lazy::{SyncOnceCell, SyncLazy}` to `sync::{OnceLock, LazyLock}`

(I used `Lazy...` instead of `...Lazy` as it seems to be more consistent, easier to pronounce, etc)

```@rustbot``` label +T-libs-api -T-libs
2022-06-19 00:17:13 +02:00
bors
ec21d7ea3c Auto merge of #97924 - cuviper:unguarded-poison, r=Mark-Simulacrum
Avoid `thread::panicking()` in non-poisoning methods of `Mutex` and `RwLock`

`Mutex::lock()` and `RwLock::write()` are poison-guarded against panics,
in that they set the poison flag if a panic occurs while they're locked.
But if we're already in a panic (`thread::panicking()`), they leave the
poison flag alone.

That check is a bit of a waste for methods that never set the poison
flag though, namely `get_mut()`, `into_inner()`, and `RwLock::read()`.
These use-cases are now split to avoid that unnecessary call.
2022-06-18 15:18:50 +00:00
Ralf Jung
b05d71f880 make std not use &A: Allocator instance 2022-06-18 07:38:28 -07:00
Aria Beingessner
1502713f99 Impl Termination for Infallible and then make the Result impls of Termination into a blanket
This allows things like `Result<ExitCode, E>` to 'just work'
2022-06-17 13:54:17 -04:00
Dylan DPC
7eabfb5fa7
Rollup merge of #97844 - ChrisDenton:dont-panic, r=JohnTitor
Windows: No panic if function not (yet) available

In some situations (e.g. #97814) it is possible for required functions to be called before they've had a chance to be loaded. Therefore, we make it possible to recover from this situation simply by looking at error codes.

`@rustbot` label +O-windows
2022-06-17 12:21:48 +02:00
Dylan DPC
b516806774
Rollup merge of #95392 - Xuanwo:stablize_try_reserve_2, r=dtolnay
std: Stabilize feature try_reserve_2

This PR intends to stabilize feature `try_reserve_2`, closes https://github.com/rust-lang/rust/issues/91789

This PR will also replace the previous PR: https://github.com/rust-lang/rust/pull/95139
2022-06-17 12:21:46 +02:00
bors
3cf1275ecc Auto merge of #98143 - cuviper:futex-rwlock-inline, r=thomcc
Add `#[inline]` to small fns of futex `RwLock`

The important methods like `read` and `write` were already inlined,
which can propagate all the way to inlining in user code, but these
small state functions were left behind as normal calls. They should
almost always be inlined as well, as they're just a few instructions.
2022-06-17 02:32:14 +00:00
Yuki Okushi
6ac93185f4
Rollup merge of #98169 - pierwill:dyn-disp, r=JohnTitor
Keyword docs: Link to wikipedia article for dynamic dispatch
2022-06-17 07:16:58 +09:00
Yuki Okushi
1f3023ca8a
Rollup merge of #98118 - steffahn:scoped-threads-nll-test, r=m-ou-se
Test NLL fix of bad lifetime inference for reference captured in closure.

This came up as a use-case for `thread::scope` API that only compiles successfully since `feature(nll)` got stabilized recently.

Closes #93203 which had been re-opened for tracking this very test case to be added.
2022-06-17 07:16:56 +09:00
Maybe Waffle
c1a2db3372 Move/rename lazy::Sync{OnceCell,Lazy} to sync::{Once,Lazy}Lock 2022-06-16 19:54:42 +04:00
Maybe Waffle
7c360dc117 Move/rename lazy::{OnceCell, Lazy} to cell::{OnceCell, LazyCell} 2022-06-16 19:53:59 +04:00
pierwill
dd0f5d8be0 Keyword docs: Link to wikipedia article for dynamic dispatch 2022-06-16 09:58:57 -05:00
bors
6ec3993ef4 Auto merge of #97842 - notriddle:notriddle/tuple-docs, r=jsha,GuillaumeGomez
Improve the tuple and unit trait docs

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

Here's the new version:

* <https://notriddle.com/notriddle-rustdoc-test/std/primitive.tuple.html>
* <https://notriddle.com/notriddle-rustdoc-test/std/primitive.unit.html>
2022-06-16 11:13:30 +00:00
Mara Bos
d72294491c Leak pthreax_mutex_t when it's dropped while locked. 2022-06-16 12:09:12 +02:00
Matthias Krüger
f4297b06e8
Rollup merge of #98125 - KarlWithK:entry_add_modify_doc, r=Dylan-DPC
Entry and_modify doc

This PR modifies the documentation for [HashMap](https://doc.rust-lang.org/std/collections/struct.HashMap.html#) and [BTreeMap](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#) by introducing examples for `and_modify`. `and_modify` is a function that tends to give more idiomatic rust code when dealing with these data structures -- yet it lacked examples and was hidden away. This PR adds that and addresses #98122.

I've made some choices which I tried to explain in my commits. This is my first time contributing to rust, so hopefully, I made the right choices.
2022-06-16 09:10:21 +02:00
Xuanwo
324286f101
std: Stabilize feature try_reserve_2
Signed-off-by: Xuanwo <github@xuanwo.io>
2022-06-16 09:30:34 +08:00
bors
5bc82c0b94 Auto merge of #98152 - JohnTitor:rollup-osr17j6, r=JohnTitor
Rollup of 7 pull requests

Successful merges:

 - #97202 (os str capacity documentation)
 - #97964 (Fix suggestions for `&a: T` parameters)
 - #98053 (Fix generic impl rustdoc json output)
 - #98059 (Inline `const_eval_select`)
 - #98092 (Fix sidebar items expand collapse)
 - #98119 (Refactor path segment parameter error)
 - #98135 (Add regression test for #93775)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-06-15 23:49:06 +00:00
Yuki Okushi
b37e4e043e
Rollup merge of #97202 - joshtriplett:os-str-capacity-documentation, r=dtolnay
os str capacity documentation

This is based on https://github.com/rust-lang/rust/pull/95394 , with expansion and consolidation
to address comments from `@dtolnay` and other `@rust-lang/libs-api` team members.
2022-06-16 07:24:38 +09:00
bors
b31f9cc22b Auto merge of #97178 - sunfishcode:ownedfd-and-dup, r=joshtriplett
Add a `BorrowedFd::try_clone_to_owned` and accompanying documentation

Add a `BorrowedFd::try_clone_to_owned`, which returns a new `OwnedFd` sharing the underlying file description. And similar for `BorrowedHandle` and `BorrowedSocket` on WIndows.

This is similar to the existing `OwnedFd::try_clone`, but it's named differently to reflect that it doesn't return `Result<Self, ...>`. I'm open to suggestions for better names.

Also, extend the `unix::io` documentation to mention that `dup` is permitted on `BorrowedFd`.

This was originally requsted [here](https://github.com/rust-lang/rust/issues/88564#issuecomment-910786081). At the time I wasn't sure whether it was desirable, but it does have uses and it helps clarify the API. The documentation previously didn't rule out using `dup` on a `BorrowedFd`, but the API only offered convenient ways to do it from an `OwnedFd`. With this patch, the API allows one to do `try_clone` on any type where it's permitted.
2022-06-15 21:08:08 +00:00
Josh Stone
78577096f6 Add #[inline] to small fns of futex RwLock
The important methods like `read` and `write` were already inlined,
which can propagate all the way to inlining in user code, but these
small state functions were left behind as normal calls. They should
almost always be inlined as well, as they're just a few instructions.
2022-06-15 10:48:52 -07:00
Dan Gohman
ee49d65fc3 Add the new stability attributes, for Windows. 2022-06-15 09:46:56 -07:00
Dan Gohman
007cbfd1db Revise the documentation for try_clone.
On Unix, describe these in terms of the underlying "file description". On
Windows, describe them in terms of the underlying "object".
2022-06-15 08:55:11 -07:00
Dan Gohman
5d0eae81ae Add BorrowedFd::try_clone_to_owned.
And `BorrowedHandle::try_clone_to_owned` and
`BorrowedSocket::try_clone_to_owned` on Windows.
2022-06-15 08:54:06 -07:00
Dan Gohman
eb37bbcebc Document that BorrowedFd may be used to do a dup. 2022-06-15 08:52:42 -07:00
bors
c3605f8c80 Auto merge of #95897 - AzureMarker:feature/horizon-std, r=nagisa
STD support for the Nintendo 3DS

Rustc already supports compiling for the Nintendo 3DS using the `armv6k-nintendo-3ds` target (Tier 3). Until now though, only `core` and `alloc` were supported. This PR adds standard library support for the Nintendo 3DS. A notable exclusion is `std::thread` support, which will come in a follow-up PR as it requires more complicated changes.

This has been a joint effort by `@Meziu,` `@ian-h-chamberlain,` myself, and prior work by `@rust3ds` members.

### Background

The Nintendo 3DS (Horizon OS) is a mostly-UNIX looking system, with the caveat that it does not come with a full libc implementation out of the box. On the homebrew side (I'm not under NDA), the libc interface is partially implemented by the [devkitPro](https://devkitpro.org/wiki/devkitPro_pacman) toolchain and a user library like [`libctru`](https://github.com/devkitPro/libctru). This is important because there are [some possible legal barriers](https://github.com/rust-lang/rust/pull/88529#issuecomment-919938396) to linking directly to a library that uses the underlying platform APIs, since they might be considered a trade secret or under NDA.

To get around this, the standard library impl for the 3DS does not directly depend on any platform-level APIs. Instead, it expects standard libc functions to be linked in. The implementation of these libc functions is left to the user. Some functions are provided by the devkitPro toolchain, but in our testing, we used the following to fill in the other functions:
- [`libctru`] - provides more basic APIs, such as `nanosleep`. Linked in by way of [`ctru-sys`](https://github.com/Meziu/ctru-rs/tree/master/ctru-sys).
- [`pthread-3ds`](https://github.com/Meziu/pthread-3ds) - provides pthread APIs for `std::thread`. Implemented using [`libctru`].
- [`linker-fix-3ds`](https://github.com/Meziu/rust-linker-fix-3ds) - fulfills some other missing libc APIs. Implemented using [`libctru`].

For more details, see the `src/doc/rustc/src/platform-support/armv6k-nintendo-3ds.md` file added in this PR.

### Notes
We've already upstreamed changes to the [`libc`] crate to support this PR, as well as the upcoming threading PR. These changes have all been released as of 0.2.121, so we bump the crate version in this PR.
Edit: After some rebases, the version bump has already been merged so it doesn't appear in this PR.

A lot of the changes in this PR are straightforward, and follow in the footsteps of the ESP-IDF target: https://github.com/rust-lang/rust/pull/87666.

The 3DS does not support user space process spawning, so these APIs are unimplemented (similar to ESP-IDF).

[`libctru`]: https://github.com/devkitPro/libctru
[`libc`]: https://github.com/rust-lang/libc
2022-06-15 14:21:28 +00:00
Raoul Strackx
a27aaceee9 Test copy_to_userspace function 2022-06-15 15:01:42 +02:00
joboet
caff72361f
std: relax memory orderings in Parker
Co-authored-by: Tomoaki Kawada <kawada@kmckk.co.jp>
2022-06-15 14:01:31 +02:00
Frank Steffahn
eb14dd863a Test NLL fix of bad lifetime inference for reference captured in closure. 2022-06-15 11:54:59 +02:00
Raoul Strackx
6f7d1937e2 Ensure userspace allocation is 8-byte aligned 2022-06-15 11:06:48 +02:00
Raoul Strackx
531752f39a Mitigate MMIO stale data vulnerabilities
Intel Security Advisory: https://www.intel.com/content/www/us/en/security-center/advisory/intel-sa-00615.html
2022-06-15 10:28:57 +02:00
Raoul Strackx
ab3a2a024f Unify copying data from enclave to userspace 2022-06-15 10:16:48 +02:00
KarlWithK
d3d22e1e66
Add examples using add_modify to HashMap
Updated the HashMap's documentation to include two references to
add_modify.

The first is when the `Entry` API is mentioned at the beginning. I was
hesitant to change the "attack" example (although I believe that it is
perfect example of where `add_modify` should be used) because both uses
work equally, but one is more idiomatic (`add_modify`).

The second is with the `entry` function that is used for the `Entry`
API. The code example was a perfect use for `add_modify`, which is why
it was changed to reflect that.
2022-06-15 01:41:56 -05:00