Commit Graph

12837 Commits

Author SHA1 Message Date
bors
f74f700952 Auto merge of #118232 - matthiaskrgr:rollup-x8crvm0, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #116807 (Improve rewind documentation)
 - #117656 (Update windows-bindgen and define `INVALID_HANDLE_VALUE` ourselves)
 - #117940 (chore: remove unnecessary drop)
 - #118028 (Document behavior of `<dyn Any as Any>::type_id()`)
 - #118060 (Use an absolute path to the NUL device)
 - #118224 (Sort unstable items last in rustdoc, instead of first)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-24 09:21:23 +00:00
Kashiwa
e9f628e109 Update comment for consistent context logic. 2023-11-24 17:18:44 +08:00
Ralf Jung
a8162673e3 also add is_empty to const raw slices 2023-11-24 08:25:01 +01:00
Matthias Krüger
b2d6480f53
Rollup merge of #118060 - ChrisDenton:abs-device-path, r=thomcc
Use an absolute path to the NUL device

While a bare "NUL" *should* be redirected to the NUL device, especially in this simple case, let's be explicit that we aren't opening a file called "NUL" and instead open it directly.

This will also set a good example for people copying std code.

r? libs
2023-11-24 08:23:53 +01:00
Matthias Krüger
c3216e2a3a
Rollup merge of #118028 - Jules-Bertholet:dyn-any-doc, r=thomcc
Document behavior of `<dyn Any as Any>::type_id()`

See also #57893

`@rustbot` label A-docs T-libs
2023-11-24 08:23:53 +01:00
Matthias Krüger
f38de06ce6
Rollup merge of #117940 - zhiqiangxu:remove_redundant_drop, r=thomcc
chore: remove unnecessary drop

 No need to manually drop since it's implicit.
2023-11-24 08:23:52 +01:00
Matthias Krüger
7e3ec1b0e2
Rollup merge of #117656 - ChrisDenton:invalid, r=thomcc
Update windows-bindgen and define `INVALID_HANDLE_VALUE` ourselves

We generate bindings to the Windows API via the `windows-bindgen` crate, which is ultimately what's also used to generate the `windows-sys` and `windows` crates. However, there currently is some custom sauce just for std which makes it a bit different from the vanilla bindings. I would love for us to reduce and eventually remove the differences entirely so that std is using the exact same bindings as everyone else. Maybe in the future we can even just have a normal dependency on `windows-sys`.

This PR removes one of those special things. Our definition of `INVALID_HANDLE_VALUE` relies on an experimental nightly feature for strict provenance, so lets bring that back in house. It also excludes it from the codegen step though that isn't strictly necessary as we override it in any case.

This PR also updates windows-bingen to 0.52.0.
2023-11-24 08:23:52 +01:00
Matthias Krüger
b8657093d6
Rollup merge of #116807 - seanlinsley:patch-2, r=thomcc
Improve rewind documentation

The persistent use of an internal cursor for readers is expected for buffer data types that aren't read all at once, but for files it leads to the confusing situation where calling `read_to_end` on the same file handle multiple times only returns the contents of the file for the first call. This PR adds a note to the documentation clarifying that in that case, `rewind()` must first be called.

I'm unsure if this is the right location for the docs update. Maybe it should also be duplicated on `File`?
2023-11-24 08:23:51 +01:00
bors
8abf920985 Auto merge of #117722 - okaneco:binarysearch, r=thomcc
Refactor `binary_search_by` to use conditional moves

Refactor the if/else checking on `cmp::Ordering` variants to a "branchless" reassignment of left and right.

This change results in fewer branches and instructions.
https://rust.godbolt.org/z/698eYffTx

---

I saw consistent benchmark improvements locally. Performance of worst case seems about the same, maybe slightly faster for the L3 test.

Current
```
slice::binary_search_l1             43.00ns/iter +/- 3.00ns
slice::binary_search_l1_with_dups   25.00ns/iter +/- 0.00ns
slice::binary_search_l1_worst_case  10.00ns/iter +/- 0.00ns
slice::binary_search_l2             64.00ns/iter +/- 1.00ns
slice::binary_search_l2_with_dups   42.00ns/iter +/- 0.00ns
slice::binary_search_l2_worst_case  16.00ns/iter +/- 0.00ns
slice::binary_search_l3            132.00ns/iter +/- 2.00ns
slice::binary_search_l3_with_dups  108.00ns/iter +/- 2.00ns
slice::binary_search_l3_worst_case  33.00ns/iter +/- 3.00ns
```
This PR
```
slice::binary_search_l1            21.00ns/iter +/- 0.00ns
slice::binary_search_l1_with_dups  14.00ns/iter +/- 0.00ns
slice::binary_search_l1_worst_case  9.00ns/iter +/- 0.00ns
slice::binary_search_l2            34.00ns/iter +/- 0.00ns
slice::binary_search_l2_with_dups  23.00ns/iter +/- 0.00ns
slice::binary_search_l2_worst_case 16.00ns/iter +/- 0.00ns
slice::binary_search_l3            92.00ns/iter +/- 3.00ns
slice::binary_search_l3_with_dups  63.00ns/iter +/- 1.00ns
slice::binary_search_l3_worst_case 29.00ns/iter +/- 0.00ns
```
2023-11-24 07:23:04 +00:00
Mark Rousskov
b81e788d16 Indicate that multiplication in Layout::array cannot overflow
This allows LLVM to optimize comparisons to zero before & after the
multiplication into one, saving on code size and eliminating an (always
true) branch from most Vec allocations.
2023-11-23 22:05:45 -05:00
bors
e68f935117 Auto merge of #98943 - WilliamVenner:feat/bufread_skip_until, r=dtolnay
Add `BufRead::skip_until`

