Commit graph

7901 commits

Author SHA1 Message Date
AngelicosPhosphoros de97d7393f Add complexity estimation of iterating over HashSet and HashMap
It is not obvious (at least for me) that complexity of iteration over hash tables depends on capacity and not length. Especially comparing with other containers like Vec or String. I think, this behaviour is worth mentioning.

I run benchmark which tests iteration time for maps with length 50 and different capacities and get this results:
```
capacity - time
64       - 203.87 ns
256      - 351.78 ns
1024     - 607.87 ns
4096     - 965.82 ns
16384    - 3.1188 us
```

If you want to dig why it behaves such way, you can look current implementation in [hashbrown code](f3a9f211d0/src/raw/mod.rs (L1933)).

Benchmarks code would be presented in PR related to this commit.
2022-05-20 18:46:24 +03:00
Ralf Jung 31c3c04498 make ptr::invalid not the same as a regular int2ptr cast 2022-05-20 17:16:41 +02:00
Caio d917112606 Stabilize core::array::from_fn 2022-05-20 11:04:13 -03:00
Guillaume Gomez 9b25cc0543
Rollup merge of #97192 - sunfishcode:sunfishcode/rightmost, r=thomcc
Say "last" instead of "rightmost" in the documentation for `std::str:rfind`

In the documentation comment for `std::str::rfind`, say "last" instead
of "rightmost" to describe the match that `rfind` finds. This follows the
spirit of #30459, for which `trim_left` and `trim_right` were replaced by
`trim_start` and `trim_end` to be more clear about how they work on
text which is displayed right-to-left.
2022-05-20 14:03:06 +02:00
bors cd73afadae Auto merge of #96422 - tmccombs:mutex-unpoison, r=m-ou-se
Add functions to un-poison Mutex and RwLock

See discussion at https://internals.rust-lang.org/t/unpoisoning-a-mutex/16521/3
2022-05-20 08:06:56 +00:00
Thayne McCombs a65afd82d1 Remove references to guards in documentation for clear_poison 2022-05-20 00:15:26 -06:00
bors 52cc779524 Auto merge of #97147 - Mark-Simulacrum:stage0-bump, r=pietroalbini
stage0 bootstrap bump

r? `@pietroalbini`
2022-05-20 05:44:52 +00:00
bors 4d6992bc18 Auto merge of #97027 - cuviper:yesalias-refcell, r=thomcc
Use pointers in `cell::{Ref,RefMut}` to avoid `noalias`

When `Ref` and `RefMut` were based on references, they would get LLVM `noalias` attributes that were incorrect, because that alias guarantee is only true until the guard drops. A `&RefCell` on the same value can get a new borrow that aliases the previous guard, possibly leading to miscompilation. Using `NonNull` pointers in `Ref` and `RefCell` avoids `noalias`.

Fixes the library side of #63787, but we still might want to explore language solutions there.
2022-05-20 01:05:53 +00:00
Dan Gohman b836cf6fb8 Say "last" instead of "rightmost" in the documentation for std::str::rfind.
In the documentation comment for `std::str::rfind`, say "last" instead
of "rightmost" to describe the match that `rfind` finds. This follows the
spirit of #30459, for which `trim_left` and `trim_right` were replaced by
`trim_start` and `trim_end` to be more clear about how they work on
text which is displayed right-to-left.
2022-05-19 15:31:17 -07:00
SylvainDe 4c1daba940 Add implicit call to from_str via parse in documentation
The documentation mentions "FromStr’s from_str method is often used implicitly,
through str’s parse method. See parse’s documentation for examples.".

It may be nicer to show that in the code example as well.
2022-05-19 22:01:43 +02:00
ajtribick 1a41a665cf
Reverse condition in Vec::retain_mut doctest 2022-05-19 20:54:16 +02:00
Dylan DPC 175974743a
Rollup merge of #97170 - benediktwerner:master, r=JohnTitor
Remove unnecessay .report() on ExitCode

Since #93442, the return type is `ExitCode` anyway so there's no need to do a conversion using `.report()` (which is now just a no-op).
2022-05-19 17:22:51 +02:00
Dylan DPC 12644bc39d
Rollup merge of #97155 - alygin:patch-1, r=JohnTitor
Fix doc typo

Fixes a minor doc typo for `atomic::fence()`.
2022-05-19 17:22:49 +02:00
benediktwerner 7013dc52d5 Remove unnecessay .report() on ExitCode 2022-05-19 11:47:36 +02:00
Thayne McCombs 66d88c9a18 Change clear_poison to take the lock instead of a guard 2022-05-19 01:53:41 -06:00
bors 50872bdb99 Auto merge of #97033 - nbdd0121:unwind3, r=Amanieu
Remove libstd's calls to `C-unwind` foreign functions

Remove all libstd and its dependencies' usage of `extern "C-unwind"`.

