Commit Graph

9094 Commits

Author SHA1 Message Date
joboet
774cadfbfa
std: fix cleanup for uninitialized stdout (#101375) 2022-09-05 09:08:07 +02:00
bors
5b4bd154de Auto merge of #101414 - mystor:pm_nested_cross_thread, r=eddyb
proc_macro/bridge: use the cross-thread executor for nested proc-macros

While working on some other changes in the bridge, I noticed that when
running a nested proc-macro (which is currently only possible using
the unstable `TokenStream::expand_expr`), any symbols held by the
proc-macro client would be invalidated, as the same thread would be used
for the nested macro by default, and the interner doesn't handle nested
use.

After discussing with `@eddyb,` we decided the best approach might be to
force the use of the cross-thread executor for nested invocations, as it
will never re-use thread-local storage, avoiding the issue. This
shouldn't impact performance, as expand_expr is still unstable, and
infrequently used.

This was chosen rather than making the client symbol interner handle
nested invocations, as that would require replacing the internal
interner `Vec` with a `BTreeMap` (as valid symbol id ranges could now be
disjoint), and the symbol interner is known to be fairly perf-sensitive.

This patch adds checks to the execution strategy to use the cross-thread
executor when doing nested invocations. An alternative implementation
strategy could be to track this information in the `ExtCtxt`, however a
thread-local in the `proc_macro` crate was chosen to add an assertion so
that `rust-analyzer` is aware of the issue if it implements
`expand_expr` in the future.

r? `@eddyb`
2022-09-05 07:07:38 +00:00
bors
9358d09a55 Auto merge of #100759 - fee1-dead-contrib:const_eval_select_real_intrinsic, r=oli-obk,RalfJung
Make `const_eval_select` a real intrinsic

This fixes issues where `track_caller` functions do not have nice panic
messages anymore when there is a call to the function, and uses the
MIR system to replace the call instead of dispatching via lang items.

Fixes #100696.
2022-09-05 01:35:01 +00:00
bors
e7cdd4c090 Auto merge of #100576 - joboet:movable_const_remutex, r=Mark-Simulacrum
Make `ReentrantMutex` movable and `const`

As `MovableMutex` is now `const`, it can be used to simplify the implementation and interface of the internal reentrant mutex type. Consequently, the standard error stream does not need to be wrapped in `OnceLock` and `OnceLock::get_or_init_pin()` can be removed.
2022-09-04 22:53:58 +00:00
Martin Kröning
ce305f8f8e Hermit: Remove unused socklen_t (dead_code) 2022-09-05 00:23:38 +02:00
Martin Kröning
11af142c93 Hermit: Fix unused_imports 2022-09-05 00:23:38 +02:00
Martin Kröning
3b985b4dd6 Hermit: Add File::set_time stub
This is not supported on hermit yet. This change is required for compiling std.
2022-09-05 00:17:46 +02:00
bors
289279de11 Auto merge of #93455 - asquared31415:vec-zero-opts, r=thomcc
Implement internal `IsZero` for Wrapping and Saturating for `Vec` optimizations

This implements the `IsZero` trait for the `Wrapping` and `Saturating` types so that users of these types can get the improved performance from the specialization of creating a `Vec` from a single element repeated when it has a zero bit pattern (example `vec![0_i32; 500]`, or after this PR `vec![Wrapping(0_i32); 500]`)

CC #60978
2022-09-04 20:33:50 +00:00
Nika Layzell
efda49712b proc_macro/bridge: use the cross-thread executor for nested proc-macros
While working on some other changes in the bridge, I noticed that when
running a nested proc-macro (which is currently only possible using
the unstable `TokenStream::expand_expr`), any symbols held by the
proc-macro client would be invalidated, as the same thread would be used
for the nested macro by default, and the interner doesn't handle nested
use.

After discussing with @eddyb, we decided the best approach might be to
force the use of the cross-thread executor for nested invocations, as it
will never re-use thread-local storage, avoiding the issue. This
shouldn't impact performance, as expand_expr is still unstable, and
infrequently used.

This was chosen rather than making the client symbol interner handle
nested invocations, as that would require replacing the internal
interner `Vec` with a `BTreeMap` (as valid symbol id ranges could now be
disjoint), and the symbol interner is known to be fairly perf-sensitive.

This patch adds checks to the execution strategy to use the cross-thread
executor when doing nested invocations. An alternative implementation
strategy could be to track this information in the `ExtCtxt`, however a
thread-local in the `proc_macro` crate was chosen to add an assertion so
that `rust-analyzer` is aware of the issue if it implements
`expand_expr` in the future.

r? @eddyb
2022-09-04 14:06:26 -04:00
Matthias Krüger
d9bba11344
Rollup merge of #101401 - mx00s:expand-const, r=fee1-dead
Make `char::is_lowercase` and `char::is_uppercase` const

Implements #101400.
2022-09-04 18:55:48 +02:00
Matthias Krüger
723f0c477b
Rollup merge of #101394 - CAD97:patch-3, r=Mark-Simulacrum
Forbid mixing `System` with direct sytem allocator calls

e.g. [on windows](dec689432f/library/std/src/sys/windows/alloc.rs (L129-L178)), trying to mix `System::alloc` and `HeapFree` will not work because of the extra work done to serve higher alignments.
2022-09-04 18:55:46 +02:00
Matthias Krüger
8f8a36d1c2
Rollup merge of #101385 - BartMassey-upstream:file-doc, r=thomcc
updated description of File struct in std::fs

I've seen several folks confused by the description of `std::fs::File` as "A reference to an open file on the filesystem." Apparently the word `reference` is sometimes taken to mean a Rust `&` reference, leading to confusion. Here's a recent representative [Reddit thread](https://www.reddit.com/r/rust/comments/x4k0lv/comment/imxu7v2/?utm_source=share&utm_medium=web2x&context=3), but I've seen this before as well.

This patch changes the description to "An object providing access to an open file on the filesystem." Hopefully this is clearer.
2022-09-04 18:55:43 +02:00
Matthias Krüger
c4ea4fb576
Rollup merge of #101322 - ChrisDenton:internal-doc, r=Mark-Simulacrum
Fix internal doc link

The doc link from `DedupSortedIter` to `BTreeMap::bulk_build_from_sorted_iter` was broken when building internal documentation,

This prevented me from building internal documentation locally:

```
R:\Rust\rust> $env:RUSTDOCFLAGS="--document-private-items"
R:\Rust\rust> x doc library/std --open --stage 0
Building rustbuild
   Compiling bootstrap v0.0.0 (R:\Rust\rust\src\bootstrap)
    Finished dev [unoptimized] target(s) in 3.15s
Documenting stage0 std (x86_64-pc-windows-msvc)
 Documenting core v0.0.0 (R:\Rust\rust\library\core)
    Finished release [optimized] target(s) in 36.42s
    Checking core v0.0.0 (R:\Rust\rust\library\core)
    Checking rustc-std-workspace-core v1.99.0 (R:\Rust\rust\library\rustc-std-workspace-core)
    Checking compiler_builtins v0.1.79
 Documenting alloc v0.0.0 (R:\Rust\rust\library\alloc)
error: unresolved link to `BTreeMap::bulk_build_from_sorted_iter`
 --> library\alloc\src\collections\btree\dedup_sorted_iter.rs:6:15
  |
6 | /// Used by [`BTreeMap::bulk_build_from_sorted_iter`].
  |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no item named `BTreeMap` in scope
  |
  = note: `-D rustdoc::broken-intra-doc-links` implied by `-D warnings`

error: could not document `alloc`
```
2022-09-04 18:55:42 +02:00
Maybe Waffle
5a672921a3 replace as usize casts with usize::from in slice sort 2022-09-04 20:54:51 +04:00
Maybe Waffle
fff92d5238 remove some integer casts from slice iter 2022-09-04 20:45:29 +04:00
Sage Mitchell
2b328ea5ee
Address feedback from PR #101401 2022-09-04 08:07:53 -07:00
Sage Mitchell
4a3e169da7
Make char::is_lowercase and char::is_uppercase const
Implements #101400.
2022-09-04 08:07:53 -07:00
bors
a2cdcb3fea Auto merge of #101296 - compiler-errors:head-span-for-enclosing-scope, r=oli-obk
Use head span for `rustc_on_unimplemented`'s `enclosing_scope` attr

This may make #101281 slightly easier to understand
2022-09-04 13:03:07 +00:00
Deadbeef
65b685e82d Add inline(always) to rt functions 2022-09-04 20:35:23 +08:00
Deadbeef
bd61b8fb3f Add inline(always) to function generated by macro 2022-09-04 20:35:23 +08:00
Deadbeef
075084f772 Make const_eval_select a real intrinsic 2022-09-04 20:35:23 +08:00
beetrees
0e0756cf0d
Don't duplicate file descriptors into stdio fds 2022-09-04 10:22:36 +01:00
bors
8521a8c92d Auto merge of #100726 - jswrenn:transmute, r=oli-obk
safe transmute: use `Assume` struct to provide analysis options

This task was left as a TODO in #92268; resolving it brings [`BikeshedIntrinsicFrom`](https://doc.rust-lang.org/nightly/core/mem/trait.BikeshedIntrinsicFrom.html) more in line with the API defined in [MCP411](https://github.com/rust-lang/compiler-team/issues/411).

**Before:**
```rust
pub unsafe trait BikeshedIntrinsicFrom<
    Src,
    Context,
    const ASSUME_ALIGNMENT: bool,
    const ASSUME_LIFETIMES: bool,
    const ASSUME_VALIDITY: bool,
    const ASSUME_VISIBILITY: bool,
> where
    Src: ?Sized,
{}
```
**After:**
```rust
pub unsafe trait BikeshedIntrinsicFrom<Src, Context, const ASSUME: Assume = { Assume::NOTHING }>
where
    Src: ?Sized,
{}
```

`Assume::visibility` has also been renamed to `Assume::safety`, as library safety invariants are what's actually being assumed; visibility is just the mechanism by which it is currently checked (and that may change).

r? `@oli-obk`

---

Related:
- https://github.com/rust-lang/compiler-team/issues/411
- https://github.com/rust-lang/rust/issues/99571
2022-09-04 07:55:44 +00:00
Michael Goulet
edba0c92de Address nits, rename enclosing_scope => parent_label 2022-09-04 02:10:31 +00:00
Christopher Durham
69721defc2
Forbid mixing System with sytem allocator calls 2022-09-03 16:47:12 -05:00
Matthias Krüger
6f4726541e more clippy::perf fixes 2022-09-03 22:57:22 +02:00
Bart Massey
3afbc115f7 updated description of File struct in std::fs 2022-09-03 11:09:06 -07:00
bors
dec689432f Auto merge of #101342 - saethlin:update-backtrace, r=Mark-Simulacrum
Update backtrace

Most notably, this pulls in ebc9a85466, which is both a bugfix and a significant performance improvement for Miri, since fixing the bug makes `RUST_BACKTRACE=1` backtraces much smaller: https://github.com/rust-lang/miri/issues/2273, https://github.com/rust-lang/miri-test-libstd/issues/8

This also pulls in other commits which turn the backtrace-rs CI green. That's nice.
2022-09-03 17:12:17 +00:00
joboet
8c37fdf2d7
std: make ReentrantMutex movable and const; simplify Stdout initialization 2022-09-03 14:05:28 +02:00
Chris Denton
0fe54d4650
Restore old behaviour on broken UNC paths 2022-09-03 07:56:38 +01:00
Dylan DPC
414d79d567
Rollup merge of #101330 - wkordalski:hashset-drain-doc, r=jyn514
Fix `std::collections::HashSet::drain` documentation

Hi!

`std::collections::HashSet::drain` contains small typo in the docstring.

I didn't read too much about the model of contributing to Rust, so merge this PR or close and fix the typo the right way :)

Thanks for Rust!
2022-09-03 10:33:07 +05:30
Dylan DPC
c42df986da
Rollup merge of #101325 - ChrisDenton:BCRYPT_RNG_ALG_HANDLE, r=thomcc
Windows RNG: Use `BCRYPT_RNG_ALG_HANDLE` by default

This only changes a small amount of actual code, the rest is documentation outlining the history of this module as I feel it will be relevant to any future issues that might crop up.

The code change is to use the `BCRYPT_RNG_ALG_HANDLE` [pseudo-handle](https://docs.microsoft.com/en-us/windows/win32/seccng/cng-algorithm-pseudo-handles) by default, which simply uses the default RNG. Previously we used `BCRYPT_USE_SYSTEM_PREFERRED_RNG` which has to load the system configuration and then find and load that RNG. I suspect this was the cause of failures on some systems (e.g. due to corrupted config). However, this is admittedly speculation as I can't reproduce the issue myself (and it does seem quite rare even in the wild). Still, removing a possible point of failure is likely worthwhile in any case.

r? libs
2022-09-03 10:33:06 +05:30
Dylan DPC
2ed716a81d
Rollup merge of #99736 - lopopolo:lopopolo/gh-80996-partial-stabilization-bounds-as-ref, r=dtolnay
Partially stabilize `bound_as_ref` by stabilizing `Bound::as_ref`

Stabilizing `Bound::as_ref` will simplify the implementation for `RangeBounds<usize>` for custom range types:

```rust
impl RangeBounds<usize> for Region {
    fn start_bound(&self) -> Bound<&usize> {
        // TODO: Use `self.start.as_ref()` when upstream `std` stabilizes:
        // https://github.com/rust-lang/rust/issues/80996
        match self.start {
            Bound::Included(ref bound) => Bound::Included(bound),
            Bound::Excluded(ref bound) => Bound::Excluded(bound),
            Bound::Unbounded => Bound::Unbounded,
        }
    }

    fn end_bound(&self) -> Bound<&usize> {
        // TODO: Use `self.end.as_ref()` when upstream `std` stabilizes:
        // https://github.com/rust-lang/rust/issues/80996
        match self.end {
            Bound::Included(ref bound) => Bound::Included(bound),
            Bound::Excluded(ref bound) => Bound::Excluded(bound),
            Bound::Unbounded => Bound::Unbounded,
        }
    }
}
```

See:

- #80996
- https://github.com/rust-lang/rust/issues/80996#issuecomment-1194575470

cc `@yaahc` who suggested partial stabilization.
2022-09-03 10:33:04 +05:30
asquared31415
80e035c9e4 implement IsZero for Saturating and Wrapping 2022-09-02 19:55:01 -04:00
bors
8c6ce6b91b Auto merge of #97802 - Enselic:add-no_ignore_sigkill-feature, r=joshtriplett
Support `#[unix_sigpipe = "inherit|sig_dfl"]` on `fn main()` to prevent ignoring `SIGPIPE`

When enabled, programs don't have to explicitly handle `ErrorKind::BrokenPipe` any longer. Currently, the program

```rust
fn main() { loop { println!("hello world"); } }
```

will print an error if used with a short-lived pipe, e.g.

    % ./main | head -n 1
    hello world
    thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', library/std/src/io/stdio.rs:1016:9
    note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

by enabling `#[unix_sigpipe = "sig_dfl"]` like this

```rust
#![feature(unix_sigpipe)]
#[unix_sigpipe = "sig_dfl"]
fn main() { loop { println!("hello world"); } }
```

there is no error, because `SIGPIPE` will not be ignored and thus the program will be killed appropriately:

    % ./main | head -n 1
    hello world

The current libstd behaviour of ignoring `SIGPIPE` before `fn main()` can be explicitly requested by using `#[unix_sigpipe = "sig_ign"]`.

With `#[unix_sigpipe = "inherit"]`, no change at all is made to `SIGPIPE`, which typically means the behaviour will be the same as `#[unix_sigpipe = "sig_dfl"]`.

See https://github.com/rust-lang/rust/issues/62569 and referenced issues for discussions regarding the `SIGPIPE` problem itself

See the [this](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Proposal.3A.20First.20step.20towards.20solving.20the.20SIGPIPE.20problem) Zulip topic for more discussions, including about this PR.

Tracking issue: https://github.com/rust-lang/rust/issues/97889
2022-09-02 21:08:08 +00:00
Ben Kimock
a7b4f189d8 Update backtrace 2022-09-02 16:09:58 -04:00
Matthias Krüger
1e008fec04
Rollup merge of #101260 - ChrisDenton:attribute-tag, r=thomcc
Use `FILE_ATTRIBUTE_TAG_INFO` to get reparse tag

I've been looking at this code recently and it just occurred to me we don't actually use the full reparse data at this point, only the tag. [`GetFileInformationByHandleEx`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfileinformationbyhandleex) can do exactly that by filling a [`FILE_ATTRIBUTE_TAG_INFO`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_attribute_tag_info) struct.

r? ```````@thomcc``````` since you've made changes here recently (which is why I have this code on my mind atm)
2022-09-02 18:22:02 +02:00
Wojciech Kordalski
532d5f2320
Fix std::collections::HashSet::drain documentation 2022-09-02 16:35:40 +02:00
Chris Denton
bc793c9fb2
Use BCRYPT_RNG_ALG_HANDLE by default
Also briefly document the history of `sys/windows/rand.rs` as they may be relevant to any future changes.
2022-09-02 14:30:16 +01:00
Chris Denton
3fee843ebb
Fix internal doc link
The doc link from `DedupSortedIter` to `BTreeMap::bulk_build_from_sorted_iter` was broken when building internal documentation,
2022-09-02 13:32:16 +01:00
Guillaume Gomez
0e82dc969f
Rollup merge of #99583 - shepmaster:provider-plus-plus, r=yaahc
Add additional methods to the Demand type

This adds on to the original tracking issue #96024

r? `````@yaahc`````
2022-09-02 11:34:46 +02:00
Guillaume Gomez
07f43a1ca1
Rollup merge of #97739 - a2aaron:let_underscore, r=estebank
Uplift the `let_underscore` lints from clippy into rustc.

This PR resolves #97241.

This PR adds three lints from clippy--`let_underscore_drop`, `let_underscore_lock`, and `let_underscore_must_use`, which are meant to capture likely-incorrect uses of `let _ = ...` bindings (in particular, doing this on a type with a non-trivial `Drop` causes the `Drop` to occur immediately, instead of at the end of the scope. For a type like `MutexGuard`, this effectively releases the lock immediately, which is almost certainly the wrong behavior)

In porting the lints from clippy I had to copy over a bunch of utility functions from `clippy_util` that these lints also relied upon. Is that the right approach?

Note that I've set the `must_use` and `drop` lints to Allow by default and set `lock` to Deny by default (this matches the same settings that clippy has). In talking with `@estebank` he informed me to do a Crater run (I am not sure what type of Crater run to request here--I think it's just "check only"?)

On the linked issue, there's some discussion about using `must_use` and `Drop` together as a heuristic for when to warn--I did not implement this yet.

r? `@estebank`
2022-09-02 11:34:45 +02:00
Matthias Krüger
b36fd55804
Rollup merge of #101270 - m-ou-se:update-comment, r=joshtriplett
Update outdated comment about output capturing in print_to.
2022-09-01 21:37:16 +02:00
Matthias Krüger
36d050645f
Rollup merge of #101190 - yjhn:patch-1, r=Mark-Simulacrum
Make docs formulation more consistent for NonZero{int}

Use third person, as it is used for other `std` documentation.
2022-09-01 21:37:10 +02:00
Adam-Gleave
33afe9724a Remove trailing whitespace 2022-09-01 17:32:00 +01:00
Adam-Gleave
9d0542b76d Document eager evaluation of bool::then_some argument 2022-09-01 16:09:25 +01:00
Mara Bos
a20318d94b Update outdated comment about output capturing in print_to. 2022-09-01 11:20:08 +02:00
bors
b32223fec1 Auto merge of #100707 - dzvon:fix-typo, r=davidtwco
Fix a bunch of typo

This PR will fix some typos detected by [typos].

I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.

[typos]: https://github.com/crate-ci/typos
2022-09-01 05:39:58 +00:00
Martin Nordholts
3810d4a368 unix_sigpipe: Make sigpipe param docs long-form 2022-09-01 06:45:04 +02:00
Chris Denton
630f831cd0
Use FILE_ATTRIBUTE_TAG_INFO to get reparse tag
This avoid unnecessarily getting the full reparse data when all we need is the tag.
2022-09-01 04:17:36 +01:00
bors
3892b7074d Auto merge of #100210 - mystor:proc_macro_diag_struct, r=eddyb
proc_macro/bridge: send diagnostics over the bridge as a struct

This removes some RPC when creating and emitting diagnostics, and
simplifies the bridge slightly.

After this change, there are no remaining methods which take advantage
of the support for `&mut` references to objects in the store as
arguments, meaning that support for them could technically be removed if
we wanted. The only remaining uses of immutable references into the
store are `TokenStream` and `SourceFile`.

r? `@eddyb`
2022-09-01 00:26:53 +00:00
Matthias Krüger
3da66f0353
Rollup merge of #101236 - thomcc:winfs-nozero, r=ChrisDenton
Avoid needless buffer zeroing in `std::sys::windows::fs`

Followup to https://github.com/rust-lang/rust/pull/101171 and https://github.com/rust-lang/rust/pull/101193. This finishes up avoiding buffer zeroing pointed out in https://github.com/rust-lang/rust/pull/100729#issuecomment-1220055311 (thanks!)

r? `@ChrisDenton`
2022-08-31 21:30:17 +02:00
Matthias Krüger
c30c42ee29
Rollup merge of #101229 - mgeisler:link-try-operator, r=thomcc
Link “? operator” to relevant chapter in The Book

Before, the text simply asked people to use a symbol which is hard to
search for. Now the text links back to the chapter on error
propagation in The Book. That should help people find the relevant
keywords for further searches.
2022-08-31 21:30:15 +02:00
Martin Nordholts
3d1a4e4f27 unix_sigpipe: Add docs for init() sigpipe param 2022-08-31 18:20:49 +02:00
Martin Nordholts
236903f7e9 unix_sigpipe: Inline compiler sigpipe constants in std 2022-08-31 18:20:49 +02:00
Ralf Jung
2a02882667
Rollup merge of #101237 - RalfJung:into-iter-zst, r=thomcc
fix into_iter on ZST

Fixes https://github.com/rust-lang/rust/issues/101235
Thanks to `@ChrisDenton` for [spotting the problem](https://github.com/rust-lang/rust/pull/100819#pullrequestreview-1091755930).
2022-08-31 14:29:55 +02:00
Ralf Jung
fe29ac9a44 fix into_iter on ZST 2022-08-31 14:21:35 +02:00
Thom Chiovoloni
14dd33b8c7
Avoid needless buffer zeroing in std::sys::windows::fs 2022-08-31 05:16:45 -07:00
Dezhi Wu
1770693771 Correct typo 2022-08-31 18:25:00 +08:00
Dezhi Wu
b1430fb7ca Fix a bunch of typo
This PR will fix some typos detected by [typos].

I only picked the ones I was sure were spelling errors to fix, mostly in
the comments.

[typos]: https://github.com/crate-ci/typos
2022-08-31 18:24:55 +08:00
Martin Geisler
e10ab62690 Link “? operator” to relevant chapter in The Book
Before, the text simply asked people to use a symbol which is hard to
search for. Now the text links back to the chapter on error
propagation in The Book. That should help people find the relevant
keywords for further searches.
2022-08-31 11:01:49 +02:00
Matthias Krüger
0ed046f44d
Rollup merge of #101171 - thomcc:fix-winfs-ub, r=ChrisDenton
Fix UB from misalignment and provenance widening in `std::sys::windows`

This fixes two types of UB:

1. Reading past the end of a reference in types like `&c::REPARSE_DATA_BUFFER` (see https://github.com/rust-lang/unsafe-code-guidelines/issues/256). This is fixed by using `addr_of!`. I think there are probably a couple more cases where we do this for other structures, and will look into it in a bit.

2. Failing to ensure that a `[u8; N]` on the stack is sufficiently aligned to convert to a `REPARSE_DATA_BUFFER`. ~~This was done by introducing a new `AlignedAs` struct that allows aligning one type to the alignment of another type. I expect there are other places where we have this issue too, or I wouldn't introduce this type, but will get to them after this lands.~~

    ~~Worth noting, it *is* implemented in a way that can cause problems depending on how we fix #81996, but this would be caught by the test I added (and presumably if we decide to fix that in a way that would break this code, we'd also introduce a `#[repr(simple)]` or `#[repr(linear)]` as a replacement for this usage of `#[repr(C)]`).~~

    Edit: None of that is still in the code, I just went with a `Align8` since that's all we'll need for almost everything we want to call.

These are more or less "potential UB" since it's likely at the moment everything works fine, although the alignment not causing issues might just be down to luck (and x86 being forgiving).

~~NB: I've only ensured this check builds, but will run tests soon.~~ All tests pass, including stage2 compiler tests.

r? ``@ChrisDenton``
2022-08-31 07:58:01 +02:00
Matthias Krüger
1484742f4a
Rollup merge of #101011 - BlackHoleFox:apple-random-improvements, r=thomcc
Use getentropy when possible on all Apple platforms

As the current code comments say, `SecRandomCopyBytes` is very heavyweight (regardless of purpose) compared to just asking the kernel directly for bytes from its own CSPRNG. We were not previously making an attempt to use the more efficient `getentropy` call on other Apple targets, instead solely using it on macOS. As the function is available on newer versions of Apple's different OSes, this changes the random filling to always attempt it first everywhere, only falling back to the less ideal alternatives after. This also cleans up the multiple Apple `imp` blocks into one.

It also should give a perf improvement, even if its likely unnoticeably small.

Refed XCode header for `getentropy` in the SDK:
```h
int getentropy(void* buffer, size_t size) __OSX_AVAILABLE(10.12) __IOS_AVAILABLE(10.0) __TVOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
```

r? ``@thomcc``
2022-08-31 07:57:56 +02:00
Matthias Krüger
b2a8d9d86c
Rollup merge of #100984 - ChrisDenton:reinstate-init, r=Mark-Simulacrum
Reinstate preloading of some dll imports

I've now come around to the conclusion that there is a justification for pre-loading the synchronization functions `WaitOnAddress` and `WakeByAddressSingle`. I've found this to have a particularly impact in testing frameworks that may have short lived processes which immediately spawn lots of threads.

Also, because pre-main initializers imply a single-threaded environment, we can switch back to using relaxed atomics which might be a minor perf improvement on some platforms (though I doubt it's particularly notable).

r? ``@Mark-Simulacrum`` and sorry for the churn here.

For convenience I'll summarise previous issues with preloading and the solutions that are included in this PR (if any):

**Issue:** User pre-main initializers may be run before std's
**Solution:** The std now uses initializers that are guaranteed to run earlier than the old initializers. A note is also added that users should not copy std's behaviour if they want to ensure they run their initializers after std.

**Issue:** Miri does not understand pre-main initializers.
**Solution:** For miri only, run the function loading lazily instead.

**Issue:** We should ideally use `LoadLibrary` to get "api-ms-win-core-synch-l1-2-0". Only "ntdll" and "kernel32" are guaranteed to always be loaded.
**Solution:** None. We can't use `LoadLibrary` pre-main. However, in the past `GetModuleHandle` has always worked in practice so this should hopefully not be a problem.

If/when Windows 7 support is dropped, we can finally remove all this for good and just use normal imports.
2022-08-31 07:57:55 +02:00
Yuki Okushi
f19783dbb8
Rollup merge of #101193 - thomcc:win-stdio-nozero, r=ChrisDenton
Avoid zeroing large stack buffers in stdio on Windows

Does what it says on the tin, using `[MaybeUninit<u16>; N]` instead of `[0u16; N]`. These buffers seem to be around 8kb, which is big enough that this is likely to be a very nice perf boost to stdio-heavy windows code.

r? ``@ChrisDenton``

*(Note: this PR also has a commit that adds windows to CI, but as it mentions I'll revert that after it comes out green -- I can only do a check build on the machine I'm typing this on)*
2022-08-31 08:47:21 +09:00
Yuki Okushi
60e8550faf
Rollup merge of #101159 - tspiteri:track-const-slice-split_at, r=Mark-Simulacrum
add tracking issue number to const_slice_split_at_not_mut

Add issue number #101158 to `const_slice_split_at_not_mut` feature.
2022-08-31 08:47:19 +09:00
Yuki Okushi
3a764e9396
Rollup merge of #100892 - sunfishcode:wasi-stdio-asfd, r=joshtriplett
Add `AsFd` implementations for stdio types on WASI.

This mirrors the implementations on Unix platforms, and also mirrors the
existing `AsRawFd` impls.
2022-08-31 08:47:15 +09:00
bors
02654a0844 Auto merge of #98919 - 5225225:stricter-invalid-value, r=RalfJung
Strengthen invalid_value lint to forbid uninit primitives, adjust docs to say that's UB

For context: https://github.com/rust-lang/rust/issues/66151#issuecomment-1174477404=

This does not make it a FCW, but it does explicitly state in the docs that uninit integers are UB.

This also doesn't affect any runtime behavior, uninit u32's will still successfully be created through mem::uninitialized.
2022-08-30 20:39:01 +00:00
Thom Chiovoloni
1b8b2dc2ff
Avoid MaybeUninit::uninit_array() 2022-08-30 06:10:55 -07:00
Thom Chiovoloni
c41f21b3e4
Fix UB in Windows DirBuffIter (provenance and alignment) 2022-08-30 05:03:22 -07:00
Thom Chiovoloni
2f9bd1a236
Avoid zeroing large stack buffers in stdio on Windows 2022-08-30 03:06:22 -07:00
yjhn
de6a3ec61a
Make docs formulation more consistent for NonZero{int}
Use third person, as it is used for other std documentation.
2022-08-30 12:29:18 +03:00
bors
0631ea5d73 Auto merge of #101183 - Dylan-DPC:rollup-6kewixv, r=Dylan-DPC
Rollup of 9 pull requests

Successful merges:

 - #95376 (Add `vec::Drain{,Filter}::keep_rest`)
 - #100092 (Fall back when relating two opaques by substs in MIR typeck)
 - #101019 (Suggest returning closure as `impl Fn`)
 - #101022 (Erase late bound regions before comparing types in `suggest_dereferences`)
 - #101101 (interpret: make read-pointer-as-bytes a CTFE-only error with extra information)
 - #101123 (Remove `register_attr` feature)
 - #101175 (Don't --bless in pre-push hook)
 - #101176 (rustdoc: remove unused CSS selectors for `.table-display`)
 - #101180 (Add another MaybeUninit array test with const)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-08-30 08:29:42 +00:00
Thom Chiovoloni
5c3490c901
Replace AlignedAs with a more specific Align8 type 2022-08-30 01:15:59 -07:00
Thom Chiovoloni
d9c760db43
Fix UWP and use AlignedReparseBuf in symlink_junction_inner 2022-08-30 00:16:53 -07:00
Dylan DPC
c731157395
Rollup merge of #95376 - WaffleLapkin:drain_keep_rest, r=dtolnay
Add `vec::Drain{,Filter}::keep_rest`

This PR adds `keep_rest` methods to `vec::Drain` and `vec::DrainFilter` under `drain_keep_rest` feature gate:
```rust
// mod alloc::vec

impl<T, A: Allocator> Drain<'_, T, A> {
    pub fn keep_rest(self);
}

impl<T, F, A: Allocator> DrainFilter<'_, T, F, A>
where
    F: FnMut(&mut T) -> bool,
{
    pub fn keep_rest(self);
}
```

Both these methods cancel draining of elements that were not yet yielded from the iterators. While this needs more testing & documentation, I want at least start the discussion. This may be a potential way out of the "should `DrainFilter` exhaust itself on drop?" argument.
2022-08-30 11:26:47 +05:30
bors
a0d07093f8 Auto merge of #100812 - Nilstrieb:revert-let-chains-nightly, r=Mark-Simulacrum
Revert let_chains stabilization

This is the revert against master, the beta revert was already done in #100538.

Bumps the stage0 compiler which already has it reverted.
2022-08-30 05:48:22 +00:00
Thom Chiovoloni
1b8025a24c
Fix some possible UB in std::sys::windows 2022-08-29 15:59:34 -07:00
bors
9f4d5d2a28 Auto merge of #101167 - matthiaskrgr:rollup-yt3jdmp, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #100898 (Do not report too many expr field candidates)
 - #101056 (Add the syntax of references to their documentation summary.)
 - #101106 (Rustdoc-Json: Retain Stripped Modules when they are imported, not when they have items)
 - #101131 (CTFE: exposing pointers and calling extern fn is just impossible)
 - #101141 (Simplify `get_trait_ref` fn used for `virtual_function_elimination`)
 - #101146 (Various changes to logging of borrowck-related code)
 - #101156 (Remove `Sync` requirement from lint pass objects)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-08-29 22:49:04 +00:00
Matthias Krüger
3bff15b7e3
Rollup merge of #101056 - kpreid:prim-doc, r=JohnTitor
Add the syntax of references to their documentation summary.

Without this change, in <https://doc.rust-lang.org/1.63.0/std/#primitives>, `reference` is the only entry in that list which does not contain the syntax by which the type is named in source code. With this change, it contains them, in roughly the same way as the `pointer` entry does.
2022-08-29 21:12:55 +02:00
Trevor Spiteri
4d95035083 add tracking issue number to const_slice_split_at_not_mut 2022-08-29 20:14:06 +02:00
Nilstrieb
d1ef8180f9 Revert let_chains stabilization
This reverts commit 3266460749.

This is the revert against master, the beta revert was already done in #100538.
2022-08-29 19:34:11 +02:00
Dylan DPC
141728fc61
Rollup merge of #100934 - a1phyr:improve_fmt_PadAdapter, r=Mark-Simulacrum
Remove a panicking branch from `fmt::builders::PadAdapter`
2022-08-29 16:49:44 +05:30
Dylan DPC
395ce34a95
Rollup merge of #100819 - WaffleLapkin:use_ptr_byte_methods, r=scottmcm
Make use of `[wrapping_]byte_{add,sub}`

These new methods trivially replace old `.cast().wrapping_offset().cast()` & similar code.
Note that [`arith_offset`](https://doc.rust-lang.org/std/intrinsics/fn.arith_offset.html) and `wrapping_offset` are the same thing.

r? ``@scottmcm``

_split off from #100746_
2022-08-29 16:49:43 +05:30
Dylan DPC
9f7e20ba35
Rollup merge of #100337 - camelid:stabilize-io_read_to_string, r=JohnTitor
Stabilize `std::io::read_to_string`

Closes #80218. 🎉

This PR stabilizes the `std::io::read_to_string` function, with the following public API:

```rust
pub fn read_to_string<R: Read>(reader: R) -> Result<String>;
```

It's analogous to `std::fs::read_to_string` for files, but it works on anything that implements `io::Read`, including `io::stdin()`.

See the tracking issue (#80218) or documentation for details.
2022-08-29 16:49:42 +05:30
Dylan DPC
1999ed798e
Rollup merge of #98801 - joshtriplett:file-create-new, r=thomcc
Add a `File::create_new` constructor

We have `File::create` for creating a file or opening an existing file,
but the secure way to guarantee creating a new file requires a longhand
invocation via `OpenOptions`.

Add `File::create_new` to handle this case, to make it easier for people
to do secure file creation.
2022-08-29 16:49:38 +05:30
bors
7a42ca942c Auto merge of #100786 - sunshowers:macos-posix-chdir, r=sunshowers
Use posix_spawn for absolute paths on macOS

Currently, on macOS, Rust never uses the fast posix_spawn path if a
directory change is requested, due to a bug in Apple's libc. However, the
bug is only triggered if the program is a relative path.

This PR makes it so that the fast path continues to work if the program
is an absolute path or a lone filename.

This was an alternative proposed in https://github.com/rust-lang/rust/pull/80537#issue-776674009, and it makes a measurable performance difference in some of my code that spawns thousands of processes.
2022-08-29 07:54:06 +00:00
Matthias Krüger
a96b44c9e2
Rollup merge of #96334 - devnexen:socket_mark, r=dtolnay
socket `set_mark` addition.

to be able to set a marker/id on the socket for network filtering
 (iptables/ipfw here) purpose.
2022-08-29 06:34:42 +02:00
Matthias Krüger
52016a1005
Rollup merge of #94890 - marmeladema:ip-addr-try-from-bytes, r=joshtriplett
Support parsing IP addresses from a byte string

Fixes #94821

The goal is to be able to parse addresses from a byte string without requiring to do any utf8 validation. Since internally the parser already works on byte strings, this should be possible and I personally already needed this in the past too.

~~I used the proposed approach from the issue by implementing `TryFrom<&'a [u8]>` for all 6 address types (3 ip address types and 3 socket address types). I believe implementing stable traits for stable types is insta-stable so this will probably need an FCP?~~

Switched to an unstable inherent method approach called `parse_ascii` as requested.

cc ``````@jyn514``````
2022-08-29 06:34:41 +02:00
Rain
bd8b4b9c15 Use posix_spawn for absolute paths on macOS
Currently, on macOS, Rust never uses the fast posix_spawn path if a
directory change is requested due to a bug in Apple's libc. However, the
bug is only triggered if the program is a relative path.

This PR makes it so that the fast path continues to work if the program
is an absolute path or a lone filename.

This was an alternative proposed in
https://github.com/rust-lang/rust/pull/80537#issue-776674009, and it
makes a measurable performance difference in some of my code that spawns
thousands of processes.
2022-08-28 19:31:09 -07:00
bors
1ea4efd065 Auto merge of #100578 - Urgau:float-next-up-down, r=scottmcm
Add next_up and next_down for f32/f64 - take 2

This is a revival of https://github.com/rust-lang/rust/pull/88728 which staled due to inactivity of the original author. I've address the last review comment.

---

This is a pull request implementing the features described at https://github.com/rust-lang/rfcs/pull/3173.

`@rustbot` label +T-libs-api -T-libs
r? `@scottmcm`
cc `@orlp`
2022-08-28 22:31:19 +00:00
Noah Lev
2df5afe622 Stabilize std::io::read_to_string 2022-08-28 13:23:19 -07:00
Martin Nordholts
ddee45e1d7 Support #[unix_sigpipe = "inherit|sig_dfl|sig_ign"] on fn main()
This makes it possible to instruct libstd to never touch the signal
handler for `SIGPIPE`, which makes programs pipeable by default (e.g.
with `./your-program | head -n 1`) without `ErrorKind::BrokenPipe`
errors.
2022-08-28 19:46:45 +02:00
bors
223d16ebbd Auto merge of #100201 - RalfJung:thread-local-key, r=thomcc
std: use realstd fast key when building tests

Under `cfg(test)`, the `std` crate is not the actual standard library, just any old crate we are testing. It imports the real standard library as `realstd`, and then does some careful `cfg` magic so that the crate built for testing uses the `realstd` global state rather than having its own copy of that.

However, this was not done for all global state hidden in std: the 'fast' version of thread-local keys, at least on some platforms, also involves some global state. Specifically its macOS version has this [`static REGISTERED`](bc63d5a26a/library/std/src/sys/unix/thread_local_dtor.rs (L62)) that would get duplicated. So this PR imports the 'fast' key type from `realstd` rather than using the local copy, to ensure its internal state (and that of the functions it calls) does not get duplicated.

I also noticed that the `__OsLocalKeyInner` is unused under `cfg(target_thread_local)`, so I removed it for that configuration. There was a comment saying macOS picks between `__OsLocalKeyInner` and `__FastLocalKeyInner` at runtime, but I think that comment is outdated -- I found no trace of such a runtime switching mechanism, and the library still check-builds on apple targets with this PR. (I don't have a Mac so I cannot actually run it.)
2022-08-28 15:12:31 +00:00
Maybe Waffle
7a433e4d00 fill-in tracking issue for feature(drain_keep_rest) 2022-08-28 17:02:37 +04:00
Maybe Waffle
8c4e0d42b2 add examples to vec::Drain{,Filter}::keep_rest docs 2022-08-28 16:58:06 +04:00
bors
ee285eab69 Auto merge of #96324 - berendjan:set_tcp_quickack, r=dtolnay
Add setter and getter for TCP_QUICKACK on TcpStream for Linux

Reference issue #96256

Setting TCP_QUICKACK on TcpStream for Linux
2022-08-28 12:26:37 +00:00
Matthias Krüger
edd81d136b
Rollup merge of #100955 - nrc:chain, r=joshtriplett
Some papercuts on error::Error

Renames the chain method, since I chain could mean anything and doesn't refer to a chain of sources (cc #58520) (and adds a comment explaining why sources is not a provided method on Error). Renames arguments to the request method from `req` to `demand` since the type is `Demand` rather than Request or Requisition.

r? ``@yaahc``
2022-08-28 09:35:17 +02:00
Matthias Krüger
15476385b5
Rollup merge of #100885 - mzohreva:mz/sgx-export-cancel-type, r=Mark-Simulacrum
Export Cancel from std::os::fortanix_sgx::usercalls::raw

This was missed in https://github.com/rust-lang/rust/pull/100642

cc ``@raoulstrackx`` and ``@jethrogb``
2022-08-28 09:35:16 +02:00
Matthias Krüger
83e83056e7
Rollup merge of #100520 - jakubdabek:patch-1, r=thomcc
Add mention of `BufReader` in `Read::bytes` docs

There is a general paragraph about `BufRead` in the `Read` trait's docs, however using `bytes` without `BufRead` *always* has a large impact, due to reads of size 1.

`@rustbot` label +A-docs
2022-08-28 09:35:15 +02:00