Alternative version of `BufRead::read_until` that simply discards data, rather than copying it into a buffer.

Useful for situations like skipping irrelevant data in a binary file format that is NUL-terminated.

<details>
<summary>Benchmark</summary>

```
running 2 tests
test bench_read_until ... bench:         123 ns/iter (+/- 6)
test bench_skip_until ... bench:          66 ns/iter (+/- 3)
```

```rs
#![feature(test)]
extern crate test;
use test::Bencher;

use std::io::{ErrorKind, BufRead};

fn skip_until<R: BufRead + ?Sized>(r: &mut R, delim: u8) -> Result<usize, std::io::Error> {
    let mut read = 0;
    loop {
        let (done, used) = {
            let available = match r.fill_buf() {
                Ok(n) => n,
                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            };
            match memchr::memchr(delim, available) {
                Some(i) => (true, i + 1),
                None => (false, available.len()),
            }
        };
        r.consume(used);
        read += used;
        if done || used == 0 {
            return Ok(read);
        }
    }
}

const STR: &[u8] = b"Ferris\0Hello, world!\0";

#[bench]
fn bench_skip_until(b: &mut Bencher) {
    b.iter(|| {
        let mut io = std::io::Cursor::new(test::black_box(STR));
        skip_until(&mut io, b'\0').unwrap();
        let mut hello = Vec::with_capacity(b"Hello, world!\0".len());
        let num_bytes = io.read_until(b'\0', &mut hello).unwrap();
        assert_eq!(num_bytes, b"Hello, world!\0".len());
        assert_eq!(hello, b"Hello, world!\0");
    });
}

#[bench]
fn bench_read_until(b: &mut Bencher) {
    b.iter(|| {
        let mut io = std::io::Cursor::new(test::black_box(STR));
        io.read_until(b'\0', &mut Vec::new()).unwrap();
        let mut hello = Vec::with_capacity(b"Hello, world!\0".len());
        let num_bytes = io.read_until(b'\0', &mut hello).unwrap();
        assert_eq!(num_bytes, b"Hello, world!\0".len());
        assert_eq!(hello, b"Hello, world!\0");
    });
}
```
</details>
2023-11-23 22:28:14 +00:00
David Tolnay
52c07b9564
Fix tracking issue of Windows ExitCodeExt 2023-11-23 11:16:10 -08:00
bohan
fc87d6e23d add track_caller for arith ops 2023-11-24 00:54:06 +08:00
bors
193466525d Auto merge of #115159 - solid-rs:patch/kmc-solid/io-safety, r=workingjubilee
kmc-solid: I/O safety