This is a prerequiste of a WIP PR which will forbid libraries calling `extern "C-unwind"` functions to be compiled in `-Cpanic=unwind` and linked against `panic_abort` (this restriction is necessary to address soundness bug #96926).
Cargo will ensure all crates are compiled with the same `-Cpanic` but the std is only compiled `-Cpanic=unwind` but needs the ability to be linked into `-Cpanic=abort`.

Currently there are two places where `C-unwind` is used in libstd:
* `__rust_start_panic` is used for interfacing to the panic runtime. This could be `extern "Rust"`
* `_{rdl,rg}_oom`: a shim `__rust_alloc_error_handler` will be generated by codegen to call into one of these; they can also be `extern "Rust"` (in fact, the generated shim is used as `extern "Rust"`, so I am not even sure why these are not, probably because they used to `extern "C"` and was changed to `extern "C-unwind"` when we allow alloc error hooks to unwind, but they really should just be using Rust ABI).

For dependencies, there is only one `extern "C-unwind"` function call, in `unwind` crate. This can be expressed as a re-export.

More dicussions can be seen in the Zulip thread: https://rust-lang.zulipchat.com/#narrow/stream/210922-project-ffi-unwind/topic/soundness.20in.20mixed.20panic.20mode

`@rustbot` label: T-libs F-c_unwind
2022-05-19 04:04:40 +00:00
bors e6327bc8b8 Auto merge of #97159 - JohnTitor:rollup-ibl51vw, r=JohnTitor
Rollup of 6 pull requests

Successful merges:

 - #96866 (Switch CI bucket uploads to intelligent tiering)
 - #97062 (Couple of refactorings to cg_ssa::base::codegen_crate)
 - #97127 (Revert "Auto merge of #96441 - ChrisDenton:sync-pipes, r=m-ou-se")
 - #97131 (Improve println! documentation)
 - #97139 (Move some settings DOM generation out of JS)
 - #97152 (Update cargo)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-19 01:41:07 +00:00
Yuki Okushi b7d72add46
Rollup merge of #97131 - gimbles:patch-2, r=Dylan-DPC
Improve println! documentation
2022-05-19 08:22:43 +09:00
Yuki Okushi 8aba26d34c
Rollup merge of #97127 - Mark-Simulacrum:revert-96441, r=m-ou-se
Revert "Auto merge of #96441 - ChrisDenton:sync-pipes, r=m-ou-se"

This reverts commit ddb7fbe843.

Partially addresses https://github.com/rust-lang/rust/issues/97124, but not marking as fixed as we're still pending on a beta backport (for 1.62, which is happening in https://github.com/rust-lang/rust/pull/97088).

r? ``@m-ou-se`` ``@ChrisDenton``
2022-05-19 08:22:43 +09:00
bors d8a3fc4d71 Auto merge of #95643 - WaffleLapkin:ptr_convenience, r=joshtriplett
Add convenience byte offset/check align functions to pointers

This PR adds the following APIs:
```rust
impl *const T {
    // feature gates `pointer_byte_offsets` and `const_pointer_byte_offsets
    pub const unsafe fn byte_offset(self, count: isize) -> Self;
    pub const fn wrapping_byte_offset(self, count: isize) -> Self;
    pub const unsafe fn byte_offset_from(self, origin: *const T) -> isize;
    pub const unsafe fn byte_add(self, count: usize) -> Self;
    pub const unsafe fn byte_sub(self, count: usize) -> Self;
    pub const fn wrapping_byte_add(self, count: usize) -> Self;
    pub const fn wrapping_byte_sub(self, count: usize) -> Self;

    // feature gate `pointer_is_aligned`
    pub fn is_aligned(self) -> bool where T: Sized;
    pub fn is_aligned_to(self, align: usize) -> bool;
}
// ... and the same for` *mut T`
```

Note that all functions except `is_aligned` do **not** require `T: Sized` as their pointee-sized-offset counterparts.

cc `@oli-obk` (you may want to check that I've correctly placed `const`s)
cc `@RalfJung`
2022-05-18 23:18:03 +00:00
Andrew Lygin 0d99b90983
Fix doc typo 2022-05-19 00:25:14 +03:00
Mark Rousskov 32fdc6b207 Stage-step cfgs 2022-05-18 12:29:35 -04:00
Sam Robinson-Adams d8ef340d99
Fix rusty grammar in std::error::Reporter docs
I initially saw "print's" instead of "prints" at the start of the doc comment for `std::error::Reporter`, while reading the docs for that type. Then I figured 'probably more where that came from', so, as well as correcting the foregoing to "prints", I've patched up these three minor solecisms (well, two [types](https://en.wikipedia.org/wiki/Type%E2%80%93token_distinction), three [tokens](https://en.wikipedia.org/wiki/Type%E2%80%93token_distinction)):

- One use of the indicative which should be subjunctive - indeed the sentence immediately following it, which mirrors its structure, _does_ use the subjunctive ([L871](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L871)). Replaced with the subjunctive.
- Two separate clauses joined with commas ([L975](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L975), [L1023](https://github.com/rust-lang/rust/blob/master/library/std/src/error.rs?plain=1#L1023)). Replaced the first with a semicolon and the second with a period. Admittedly those judgements are pretty much 100% subjective, based on my sense of how the sentences flowed into each other (though ofc the _replacement of the comma itself_ is not subjective or opinion-based).

I know this is silly and finicky, but I hope it helps tidy up the docs a bit for future readers!
2022-05-18 15:10:18 +01:00
Dylan DPC 2d95c6acab
Rollup merge of #97101 - coolreader18:exitcode-method-issue, r=yaahc
Add tracking issue for ExitCode::exit_process

r? `@yaahc`
2022-05-18 08:41:17 +02:00
Dylan DPC 927a40b1a7
Rollup merge of #96917 - marti4d:master, r=ChrisDenton
Make HashMap fall back to RtlGenRandom if BCryptGenRandom fails

With PR #84096, Rust `std::collections::hash_map::RandomState` changed from using `RtlGenRandom()` ([msdn](https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-rtlgenrandom)) to `BCryptGenRandom()` ([msdn](https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom)) as its source of secure randomness after much discussion ([here](https://github.com/rust-random/getrandom/issues/65#issuecomment-753634074), among other places).

Unfortunately, after that PR landed, Mozilla Firefox started experiencing fairly-rare crashes during startup while attempting to initialize the `env_logger` crate. ([docs for env_logger](https://docs.rs/env_logger/latest/env_logger/)) The root issue is that on some machines, `BCryptGenRandom()` will fail with an `Access is denied. (os error 5)` error message. ([Bugzilla issue 1754490](https://bugzilla.mozilla.org/show_bug.cgi?id=1754490)) (Discussion in issue #94098)

Note that this is happening upon startup of Firefox's unsandboxed Main Process, so this behavior is different and separate from previous issues ([like this](https://bugzilla.mozilla.org/show_bug.cgi?id=1746254)) where BCrypt DLLs were blocked by process sandboxing. In the case of sandboxing, we knew we were doing something abnormal and expected that we'd have to resort to abnormal measures to make it work.

However, in this case we are in a regular unsandboxed process just trying to initialize `env_logger` and getting a panic. We suspect that this may be caused by a virus scanner or some other security software blocking the loading of the BCrypt DLLs, but we're not completely sure as we haven't been able to replicate locally.

It is also possible that Firefox is not the only software affected by this; we just may be one of the pieces of Rust software that has the telemetry and crash reporting necessary to catch it.

I have read some of the historical discussion around using `BCryptGenRandom()` in Rust code, and I respect the decision that was made and agree that it was a good course of action, so I'm not trying to open a discussion about a return to `RtlGenRandom()`. Instead, I'd like to suggest that perhaps we use `RtlGenRandom()` as a "fallback RNG" in the case that BCrypt doesn't work.

This pull request implements this fallback behavior. I believe this would improve the robustness of this essential data structure within the standard library, and I see only 2 potential drawbacks:

1. Slight added overhead: It should be quite minimal though. The first call to `sys::rand::hashmap_random_keys()` will incur a bit of initialization overhead, and every call after will incur roughly 2 non-atomic global reads and 2 easily predictable branches. Both should be negligible compared to the actual cost of generating secure random numbers
2. `RtlGenRandom()` is deprecated by Microsoft: Technically true, but as mentioned in [this comment on GoLang](https://github.com/golang/go/issues/33542#issuecomment-626124873), this API is ubiquitous in Windows software and actually removing it would break lots of things. Also, Firefox uses it already in [our C++ code](https://searchfox.org/mozilla-central/rev/5f88c1d6977e03e22d3420d0cdf8ad0113c2eb31/mfbt/RandomNum.cpp#25), and [Chromium uses it in their code as well](https://source.chromium.org/chromium/chromium/src/+/main:base/rand_util_win.cc) (which transitively means that Microsoft uses it in their own web browser, Edge). If there did come a time when Microsoft truly removes this API, it should be easy enough for Rust to simply remove the fallback in the code I've added here
2022-05-18 08:41:16 +02:00
Gim a47edcf72a
Update macros.rs 2022-05-18 07:31:58 +05:30
Mark Rousskov 6259670d50 Revert "Auto merge of #96441 - ChrisDenton:sync-pipes, r=m-ou-se"
This reverts commit ddb7fbe843, reversing
changes made to baaa3b6829.
2022-05-17 18:46:11 -04:00
Noa e68e9775e2
Add tracking issue for ExitCode::exit_process 2022-05-16 22:56:26 -05:00
Josh Stone 1f33c921d1 Add a comment for covariant Ref 2022-05-16 17:24:53 -07:00
Josh Stone 1e53fab55a Remove outdated references to nll-rfc#40 2022-05-16 17:22:51 -07:00
Chris Martin aba3454aa1 Improve error message for fallback RNG failure 2022-05-16 13:49:12 -04:00
Nilstrieb 4a2214885d Clarify slice and Vec iteration order
While already being inferable from the doc examples, it wasn't
fully specified. This is the only logical way to do a slice
iterator.
2022-05-16 19:29:45 +02:00
Raoul Strackx 3e252a7ffc Allow unused_macro_rules in path tests 2022-05-16 08:55:05 +02:00
bors 56d540e057 Auto merge of #97053 - CAD97:realloc-clarification, r=dtolnay
Remove potentially misleading realloc parenthetical

This parenthetical is problematic, because it suggests that the following is sound:

```rust
let layout = Layout:🆕:<[u8; 32]>();
let p1 = alloc(layout);
let p2 = realloc(p1, layout, 32);
if p1 == p2 {
    p1.write([0; 32]);
    dealloc(p1, layout);
} else {
    dealloc(p2, layout);
}
```

At the very least, this isn't the case for [ANSI `realloc`](https://en.cppreference.com/w/c/memory/realloc)

> The original pointer `ptr` is invalidated and any access to it is undefined behavior (even if reallocation was in-place).

and [Windows `HeapReAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heaprealloc) is unclear at best (`HEAP_REALLOC_IN_PLACE_ONLY`'s description may imply that the old pointer may be used if `HEAP_REALLOC_IN_PLACE_ONLY` is provided).

The conservative position is to just remove the parenthetical.

cc `@rust-lang/wg-unsafe-code-guidelines` `@rust-lang/wg-allocators`
2022-05-16 02:33:34 +00:00
bors cdd74fc7b1 Auto merge of #97065 - gabriel-doriath-dohler:master, r=joshtriplett
Rename `eq_ignore_case` to `starts_with_ignore_case`

The method doesn't test for equality. It tests if the object starts with
a given byte array, so its name is confusing.
2022-05-16 00:12:06 +00:00
gabriel-doriath-dohler 26265319c7 Rename eq_ignore_case to starts_with_ignore_case
The method doesn't test for equality. It tests if the object starts with
a given byte array, so its name is confusing.
2022-05-15 23:59:59 +00:00
Dylan DPC d56c59efdc
Rollup merge of #97060 - bdbai:fix/uwphandle, r=ChrisDenton
Fix use of SetHandleInformation on UWP

The use of `SetHandleInformation` (introduced in #96441 to make `HANDLE` inheritable) breaks UWP builds because it is not available for UWP targets.

Proposed workaround: duplicate the `HANDLE` with `inherit = true` and immediately close the old one. Traditional Windows Desktop programs are not affected.

cc `@ChrisDenton`
2022-05-15 18:41:27 +02:00
Dylan DPC f8832c23da
Rollup merge of #96947 - sunfishcode:sunfishcode/rustc-nonnull-optimization-guaranteed, r=joshtriplett
Add rustc_nonnull_optimization_guaranteed to Owned/Borrowed Fd/Socket

PR #94586 added support for using
`rustc_nonnull_optimization_guaranteed` on values where the "null" value
is the all-ones bitpattern.

Now that #94586 has made it to the stage0 compiler, add
`rustc_nonnull_optimization_guaranteed` to `OwnedFd`, `BorrowedFd`,
`OwnedSocket`, and `BorrowedSocket`, since these types all exclude
all-ones bitpatterns.

This allows `Option<OwnedFd>`, `Option<BorrowedFd>`, `Option<OwnedSocket>`,
and `Option<BorrowedSocket>` to be used in FFI declarations, as described
in the [I/O safety RFC].

[I/O safety RFC]: https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md#ownedfd-and-borrowedfdfd-1
2022-05-15 18:41:25 +02:00
bdbai 4f637ee30b fix use of SetHandleInformation on UWP 2022-05-15 21:15:45 +08:00
CAD97 09dc24bc04 Remove potentially misleading realloc parenthetical 2022-05-14 22:30:14 -05:00
bors 17180f4a56 Auto merge of #94872 - mati865:mingw-llvm-target, r=petrochenkov
Add MVP LLVM based mingw-w64 targets

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

Those are `rustc` side changes to create working x86_64 and AArch64 Rustc hosts and targets.
Apart from this PR changes to various crates are required which I'll do once this is accepted.

I'm expecting more changes on `rustc` side later on as I cannot even run full testsuite at this moment because passing JSON spec breaks paths in various tests.

Tier 3 policy:

> A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)

I pledge to do my best maintaining it, MSYS2 is one of interested consumers so it should have enough testing (after the releases).

 > Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.

This triple name was discussed at [`t-compiler/LLVM+mingw-w64 Windows targets`](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/LLVM.2Bmingw-w64.20Windows.20targets)

> Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.

I think the explanation in platform support doc is enough to make this aspect clear.

> Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.

It's using open source tools only.

> The target must not introduce license incompatibilities.

It's even more liberal than already existing `*-pc-windows-gnu`.

> Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).

Understood.

> The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements.

There are no new dependencies/features required.

> Compiling, linking, and emitting functional binaries, libraries, or other code for the target (whether hosted on the target itself or cross-compiling from another target) must not depend on proprietary (non-FOSS) libraries. Host tools built for the target itself may depend on the ordinary runtime libraries supplied by the platform and commonly used by other applications built for the target, but those libraries must not be required for code generation for the target; cross-compilation to the target must not require such libraries at all. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3.

As previously said it's using open source tools only.

> "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users.

There are no such terms present/

> Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.

I'm not the reviewer here.

> This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements.

Again I'm not the reviewer here.

> Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.

> The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary.

Building is described in platform support doc, running tests doesn't work right now (without hacks) because Rust's build system doesn't seem to support testing targets built from `.json`.
Docs will be updated once this lands in beta allowing master branch to build and run tests without `.json` files.

> Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via `@)` to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.

Understood.

> Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications.

Understood.

 > Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.

I believe I didn't break any other target.

> In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target.

I think there are no such problems in this PR.
2022-05-14 08:20:11 +00:00
bors c31879922e Auto merge of #97035 - JohnTitor:rollup-00ko07z, r=JohnTitor
Rollup of 6 pull requests

Successful merges:

 - #95365 (Use default alloc_error_handler for hermit)
 - #96986 ([save-analysis] Reference the variant not enum at struct-literal cons…)
 - #96998 (rustdoc: remove weird, unused variable from source-files.js)
 - #97005 (Two small improvements of rustc_expand)
 - #97018 (Ensure that test fail if a JS error occurs)
 - #97031 (Drop tracking: handle invalid assignments better)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-14 05:53:39 +00:00