Adds the I/O safety API (#87329) for socket file descriptors in [`*-kmc-solid_*`](https://doc.rust-lang.org/nightly/rustc/platform-support/kmc-solid.html) Tier 3 targets. All new public items are gated by the `solid_ext` library feature.

This PR adds the following public types and traits:

    std::os::solid::io::AsFd
    std::os::solid::io::BorrowedFd
    std::os::solid::io::OwnedFd

    std::os::solid::prelude::AsFd (re-export)
    std::os::solid::prelude::BorrowedFd (re-export)
    std::os::solid::prelude::OwnedFd (re-export)

And trait implementations:

    From<std::net::TcpListener> for std::os::solid::io::OwnedFd
    From<std::net::TcpStream> for std::os::solid::io::OwnedFd
    From<std::net::UdpSocket> for std::os::solid::io::OwnedFd
    From<std::os::solid::io::OwnedFd> for std::net::TcpListener
    From<std::os::solid::io::OwnedFd> for std::net::TcpStream
    From<std::os::solid::io::OwnedFd> for std::net::UdpSocket
    std::fmt::Debug for std::os::solid::io::BorrowedFd<'_>
    std::fmt::Debug for std::os::solid::io::OwnedFd
    std::io::IsTerminal for std::os::solid::io::BorrowedFd<'_>
    std::io::IsTerminal for std::os::solid::io::OwnedFd
    std::os::fd::AsRawFd for std::os::solid::io::BorrowedFd<'_>
    std::os::fd::AsRawFd for std::os::solid::io::OwnedFd
    std::os::fd::FromRawFd for std::os::solid::io::OwnedFd
    std::os::fd::IntoRawFd for std::os::solid::io::OwnedFd
    std::os::solid::io::AsFd for &impl std::os::solid::io::AsFd
    std::os::solid::io::AsFd for &mut impl std::os::solid::io::AsFd
    std::os::solid::io::AsFd for Arc<impl std::os::solid::io::AsFd>
    std::os::solid::io::AsFd for Box<impl std::os::solid::io::AsFd>
    std::os::solid::io::AsFd for Rc<impl std::os::solid::io::AsFd>
    std::os::solid::io::AsFd for std::net::TcpListener
    std::os::solid::io::AsFd for std::net::TcpStream
    std::os::solid::io::AsFd for std::net::UdpSocket
    std::os::solid::io::AsFd for std::os::solid::io::BorrowedFd<'_>
    std::os::solid::io::AsFd for std::os::solid::io::OwnedFd

Taking advantage of the above change, this PR also refactors the internal details of `std::sys::solid::net` to match the design of other targets, e.g., by redefining `Socket` as a newtype of `OwnedFd`.
2023-11-23 04:24:09 +00:00
Max Heller
84b3c84223
add missing period in std::process::Command docs 2023-11-22 20:04:43 -05:00
bors
c387f012b1 Auto merge of #118154 - ChrisDenton:win-clippy, r=scottmcm
Fix some clippy lints for library/std/src/sys/windows

These issues were shown by running `x clippy` on `library/std` and filtering for `windows/` paths. I think running clippy on the full std would be great but I wanted to start smaller and with something that's hopefully easier to review. It'd be good to eventually run clippy in CI but that's a bigger conversation.

I've created separate commits for each clippy lint fixed (with the commit title set to the lint name) and reviewed the changes myself. Most of the fixes here are trivial.

r? libs
2023-11-23 00:30:15 +00:00
Chris Denton
b9fe367b99
x fmt library/std 2023-11-22 13:17:02 +00:00
Chris Denton
6c8ebf174c
redundant_slicing 2023-11-22 13:17:02 +00:00
Chris Denton
852c038393
cmp_null
comparing with null is better expressed by the `.is_null()` method
2023-11-22 13:17:02 +00:00
Chris Denton
c15adf6557
manual_range_contains 2023-11-22 13:17:01 +00:00
Chris Denton
d7e1f1cc08
op_ref
taken reference of right operand
2023-11-22 13:00:30 +00:00
Chris Denton
4c084c576a
manual_map
manual implementation of `Option::map`
2023-11-22 13:00:30 +00:00
Chris Denton
8c85c5b7f4
unnecessary_lazy_evaluations
unnecessary closure used with `bool::then`
2023-11-22 13:00:29 +00:00
Chris Denton
220217af13
redundant_closure 2023-11-22 13:00:29 +00:00
Chris Denton
b962ae1324
duration_subsec
calling `subsec_micros()` is more concise than this calculation
2023-11-22 13:00:29 +00:00
Chris Denton
9e42456a0d
unnecessary_cast
casting to the same type is unnecessary
2023-11-22 13:00:29 +00:00
Chris Denton
24542639aa
needless_borrow
this expression creates a reference which is immediately dereferenced by the compiler
2023-11-22 13:00:29 +00:00
Chris Denton
42734599bd
needless_borrows_for_generic_args
the borrowed expression implements the required traits
2023-11-22 13:00:28 +00:00
Chris Denton
fe255695f9
manual_slice_size_calculation 2023-11-22 13:00:28 +00:00
Chris Denton
bfbeb3ebd9
unnecessary_mut_passed
This is where our Windows API bindings previously (and incorrectly) used `*mut` instead of `*const` pointers. Now that the bindings have been corrected, the mutable references (which auto-convert to `*mut`) are unnecessary and we can use shared references.
2023-11-22 13:00:28 +00:00
Chris Denton
6c22e57c39
useless_conversion 2023-11-22 13:00:28 +00:00
Chris Denton
533de2bc41
needless_return
unneeded `return` statement
2023-11-22 13:00:28 +00:00
Urgau
4c2d6de70e Stabilize RFC3324 dyn upcasting coercion
Aka trait_upcasting feature.

And also adjust the `deref_into_dyn_supertrait` lint.
2023-11-22 13:56:36 +01:00
Chris Denton
ad12be3668
allow clippy style in windows/c.rs
We intentional use the Windows API style here.
2023-11-22 00:14:46 +00:00
roblabla
08803eb4c8 Update backtrace submodule 2023-11-21 16:33:42 +01:00
bors
e24e5af787 Auto merge of #117619 - elomatreb:add-duration-abs-diff, r=thomcc
Add `Duration::abs_diff`

This adds a `Duration::abs_diff` method analogous to the existing one on the primitive integers.

ACP: https://github.com/rust-lang/libs-team/issues/291
Tracking Issue: https://github.com/rust-lang/rust/issues/117618
2023-11-21 13:09:49 +00:00
Nilstrieb
bfc2675362
Rollup merge of #118094 - JarvisCraft:SpecFromElem-for-empty-tuple, r=thomcc
feat: specialize `SpecFromElem` for `()`

# Description

This PR adds a specialization `SpecFromElem for ()` which allows to significantly reduce `vec![(), N]` time in debug builds (specifically, tests) turning it from observable $O(n)$ to $O(1)$.

# Observing the change

The problem this PR aims to fix explicitly is slow `vec![(), N]` on big `N`s which may appear in tests (see [Background section](#Background) for more details).

The minimal example to see the problem:

```rust
#![feature(test)]

extern crate test;

#[cfg(test)]
mod tests {
    const HUGE_SIZE: usize = i32::MAX as usize + 1;

    #[bench]
    fn bench_vec_literal(b: &mut test::Bencher) {
        b.iter(|| vec![(); HUGE_SIZE]);
    }

    #[bench]
    fn bench_vec_repeat(b: &mut test::Bencher) {
        b.iter(|| [(); 1].repeat(HUGE_SIZE));
    }
}
```
<details><summary>Output</summary>
<p>

```bash
cargo +nightly test -- --report-time -Zunstable-options
   Compiling huge-zst-vec-literal-bench v0.1.0 (/home/progrm_jarvis/RustroverProjects/huge-zst-vec-literal-bench)
    Finished test [unoptimized + debuginfo] target(s) in 0.31s
     Running unittests src/lib.rs (target/debug/deps/huge_zst_vec_literal_bench-e43b1ef287ba8b36)

running 2 tests
test tests::bench_vec_repeat  ... ok <0.000s>
test tests::bench_vec_literal ... ok <14.382s>

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 14.38s

   Doc-tests huge-zst-vec-literal-bench

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```
</p>
</details>

> [!IMPORTANT]
> This problem is only observable in Debug (unoptimized) builds, while Release (optimized) ones do not observe this problem. It still is worth fixing it, IMO, since the original scenario observes the problem in tests for which optimizations are disabled by default and it seems unreasonable to override this for the whole project while the problem is very local.

# Background

While working on a crate for a custom data format which has an `i32::MAX` limit on its list's sizes, I wrote the following test to ensure that this invariant is upheld:

```rust
#[test]
fn lists_should_have_i32_size() {
    assert!(
        RawNbtList::try_from(vec![(); i32::MAX as usize]).is_ok(),
        "lists should permit the size up to {}",
        i32::MAX
    );
    assert!(
        RawNbtList::try_from(vec![(); i32::MAX as usize + 1]).is_err(),
        "lists should have the size of at most {}",
        i32::MAX
    );
}
```

Soon I discovered that this takes $\approx 3--4s$ per assertion on my machine, almost all of which is spent on `vec![..]`.
While this would be logical for a non-ZST vector (which would require actual $O(n)$ allocation), here `()` was used intentionally considering that for ZSTs size-changing operations should anyway be $O(1)$ (at least from allocator perspective). Yet, this "overhead" is logical if we consider that in general case `clone()` (which is used by `Vec` literal) may have a non-trivial implementation and thus each element has to actually be visited (even if they occupy no space).

In my specific case, the following (contextual) equivalent solved the issue:

```rust
#[test]
fn lists_should_have_i32_size() {
    assert!(
        RawNbtList::try_from([(); 1].repeat(i32::MAX as usize)).is_ok(),
        "lists should permit the size up to {}",
        i32::MAX
    );
    assert!(
        RawNbtList::try_from([(); 1].repeat(i32::MAX as usize + 1)).is_err(),
        "lists should have the size of at most {}",
        i32::MAX
    );
}
```

which works since `repeat` explicitly uses `T: Copy` and so does not have to think about non-trivial `Clone`.

But it still may be counter-intuitive for users to observe such long time on the "canonical" vec literal thus the PR.

# Generic solution

This change is explicitly non-generic. Initially I considered it possible to implement in generically, but this would require the specialization to have the following type requirements:
-  the type must be a ZST: easily done via
  ```rust
  if core::mem::size_of::<T>() == 0 {
    todo!("specialization")
  }
  ```
  or
  ```rust
  use core::mem::SizedTypeProperties;
  if T::IS_ZST {
    todo!("specialization")
  }
  ```
- :white_check_mark`: the type must implement `Copy`: implementable non-conflictable via a separate specialization:
  ```rust
  trait IsCopyZst: Sized {
    fn is_copy_zst() -> bool;
  }
  impl<T> IsCopyZst for T {
    fn is_copy_zst() -> bool {
        false
    }
  }
  impl<T: Copy> IsCopyZst for T {
    fn is_copy_zst() -> bool {
        Self::IS_ZST
    }
  }
  ```
-  the type should have a trivial `Clone` implementation: since `vec![t; n]` is specified to use `clone()`, we can only use this "performance optimization" when we are guaranteed that `clone()` does nothing except for copying.

The latter is the real blocker for a generic fix since I am unaware of any way to get this information in a compiler-guaranteed way.

While there may be a fix for this (my friend `@CertainLach` has suggested a potential solution by an perma-unstable fn in `Clone` like `is_trivially_cloneable()` defaulting to `false` and only overridable by `rustc` on derive), this is surely out of this PRs scope.
2023-11-21 09:06:29 +01:00
Nilstrieb
6bb671e7e8
Rollup merge of #117790 - rcvalle:rust-cfi-fix-000000, r=workingjubilee
CFI: Add missing use core::ffi::c_int

Adds missing use core::ffi::c_int for when sanitizer_cfi_normalize_integers is defined.
2023-11-21 09:06:27 +01:00
Petr Portnov
72a8633ee8
docs(GH-118094): make docs a bit more explicit
Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2023-11-20 18:35:04 +03:00
Petr Portnov
91fcdde51b
chore(GH-118094): explicitly mark _elem as unused
Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2023-11-20 18:33:55 +03:00
Petr Portnov
2fd9442afc
feat: specialize SpecFromElem for ()
While a better approach would be to implement it for all ZSTs
which are `Copy` and have trivial `Clone`,
the last property cannot be detected for now.

Signed-off-by: Petr Portnov <me@progrm-jarvis.ru>
2023-11-20 18:29:09 +03:00
Michael Goulet
6d33e900d8
Rollup merge of #117957 - the8472:pidfd-wait, r=Mark-Simulacrum
if available use a Child's pidfd for kill/wait

This should get us closer to stabilization of pidfds since they now do something useful. And they're `CLOEXEC` now.

```
$ strace -ffe clone,sendmsg,recvmsg,execve,kill,pidfd_open,pidfd_send_signal,waitpid,waitid ./x test std --no-doc -- pidfd

[...]
running 1 tests
strace: Process 816007 attached
[pid 816007] pidfd_open(816006, 0)      = 3
[pid 816007] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f0c6b787990) = 816008
strace: Process 816008 attached
[pid 816007] recvmsg(3,  <unfinished ...>
[pid 816008] pidfd_open(816008, 0)      = 3
[pid 816008] sendmsg(4, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[3]}], msg_controllen=24, msg_flags=0}, 0) = 0
[pid 816007] <... recvmsg resumed>{msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[4]}], msg_controllen=24, msg_flags=MSG_CMSG_CLOEXEC}, MSG_CMSG_CLOEXEC) = 0
[pid 816008] execve("/usr/bin/false", ["false"], 0x7ffcf2100048 /* 105 vars */) = 0
[pid 816007] waitid(P_PIDFD, 4,  <unfinished ...>
[pid 816008] +++ exited with 1 +++
[pid 816007] <... waitid resumed>{si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=816008, si_uid=1001, si_status=1, si_utime=0, si_stime=0}, WEXITED, NULL) = 0
[pid 816007] --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=816008, si_uid=1001, si_status=1, si_utime=0, si_stime=0} ---
[pid 816007] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLDstrace: Process 816009 attached
, child_tidptr=0x7f0c6b787990) = 816009
[pid 816007] recvmsg(3,  <unfinished ...>
[pid 816009] pidfd_open(816009, 0)      = 3
[pid 816009] sendmsg(5, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[3]}], msg_controllen=24, msg_flags=0}, 0) = 0
[pid 816007] <... recvmsg resumed>{msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base="", iov_len=0}], msg_iovlen=1, msg_control=[{cmsg_len=20, cmsg_level=SOL_SOCKET, cmsg_type=SCM_RIGHTS, cmsg_data=[5]}], msg_controllen=24, msg_flags=MSG_CMSG_CLOEXEC}, MSG_CMSG_CLOEXEC) = 0
[pid 816009] execve("/usr/bin/sleep", ["sleep", "1000"], 0x7ffcf2100048 /* 105 vars */) = 0
[pid 816007] waitid(P_PIDFD, 5, {}, WNOHANG|WEXITED, NULL) = 0
[pid 816007] pidfd_send_signal(5, SIGKILL, NULL, 0) = 0
[pid 816007] waitid(P_PIDFD, 5,  <unfinished ...>
[pid 816009] +++ killed by SIGKILL +++
[pid 816007] <... waitid resumed>{si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=816009, si_uid=1001, si_status=SIGKILL, si_utime=0, si_stime=0}, WEXITED, NULL) = 0
[pid 816007] --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_KILLED, si_pid=816009, si_uid=1001, si_status=SIGKILL, si_utime=0, si_stime=0} ---
[pid 816007] +++ exited with 0 +++
```
2023-11-19 19:14:34 -08:00
Chris Denton
3a486c1feb
Use an absolute path to the NUL device
While a bare "NUL" *should* be redirected to the NUL device, especially in this simple case, let's be explicit that we aren't opening a file called "NUL" and instead open it directly.

This will also set a good example for people copying std code.
2023-11-19 16:24:39 +00:00
The 8472
f34e7f4768 Don't set cmsg fields in msghdr if we have no cmsg to send 2023-11-19 15:19:47 +01:00
bors
d052f6fde6 Auto merge of #117895 - mzohreva:mz/fix-sgx-backtrace, r=Mark-Simulacrum
Adjust frame IP in backtraces relative to image base for SGX target

This is followup to https://github.com/rust-lang/backtrace-rs/pull/566.

The backtraces printed by `panic!` or generated by `std::backtrace::Backtrace` in SGX target are not usable. The frame addresses need to be relative to image base address so they can be used for symbol resolution. Here's an example panic backtrace generated before this change:

```
$ cargo r --target x86_64-fortanix-unknown-sgx
...
stack backtrace:
   0:     0x7f8fe401d3a5 - <unknown>
   1:     0x7f8fe4034780 - <unknown>
   2:     0x7f8fe401c5a3 - <unknown>
   3:     0x7f8fe401d1f5 - <unknown>
   4:     0x7f8fe401e6f6 - <unknown>