Yuki Okushi 6c6958b531
Rollup merge of #95365 - mkroening:hermit-alloc-error-handler, r=joshtriplett
Use default alloc_error_handler for hermit

Hermit now properly separates kernel from userspace.
Applications for hermit can now use Rust's default `alloc_error_handler` instead of calling the kernel's `__rg_oom`.

CC: ``@stlankes``
2022-05-14 13:42:49 +09:00
bors 9fbbe75fd7 Auto merge of #95602 - scottmcm:faster-array-intoiter-fold, r=the8472
Fix `array::IntoIter::fold` to use the optimized `Range::fold`

It was using `Iterator::by_ref` in the implementation, which ended up pessimizing it enough that, for example, it didn't vectorize when we tried it in the <https://rust-lang.zulipchat.com/#narrow/stream/257879-project-portable-simd/topic/Reducing.20sum.20into.20wider.20types> conversation.

Demonstration that the codegen test doesn't pass on the current nightly: <https://rust.godbolt.org/z/Taxev5eMn>
2022-05-14 03:12:53 +00:00
Gary Guo fbb3c19e03 Use re-export instead of inline wrapper in libunwind
This ensures that there are no calls to `C-unwind` function in libunwind.
2022-05-14 02:53:59 +01:00
Gary Guo 68f063bf3f Use Rust ABI for __rust_start_panic and _{rdl,rg}_oom 2022-05-14 02:53:59 +01:00
Chris Martin 3de6c2ca33 Address review feedback 2022-05-13 18:14:03 -04:00
bors f1f721e640 Auto merge of #97013 - matthiaskrgr:rollup-c1pc6pc, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #96154 (Expand core::hint::unreachable_unchecked() docs)
 - #96615 (Add a regression test for #54779)
 - #96982 (fix clippy expect_fun_call)
 - #97003 (Remove some unnecessary `rustc_allow_const_fn_unstable` attributes.)
 - #97011 (Add regression test for #28935)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2022-05-13 20:26:04 +00:00