```
Here's the same panic after this change:
```
$ cargo +stage1 r --target x86_64-fortanix-unknown-sgx
stack backtrace:
   0:            0x198bf - <unknown>
   1:            0x3d181 - <unknown>
   2:            0x26164 - <unknown>
   3:            0x19705 - <unknown>
   4:            0x1ef36 - <unknown>
```
cc `@jethrogb` and `@workingjubilee`
2023-11-19 03:00:18 +00:00
Takayuki Maeda
baf3059f4e
Rollup merge of #116750 - fintelia:seek_seek_relative, r=Mark-Simulacrum
Add Seek::seek_relative

The `BufReader` struct has a `seek_relative` method because its `Seek::seek` implementation involved dumping the internal buffer (https://github.com/rust-lang/rust/issues/31100).

Unfortunately, there isn't really a good way to take advantage of that method in generic code. This PR adds the same method to the main `Seek` trait with the straightforward default method, and an override for `BufReader` that calls its implementation.

_Also discussed in [this](https://internals.rust-lang.org/t/add-seek-seek-relative/19546) internals.rust-lang.org thread._
2023-11-19 04:14:40 +09:00
bors
33688d2467 Auto merge of #117525 - GKFX:remove_option_payload_ptr, r=petrochenkov
Remove option_payload_ptr; redundant to offset_of

The `option_payload_ptr` intrinsic is no longer required as `offset_of` supports traversing enums (#114208). This PR removes it in order to dogfood offset_of (as suggested at https://github.com/rust-lang/rust/issues/106655#issuecomment-1790907626). However, it will not build until those changes reach beta (which I think is within the next 8 days?) so I've opened it as a draft.
2023-11-18 12:45:42 +00:00
George Bateman
58ea02e872
Update based on petrochenkov's review 2023-11-18 10:50:47 +00:00
bors
6416e2e675 Auto merge of #115412 - eswartz:docs/total_cmp-test-result-in-docs, r=scottmcm
Expose tests for {f32,f64}.total_cmp in docs

Expose tests for {f32,f64}.total_cmp in docs

Uncomment the helpful `assert_eq!` line, which is stripped out completely in docs, and leaves the reader to mentally play through the algorithm, or go to the playground and add a println!, to see what the result will be.

(If these tests are known to fail on some platforms, is there some mechanism to conditionalize this or escape the test so the `assert_eq!` source will be visible on the web? I am a newbie, which is why I was reading docs ;)
2023-11-18 08:49:03 +00:00
bors
61d3b263a7 Auto merge of #115249 - clarfonthey:alignment, r=scottmcm
impl more traits for ptr::Alignment, add mask method

Changes:

* Adds `rustc_const_unstable` attributes where missing
* Makes `log2` method const
* Adds `mask` method
* Implements `Default`, which is equivalent to `Alignment::MIN`

No longer included in PR:

* Removes indirection of `AlignmentEnum` type alias (this was intentional)
* Implements `Display`, `Binary`, `Octal`, `LowerHex`, and `UpperHex` (should go through libs-api instead)
* Controversially implements `LowerExp` and `UpperExp` using `p` instead of `e` to indicate a power of 2 (also should go through libs-api)

Tracking issue for `ptr::Alignment`: #102070
2023-11-18 06:51:15 +00:00
ltdk
114873dc19 impl more traits for ptr::Alignment, add mask method 2023-11-18 00:05:28 -05:00
bors
e6dade96f4 Auto merge of #117825 - fee1-dead-contrib:corefx, r=petrochenkov
Reenable effects in libcore

With #116670, #117531, and #117171, I think we would be comfortable with re-enabling the effects feature for more testing in libcore.

r? `@oli-obk`
cc `@fmease`
cc #110395
2023-11-18 04:56:31 +00:00
bors
1a740c3816 Auto merge of #117138 - zachs18:rwlock_guard_debug_unsized, r=dtolnay
Add T: ?Sized to `RwLockReadGuard` and `RwLockWriteGuard`'s Debug impls.

For context, `MutexGuard` has `+ ?Sized` on its `Debug` impl, and all three have `+ ?Sized` on their `Display` impls.

It looks like the `?Sized` was just missed when the impls were added (the impl for `MutexGuard` was added in the same PR (https://github.com/rust-lang/rust/pull/38006) with support for `T: Debug + ?Sized`, and `RwLock*Guard`s did allow `T: ?Sized` types already); the `Display` impls were added later (https://github.com/rust-lang/rust/pull/42822) with support for `T: Debug + ?Sized` types.

I think this needs a T-libs-api FCP? I'm not sure if this also needs an ACP. If so I can make one.

These are changes to (stable) trait impls on stable types so will be insta-stable.

`@rustbot` label +T-libs-api
2023-11-18 00:59:19 +00:00
Jules Bertholet
db62921159
Document behavior of <dyn Any as Any>::type_id()
See also #57893
2023-11-17 19:54:37 -05:00
Matthias Krüger
e06a6d3ebe
Rollup merge of #118006 - lcnr:discriminant-docs, r=compiler-errors
clarify `fn discriminant` guarantees: only free lifetimes may get erased

cc https://github.com/rust-lang/rust/pull/104299/files#r1397082347

don't think this necessitates a backport by itself, but should imo be included if one were to exist.

r? types
2023-11-17 23:04:24 +01:00
Matthias Krüger
aa2289d3bc
Rollup merge of #117549 - DaniPopes:more-copied, r=b-naber
Use `copied` instead of manual `map`
2023-11-17 23:04:22 +01:00
Matthias Krüger
ca3a02836e
Rollup merge of #117338 - workingjubilee:asmjs-meets-thanatos, r=b-naber
Remove asmjs

Fulfills [MCP 668](https://github.com/rust-lang/compiler-team/issues/668).

`asmjs-unknown-emscripten` does not work as-specified, and lacks essential upstream support for generating asm.js, so it should not exist at all.
2023-11-17 23:04:21 +01:00
Mohsen Zohrevandi
b576dd2b3c Use ptr::invalid_mut for SGX image base 2023-11-17 11:49:23 -08:00
bors
f6dcaee23f Auto merge of #111922 - vaporoxx:feat-searcher, r=dtolnay
feat: implement `DoubleEndedSearcher` for `CharArray[Ref]Searcher`

This PR implements `DoubleEndedSearcher` for both `CharArraySearcher` and `CharArrayRefSearcher`. I'm not sure whether this was just overlooked or if there is a reason for it, but since it behaves exactly like `CharSliceSearcher`, I think the implementations should be appropriate.
2023-11-17 18:47:34 +00:00
Chris Denton
00a12af3ca
Update windows-bindgen 2023-11-17 12:18:04 +00:00
Chris Denton
df58704701
Define INVALID_HANDLE_VALUE ourselves 2023-11-17 12:03:41 +00:00
lcnr
3b0e1d23b7 only free lifetimes may get erased 2023-11-17 11:03:52 +00:00
Matthias Krüger
1cabedc256
Rollup merge of #115476 - RalfJung:abi-compat-docs, r=Mark-Simulacrum
document ABI compatibility

I don't think we have any central place where we document our ABI compatibility rules, so let's create one. The `fn()` pointer type seems like a good place since ABI questions can only become relevant when invoking a function through a function pointer.

This will likely need T-lang FCP.
2023-11-17 08:10:26 +01:00
Ralf Jung
8f03a55566 linking in general has more pitfalls than just call ABI 2023-11-17 08:02:28 +01:00
Takayuki Maeda
c77cb7a3f6
Rollup merge of #117946 - RalfJung:miri-libcore-test, r=Mark-Simulacrum
avoid exhaustive i16 test in Miri

https://github.com/rust-lang/rust/pull/116301 added a test that is way too slow to be running in Miri. So let's only test a few hopefully representative cases.
2023-11-17 12:56:31 +09:00
George Bateman
661df4fd55
Remove option_payload_ptr; redundant to offset_of 2023-11-16 22:56:25 +00:00
Urgau
8d91d6662f Stabilize ptr_addr_eq library feature 2023-11-16 11:35:59 +01:00
Mark Rousskov
917f6540ed Re-format code with new rustfmt 2023-11-15 21:45:48 -05:00
The 8472
12efa53b19 if available use a Child's pidfd for kill/wait 2023-11-16 02:05:37 +01:00
Mark Rousskov
db3e2bacb6 Bump cfg(bootstrap)s 2023-11-15 19:41:28 -05:00
Mark Rousskov
efe54e24aa Substitute version placeholders 2023-11-15 19:40:51 -05:00
The 8472
3ffbb4899e update comment, we're currently using a different syscall 2023-11-16 01:38:59 +01:00
The 8472
10127d9eb5 set CLOEXEC on pidfd received from child process 2023-11-16 01:36:54 +01:00
Ralf Jung
1c1b7897d8 avoid exhaustive i16 test in Miri 2023-11-15 19:23:04 +01:00
zhiqiangxu
a355df4432
remove unnecessary drop 2023-11-16 00:01:57 +08:00
Mohsen Zohrevandi
ec8c3d9992 Move SGX-specific image base logic to sys_common 2023-11-14 13:27:57 -08:00
Mohsen Zohrevandi
6e7ea03c26 Adjust frame IP in backtraces relative to image base for SGX target 2023-11-14 10:27:12 -08:00
bors
5526682702 Auto merge of #117330 - tmiasko:custom-mir-cleanup-blocks, r=cjgillot
Custom MIR: Support cleanup blocks

Cleanup blocks are declared with `bb (cleanup) = { ... }`.

`Call` and `Drop` terminators take an additional argument describing the unwind action, which is one of the following:

* `UnwindContinue()`
* `UnwindUnreachable()`
* `UnwindTerminate(reason)`, where reason is `ReasonAbi` or `ReasonInCleanup`
* `UnwindCleanup(block)`

Also support unwind resume and unwind terminate terminators:

* `UnwindResume()`
* `UnwindTerminate(reason)`
2023-11-14 08:53:25 +00:00
Tomasz Miąsko
78da577650 Custom MIR: Support cleanup blocks
Cleanup blocks are declared with `bb (cleanup) = { ... }`.

`Call` and `Drop` terminators take an additional argument describing the
unwind action, which is one of the following:

* `UnwindContinue()`
* `UnwindUnreachable()`
* `UnwindTerminate(reason)`, where reason is `ReasonAbi` or `ReasonInCleanup`
* `UnwindCleanup(block)`

Also support unwind resume and unwind terminate terminators:

* `UnwindResume()`
* `UnwindTerminate(reason)`
2023-11-14 08:23:58 +01:00
bors
b9175240ea Auto merge of #116301 - mj10021:issue-115737-fix, r=cuviper
fix rounding issue with exponents in fmt

fixes issue #115737 , where the decimal places are rounded incorrectly when formatting scientific notation
2023-11-14 00:04:05 +00:00
bors
85b8450466 Auto merge of #116866 - slanterns:inspect-stabilize, r=BurntSushi
Stabilize `result_option_inspect`

This PR stabilizes `result_option_inspect`:

```rust
// core::option

impl Option<T> {
    pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self;
}

// core::result

impl Result<T, E> {
    pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self;
    pub fn inspect_err<F: FnOnce(&E)>(self, f: F) -> Self;
}
```

<br>

Tracking issue: https://github.com/rust-lang/rust/issues/91345.
Implementation PR: https://github.com/rust-lang/rust/pull/91346.

Closes https://github.com/rust-lang/rust/issues/91345.
2023-11-13 19:46:18 +00:00
Deadbeef
da28b30896 Reenable effects in libcore 2023-11-12 04:33:19 +00:00
James Dietz
3f0908f47c round to even 2023-11-11 17:22:07 -05:00
James Dietz
e81964e6f9 fix rounding issue with exponents in fmt 2023-11-11 16:40:22 -05:00
bors
2c1b65ee14 Auto merge of #115694 - clarfonthey:std-hash-private, r=dtolnay
Add `std:#️⃣:{DefaultHasher, RandomState}` exports (needs FCP)

This implements rust-lang/libs-team#267 to move the libstd hasher types to `std::hash` where they belong, instead of `std::collections::hash_map`.

<details><summary>The below no longer applies, but is kept for clarity.</summary>
This is a small refactor for #27242, which moves the definitions of `RandomState` and `DefaultHasher` into `std::hash`, but in a way that won't be noticed in the public API.