Nilstrieb d11667f5cc Change orderings of Debug for the Atomic types to Relaxed.
This reduces synchronization between threads when
debugging the atomic types.
Reducing the synchronization means that executions with and
without the debug calls will be more consistent,
making it easier to debug.
2022-05-13 21:22:54 +02:00
Josh Stone 2b8041f574 Use a pointer in cell::RefMut so it's not noalias 2022-05-13 12:08:54 -07:00
Josh Stone d369045aed Use a pointer in cell::Ref so it's not noalias 2022-05-13 11:42:10 -07:00
bors 9ad4bde042 Auto merge of #95356 - coolreader18:exitstatus-exit-method, r=<try>
ExitCode::exit_process() method

cc `@yaahc` / #93840

(eeek, hit ctrl-enter before I meant to and right after realizing the branch name was wrong. oh, well)

I feel like it makes sense to have the `exit(ExitCode)` function as a method or at least associated function on ExitCode, but maybe that would hurt discoverability? Probably not as much if it's at the top of the `process::exit()` documentation or something, but idk. Also very unsure about the name, I'd like something that communicates that you are exiting with *this* ExitCode, but with a method name being postfix it doesn't seem to flow. `code.exit_process_with()` ? `.exit_process_with_self()` ? Blech. Maybe it doesn't matter, since ideally just `code.exit()` or something would be clear simply by the name and single parameter but 🤷

Also I'd like to touch up the `ExitCode` docs (which I did a bit here), but that would probably be good in a separate PR, right? Since I think the beta deadline is coming up.
2022-05-13 18:29:13 +00:00
Noa a9e29d204e
Guarantee less in docs 2022-05-13 13:28:24 -05:00
Noa 688dcc68fe
Add ExitCode::exit_process example 2022-05-13 13:28:22 -05:00
Mateusz Mikuła 60361f2ca3 Add LLVM based mingw-w64 targets 2022-05-13 20:14:15 +02:00
Simon Sapin 7ccc09b210 Extend ptr::null and null_mut to all thin (including extern) types
Fixes https://github.com/rust-lang/rust/issues/93959

This change was accepted in https://rust-lang.github.io/rfcs/2580-ptr-meta.html

Note that this changes the signature of **stable** functions.
The change should be backward-compatible, but it is **insta-stable**
since it cannot (easily, at all?) be made available only
through a `#![feature(…)]` opt-in.

The RFC also proposed the same change for `NonNull::dangling`,
which makes sense it terms of its signature but not in terms of its implementation.
`dangling` uses `align_of()` as an address. But what `align_of()` should be for
extern types or whether it should be allowed at all remains an open question.

This commit depends on https://github.com/rust-lang/rust/pull/93977, which is not yet
part of the bootstrap compiler. So `#[cfg]` is used to only apply the change in
stage 1+. As far a I know bounds cannot be made conditional with `#[cfg]`, so the
entire functions are duplicated. This is unfortunate but temporary.

Since this duplication makes it less obvious in the diff,
the new definitions differ in:

* More permissive bounds (`Thin` instead of implied `Sized`)
* Different implementation
* Having `rustc_allow_const_fn_unstable(ptr_metadata)`
2022-05-13 18:03:06 +02:00
Matthias Krüger a56211a44e
Rollup merge of #97003 - nnethercote:rm-const_fn-attrs, r=fee1-dead
Remove some unnecessary `rustc_allow_const_fn_unstable` attributes.

r? `@fee1-dead`
2022-05-13 16:03:25 +02:00
Matthias Krüger feb18d102a
Rollup merge of #96154 - lukaslueg:unreachablehint, r=scottmcm
Expand core::hint::unreachable_unchecked() docs

Rework the docs for `unreachable_unchecked`, encouraging deliberate use, and providing a better example for action at a distance.

Fixes #95865
2022-05-13 16:03:22 +02:00
Scott McMurray e8fc7ba6a7 Slap #[inline] on all the ByRefSized methods, per the8472's suggestion 2022-05-13 00:43:15 -07:00
Nicholas Nethercote fd01fbc058 Remove some unnecessary rustc_allow_const_fn_unstable attributes. 2022-05-13 16:01:18 +10:00
Matthias Krüger f38b7ff3b6
Rollup merge of #96932 - sunfishcode:sunfishcode/document-borrowed-handle, r=joshtriplett
Clarify what values `BorrowedHandle`, `OwnedHandle` etc. can hold.

Reword the documentation to clarify that when `BorrowedHandle`, `OwnedHandle`, or `HandleOrNull` hold the value `-1`, it always means the current process handle, and not `INVALID_HANDLE_VALUE`.