I've opened rust-lang/libs-team#267 as a formal ACP to move these directly into the root of `std::hash`, but for now, they're at least separated out from the collections code in a way that will make moving that around easier.

I decided to simply copy the rustdoc for `std::hash` from `core::hash` since I think it would be ideal for the two to diverge longer-term, especially if the ACP is accepted. However, I would be willing to factor them out into a common markdown document if that's preferred.
</details>
2023-11-11 21:12:20 +00:00
Ralf Jung
52d22eaa23 clarify ABI compatibility of fn ptr types and ptr types
and add an and
2023-11-11 13:36:02 +01:00
Ralf Jung
044d05769b add 'import functions' to the list of situations where ABI compatibility comes up 2023-11-10 20:33:19 +01:00
Ramon de C Valle
55e3dc487f CFI: Add missing use core::ffi::c_int
Adds missing use core::ffi::c_int for when
sanitizer_cfi_normalize_integers is defined.
2023-11-10 08:20:04 -08:00
bors
17d0a45f5d Auto merge of #117572 - RalfJung:addr_of, r=cuviper
update and clarify addr_of docs

This updates the docs to match https://github.com/rust-lang/reference/pull/1387. Cc `@rust-lang/opsem`

`@chorman0773` not sure if you had anything else you wanted to say here, I'd be happy to get your feedback. :)