`-1` should only mean `INVALID_HANDLE_VALUE` after a call to a function documented to return that to report errors, which should lead I/O functions to produce errors rather than succeeding and producing `OwnedHandle` or `BorrowedHandle` values. So if a consumer of an `OwnedHandle` or `BorrowedHandle` ever sees them holding a `-1`, it should always mean the current process handle.
2022-05-13 05:33:10 +02:00
Matthias Krüger 80e1dec10e
Rollup merge of #96860 - semarie:openbsd-futex-time64, r=cuviper
openbsd: convert futex timeout managment to Timespec usage

unbreak openbsd build after #96657

r? cuviper

please note I made `Timespec::zero()` public to be able to use it. OpenBSD is using relative timeout for `futex(2)` and I don't find simple way to use `Timespec` this way.
2022-05-12 16:41:03 +02:00
Maybe Waffle 03d4569939 Fill-in tracking issues for features pointer_byte_offsets, const_pointer_byte_offsets and pointer_is_aligned 2022-05-12 12:54:21 +04:00
Maybe Waffle 5a5d62aeb2 Optimize ptr.is_aligned_to()
Apparently LLVM is unable to understand that if count_ones() == 1 then self != 0.
Adding `assume(align != 0)` helps generating better asm:
https://rust.godbolt.org/z/ja18YKq91
2022-05-12 12:54:21 +04:00
Maybe Waffle 6c1ebff59e Implement ptr.is_aligned() in terms of .is_aligned_to() 2022-05-12 12:54:21 +04:00
Maybe Waffle a908eec438 Lift the Sized requirement from convenience ptr fns
Since they work on byte pointers (by `.cast::<u8>()`ing them), there is
no need to know the size of `T` and so there is no need for `T: Sized`.

The `is_aligned_to` is similar, though it doesn't need the _alignment_
of `T`.
2022-05-12 12:54:21 +04:00
Maybe Waffle c8c91f757a Add convenience functions to pointers
The functions added:
- {*const T,*mut T}::{wrapping_,}byte_{offset,add,sub}
- {*const T,*mut T}::{byte_offset_from,is_aligned,is_aligned_to}
2022-05-12 12:54:16 +04:00
Dan Gohman 275812ad2c Fix comment syntax. 2022-05-11 21:11:49 -07:00
Dan Gohman 516a7fa693 Relax the wording about the meaning of -1. 2022-05-11 20:50:07 -07:00
bors 1d2ea98cff Auto merge of #95837 - scottmcm:ptr-offset-from-unsigned, r=oli-obk
Add `sub_ptr` on pointers (the `usize` version of `offset_from`)

We have `add`/`sub` which are the `usize` versions of `offset`, this adds the `usize` equivalent of `offset_from`.  Like how `.add(d)` replaced a whole bunch of `.offset(d as isize)`, you can see from the changes here that it's fairly common that code actually knows the order between the pointers and *wants* a `usize`, not an `isize`.

As a bonus, this can do `sub nuw`+`udiv exact`, rather than `sub`+`sdiv exact`, which can be optimized slightly better because it doesn't have to worry about negatives.  That's why the slice iterators weren't using `offset_from`, though I haven't updated that code in this PR because slices are so perf-critical that I'll do it as its own change.

This is an intrinsic, like `offset_from`, so that it can eventually be allowed in CTFE.  It also allows checking the extra safety condition -- see the test confirming that CTFE catches it if you pass the pointers in the wrong order.
2022-05-12 02:49:00 +00:00
Scott McMurray 003b954a43 Apply CR suggestions; add real tracking issue 2022-05-11 17:16:25 -07:00
Scott McMurray 4bb15b3797 Add a debug check for ordering, and check for isize overflow in CTFE 2022-05-11 17:16:25 -07:00
Scott McMurray e76b3f3b5b Rename unsigned_offset_from to sub_ptr 2022-05-11 17:16:25 -07:00
Scott McMurray 89a18cb600 Add unsigned_offset_from on pointers
Like we have `add`/`sub` which are the `usize` version of `offset`, this adds the `usize` equivalent of `offset_from`.  Like how `.add(d)` replaced a whole bunch of `.offset(d as isize)`, you can see from the changes here that it's fairly common that code actually knows the order between the pointers and *wants* a `usize`, not an `isize`.

As a bonus, this can do `sub nuw`+`udiv exact`, rather than `sub`+`sdiv exact`, which can be optimized slightly better because it doesn't have to worry about negatives.  That's why the slice iterators weren't using `offset_from`, though I haven't updated that code in this PR because slices are so perf-critical that I'll do it as its own change.

This is an intrinsic, like `offset_from`, so that it can eventually be allowed in CTFE.  It also allows checking the extra safety condition -- see the test confirming that CTFE catches it if you pass the pointers in the wrong order.
2022-05-11 17:16:25 -07:00
bors 0cd939e36c Auto merge of #96150 - est31:unused_macro_rules, r=petrochenkov
Implement a lint to warn about unused macro rules

This implements a new lint to warn about unused macro rules (arms/matchers), similar to the `unused_macros` lint added by #41907 that warns about entire macros.

```rust
macro_rules! unused_empty {
    (hello) => { println!("Hello, world!") };
    () => { println!("empty") }; //~ ERROR: 1st rule of macro `unused_empty` is never used
}

fn main() {
    unused_empty!(hello);
}
```

Builds upon #96149 and #96156.

Fixes #73576
2022-05-12 00:08:08 +00:00
Dan Gohman 5c60951344 Fix attribute name. 2022-05-11 09:29:08 -07:00
Dan Gohman a5077f1342 RawSocket is unsigned on Windows. 2022-05-11 09:10:33 -07:00
Dan Gohman 78806d4cfe Fix duplicate import on Windows. 2022-05-11 07:41:34 -07:00
Dan Gohman 90ff6fcd4e Add rustc_nonnull_optimization_guaranteed to Owned/Borrowed Fd/Socket
PR #94586 added support for using
`rustc_nonnull_optimization_guaranteed` on values where the "null" value
is the all-ones bitpattern.

Now that #94586 has made it to the stage0 compiler, add
`rustc_nonnull_optimization_guaranteed` to `OwnedFd`, `BorrowedFd`,
`OwnedSocket`, and `BorrowedSocket`, since these types all exclude
all-ones bitpatterns.

This allows `Option<OwnedFd>`, `Option<BorrowedFd>`, `Option<OwnedSocket>`,
and `Option<BorrowedSocket>` to be used in FFI declarations, as described
in the [I/O safety RFC].

[I/O safety RFC]: https://github.com/rust-lang/rfcs/blob/master/text/3128-io-safety.md#ownedfd-and-borrowedfdfd-1
2022-05-11 07:26:49 -07:00
Dan Gohman 2f75b4aaa6 HandleOrNull can hold null, and HandleOrInvalid can hold INVALID_HANDLE_VALUE. 2022-05-11 06:40:52 -07:00
Dan Gohman 0a39e5ad36 Fix incorrect mentions of OwnedFd and BorrowedFd in Windows docs. 2022-05-10 21:56:51 -07:00
Sébastien Marie 42f8e1f879 to_timespec could be unused by some targets 2022-05-11 04:51:09 +00:00
Sébastien Marie 3cadc11d83 avoid using both Some() and ? on linux/android/freebsd code 2022-05-11 04:50:48 +00:00
Sébastien Marie f75d02d669 openbsd: convert futex timeout managment to Timespec usage 2022-05-11 04:50:23 +00:00
Dan Gohman 2bb7fdb8e1 Also document that as_raw_handle may return NULL. 2022-05-10 21:42:30 -07:00
Dan Gohman 4ce68c13bf Clarify what values BorrowedHandle, OwnedHandle etc. can hold.
Clarify that when `BorrowedHandle`, `OwnedHandle`, or `HandleOrNull`
hold the value `-1`, it always means the current process handle, and not
`INVALID_HANDLE_VALUE`.
2022-05-10 21:25:48 -07:00
bors ecd44958e0 Auto merge of #96232 - sunfishcode:sunfishcode/io-safety-const-fns, r=joshtriplett
Make `BorrowedFd::borrow_raw` a const fn.

Making `BorrowedFd::borrow_raw` a const fn allows it to be used to
create a constant `BorrowedFd<'static>` holding constants such as
`AT_FDCWD`. This will allow [`rustix::fs::cwd`] to become a const fn.

For consistency, make similar changes to `BorrowedHandle::borrow_raw`
and `BorrowedSocket::borrow_raw`.

[`rustix::fs::cwd`]: https://docs.rs/rustix/latest/rustix/fs/fn.cwd.html

r? `@joshtriplett`
2022-05-10 21:19:19 +00:00
est31 493af0b54f Also allow unused macro rules in stdarch 2022-05-10 19:53:22 +02:00
Tobias Bucher 813c5b0161 Recommend Ipv6Addr::to_ipv4_mapped over Ipv6Addr::to_ipv4
Fixes #96718.
2022-05-10 18:08:46 +02:00
Tobias Bucher 839d97e27e Stabilize Ipv6Addr::to_ipv4_mapped
CC #27709 (tracking issue for the `ip` feature which contains more
functions)

The function `Ipv6Addr::to_ipv4` is bad because it also returns an IPv4
address for the IPv6 loopback address `::1`. Stabilize
`Ipv6Addr::to_ipv4_mapped` so we can recommend that function instead.
2022-05-10 18:06:48 +02:00
Chris Martin 0c92519d01 Make HashMap fall back to RtlGenRandom if BCryptGenRandom fails
Issue #84096 changed the hashmap RNG to use BCryptGenRandom instead of
RtlGenRandom on Windows.