Fixes https://github.com/rust-lang/rust/issues/114902, so Cc `@joshlf`
2023-11-10 08:04:47 +00:00
Ralf Jung
e30f8ae867
mention null explicitly
Co-authored-by: Josh Stone <cuviper@gmail.com>
2023-11-10 07:34:28 +01:00
Matthias Krüger
0f1da7e682
Rollup merge of #117730 - jmillikin:fmt-debug-helper-fns, r=cuviper
Closure-consuming helper functions for `fmt::Debug` helpers

ACP: https://github.com/rust-lang/libs-team/issues/288

Tracking issue: https://github.com/rust-lang/rust/issues/117729
2023-11-10 01:50:24 +01:00
Matthias Krüger
7096ec3e00
Rollup merge of #117039 - scottmcm:clarify-get-unchecked, r=cuviper
Clarify UB in `get_unchecked(_mut)`

Inspired by #116915, it was unclear to me what exactly "out-of-bounds index" means in `get_unchecked`.

One could [potentially](https://rust.godbolt.org/z/hxM764orW) interpret it that `get_unchecked` is just another way to write `offset`, but I think `get_unchecked(len)` is supposed to be UB even though `.offet(len)` is well-defined (as is `.get_unchecked(..len)`), so write that more directly in the docs.

**libs-api folks**: Can you confirm whether this is what you expect this to mean?  And is the situation any different for `<*const [T]>::get_unchecked`?
2023-11-10 01:50:24 +01:00
John Millikin
82a9f94de5 Closure-consuming helper functions for fmt::Debug helpers 2023-11-10 07:50:11 +09:00
Takayuki Maeda
b4fa5b7004
Rollup merge of #117694 - jmillikin:core-io-borrowed-buf, r=m-ou-se
Move `BorrowedBuf` and `BorrowedCursor` from `std:io` to `core::io`

Tracking issue: https://github.com/rust-lang/rust/issues/117693

ACP: https://github.com/rust-lang/libs-team/issues/290
2023-11-09 11:36:52 +09:00
Takayuki Maeda
a1a8d6fe9c
Rollup merge of #116762 - WaffleLapkin:fixup_fromptr_docs, r=RalfJung
Fixup `Atomic*::from_ptr` safety docs

See https://github.com/rust-lang/rust/pull/115719#issuecomment-1762725010
cc ``@RalfJung``
2023-11-09 11:36:51 +09:00
John Millikin
341c85648c Move BorrowedBuf and BorrowedCursor from std:io to core::io
Assigned new feature name `core_io_borrowed_buf` to distinguish from the
`Read::read_buf` functionality in `std::io`.
2023-11-09 07:10:11 +09:00
bors
fdaaaf9f92 Auto merge of #116930 - RalfJung:raw-ptr-match, r=davidtwco
patterns: reject raw pointers that are not just integers

Matching against `0 as *const i32` is fine, matching against `&42 as *const i32` is not.

This extends the existing check against function pointers and wide pointers: we now uniformly reject all these pointer types during valtree construction, and then later lint because of that. See [here](https://github.com/rust-lang/rust/pull/116930#issuecomment-1784654073) for some more explanation and context.

Also fixes https://github.com/rust-lang/rust/issues/116929.

Cc `@oli-obk` `@lcnr`
2023-11-08 20:42:32 +00:00
okaneco
d585eecb05 Refactor binary_search_by to use conditional moves
Refactor the if/else checking on cmp::Ordering variants to a
"branchless" reassignment of left and right. This change results
in fewer branches and instructions.
2023-11-08 14:53:49 -05:00
bors
28acba3c61 Auto merge of #115460 - zachs18:borrowedcursor_write_no_panic, r=dtolnay
Don't panic in `<BorrowedCursor as io::Write>::write`

Instead of panicking if the BorrowedCursor does not have enough capacity for the whole buffer, just return a short write, [like `<&mut [u8] as io::Write>::write` does](https://doc.rust-lang.org/src/std/io/impls.rs.html#349).

(cc `@ChayimFriedman2` https://github.com/rust-lang/rust/issues/78485#issuecomment-1493129588)

(I'm not sure if this needs an ACP? since it's not changing the "API", just what the function does)
2023-11-08 14:08:48 +00:00
scottmcm
545175ce87
Fix addition formatting 2023-11-07 18:39:09 -08:00