Mozilla Firefox started experiencing random failures in
env_logger::Builder::new() (Issue #94098) during initialization of their
unsandboxed main process with an "Access Denied" error message from
BCryptGenRandom(), which is used by the HashMap contained in
env_logger::Builder

The root cause appears to be a virus scanner or other software interfering
with BCrypt DLLs loading.

This change adds a fallback option if BCryptGenRandom is unusable for
whatever reason. It will fallback to RtlGenRandom in this case.

Fixes #94098
2022-05-10 11:30:46 -04:00
Yuki Okushi 7274447c36
Rollup merge of #96861 - m-ou-se:std-use-prelude-2021, r=joshtriplett
Use Rust 2021 prelude in std itself.
2022-05-11 00:09:34 +09:00
Yuki Okushi f689f6582c
Rollup merge of #96725 - nico-abram:win_tid, r=ChrisDenton
Expose process windows_process_extensions_main_thread_handle on Windows

~~I did not find any tests in 7d3e03666a/library/std/src/sys/windows/process/tests.rs that actually launch processes, so I haven't added tests for this.~~ I ran the following locally, to check that it works as expected:
```rs
#![feature(windows_process_extensions_main_thread_handle)]

fn main() {
    use std::os::windows::process::{ChildExt, CommandExt};
    const CREATE_SUSPENDED: u32 = 0x00000004;

    let proc = std::process::Command::new("cmd")
        .args(["/C", "echo hello"])
        .creation_flags(CREATE_SUSPENDED)
        .spawn()
        .unwrap();

    extern "system" {
        fn ResumeThread(_: *mut std::ffi::c_void) -> u32;
    }
    unsafe {
        ResumeThread(proc.main_thread_handle());
    }

    let output = proc.wait_with_output().unwrap();
    let str_output = std::str::from_utf8(&output.stdout[..]).unwrap();
    println!("{}", str_output);
}

```

Without the feature attribute it wouldn't compile, and commenting the `ResumeThread` line makes it hang forever, showing that it works.

Trakcing issue https://github.com/rust-lang/rust/issues/96723
2022-05-11 00:09:32 +09:00
Dylan DPC c5c273b30e
Rollup merge of #96674 - bstrie:vardoc, r=thomcc
docs: add link explaining variance to NonNull docs
2022-05-10 08:24:02 +02:00
unknown 5368ea7d2e Expose process main_thread_handle on Windows 2022-05-10 02:41:19 -03:00
Matthias Krüger f4bef2e41c
Rollup merge of #96841 - thomcc:revert-osstr-join, r=m-ou-se
Revert "Implement [OsStr]::join", which was merged without FCP.

This reverts commit 4fcbc53820, see https://github.com/rust-lang/rust/pull/96744. (I'm terribly sorry, and truly don't remember r+ing it, or even having seen it before yesterday, which is... genuinely very worrisome for me).

r? `@m-ou-se`
2022-05-09 18:45:37 +02:00
Matthias Krüger 6c8001b85c
Rollup merge of #96008 - fmease:warn-on-useless-doc-hidden-on-assoc-impl-items, r=lcnr
Warn on unused `#[doc(hidden)]` attributes on trait impl items

[Zulip conversation](https://rust-lang.zulipchat.com/#narrow/stream/266220-rustdoc/topic/.E2.9C.94.20Validy.20checks.20for.20.60.23.5Bdoc.28hidden.29.5D.60).

Whether an associated item in a trait impl is shown or hidden in the documentation entirely depends on the corresponding item in the trait declaration. Rustdoc completely ignores `#[doc(hidden)]` attributes on impl items. No error or warning is emitted:

```rust
pub trait Tr { fn f(); }
pub struct Ty;
impl Tr for Ty { #[doc(hidden)] fn f() {} }
//               ^^^^^^^^^^^^^^ ignored by rustdoc and currently
//                              no error or warning issued
```

This may lead users to the wrong belief that the attribute has an effect. In fact, several such cases are found in the standard library (I've removed all of them in this PR).
There does not seem to exist any incentive to allow this in the future either: Impl'ing a trait for a type means the type *fully* conforms to its API. Users can add `#[doc(hidden)]` to the whole impl if they want to hide the implementation or add the attribute to the corresponding associated item in the trait declaration to hide the specific item. Hiding an implementation of an associated item does not make much sense: The associated item can still be found on the trait page.

This PR emits the warn-by-default lint `unused_attribute` for this case with a future-incompat warning.

`@rustbot` label T-compiler T-rustdoc A-lint
2022-05-09 18:45:36 +02:00
Matthias Krüger 28d800ce1c
Rollup merge of #95483 - golddranks:improve_float_docs, r=joshtriplett
Improve floating point documentation

This is my attempt to improve/solve https://github.com/rust-lang/rust/issues/95468 and https://github.com/rust-lang/rust/issues/73328 .

Added/refined explanations:
- Refine the "NaN as a special value" top level explanation of f32
- Refine `const NAN` docstring: add an explanation about there being multitude of NaN bitpatterns and disclaimer about the portability/stability guarantees.
- Refine `fn is_sign_positive` and `fn is_sign_negative` docstrings: add disclaimer about the sign bit of NaNs.
- Refine `fn min` and `fn max` docstrings: explain the semantics and their relationship to the standard and libm better.
- Refine `fn trunc` docstrings: explain the semantics slightly more.
- Refine `fn powi` docstrings: add disclaimer that the rounding behaviour might be different from `powf`.
- Refine `fn copysign` docstrings: add disclaimer about payloads of NaNs.
- Refine `minimum` and `maximum`: add disclaimer that "propagating NaN" doesn't mean that propagating the NaN bit patterns is guaranteed.
- Refine `max` and `min` docstrings: add "ignoring NaN" to bring the one-row explanation to parity with `minimum` and `maximum`.

Cosmetic changes:
- Reword `NaN` and `NAN` as plain "NaN", unless they refer to the specific `const NAN`.
- Reword "a number" to `self` in function docstrings to clarify.
- Remove "Returns NAN if the number is NAN" from `abs`, as this is told to be the default behavior in the top explanation.
2022-05-09 18:45:35 +02:00
Mara Bos 4f212f08cf Use Rust 2021 prelude in std itself. 2022-05-09 11:12:32 +02:00
bors 8a2fe75d0e Auto merge of #95960 - jhpratt:remove-rustc_deprecated, r=compiler-errors
Remove `#[rustc_deprecated]`

This removes `#[rustc_deprecated]` and introduces diagnostics to help users to the right direction (that being `#[deprecated]`). All uses of `#[rustc_deprecated]` have been converted. CI is expected to fail initially; this requires #95958, which includes converting `stdarch`.

I plan on following up in a short while (maybe a bootstrap cycle?) removing the diagnostics, as they're only intended to be short-term.
2022-05-09 04:47:30 +00:00