libunwind fix and cleanup
Fix:
1. "system-llvm-libunwind" now only skip build-script for linux target
2. workaround from https://github.com/rust-lang/rust/pull/65972 is not needed, upstream fix it in 68c50708d1 ( LLVM 11 )
3. remove code for MSCV and Apple in `compile()`, as they are not used
4. fix https://github.com/rust-lang/rust/issues/69222 , compile c files and cpp files in different config
5. fix conditional compilation for musl target.
6. fix that x86_64-fortanix-unknown-sgx don't link libunwind built in build-script into rlib
Add inline attr to CString::into_inner so it can optimize out NonNull checks
It seems that currently if you convert any of the standard library's container to a pointer and then to a NonNull pointer, all will optimize out the NULL check except `CString`(https://godbolt.org/z/YPKW9G5xn),
because for some reason `CString::into_inner` isn't inlined even though it's a private function that should compile into a simple `mov` instruction.
Adding a simple `#[inline]` attribute solves this, code example:
```rust
use std::ffi::CString;
use std::ptr::NonNull;
pub fn cstring_nonull(mut n: CString) -> NonNull<i8> {
NonNull::new(CString::into_raw(n)).unwrap()
}
```
assembly before:
```asm
__ZN3wat14cstring_nonull17h371c755bcad76294E:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset %rbp, -16
movq %rsp, %rbp
.cfi_def_cfa_register %rbp
callq __ZN3std3ffi5c_str7CString10into_inner17h28ece07b276e2878E
testq %rax, %rax
je LBB0_2
popq %rbp
retq
LBB0_2:
leaq l___unnamed_1(%rip), %rdi
leaq l___unnamed_2(%rip), %rdx
movl $43, %esi
callq __ZN4core9panicking5panic17h92a83fa9085a8f73E
.cfi_endproc
.section __TEXT,__const
l___unnamed_1:
.ascii "called `Option::unwrap()` on a `None` value"
l___unnamed_3:
.ascii "wat.rs"
.section __DATA,__const
.p2align 3
l___unnamed_2:
.quad l___unnamed_3
.asciz "\006\000\000\000\000\000\000\000\006\000\000\000(\000\000"
```
Assembly after:
```asm
__ZN3wat14cstring_nonull17h9645eb9341fb25d7E:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset %rbp, -16
movq %rsp, %rbp
.cfi_def_cfa_register %rbp
movq %rdi, %rax
popq %rbp
retq
.cfi_endproc
```
(Related discussion on zulip: https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/NonNull.20From.3CBox.3CT.3E.3E)
Remove Iterator #[rustc_on_unimplemented]s that no longer apply.
Now that `IntoIterator` is implemented for arrays, all the `rustc_on_unimplemented` for arrays of ranges (e.g. `for _ in [1..3] {}`) no longer apply, since they are now valid Rust.
Separated these from #85670, because we should discuss a potential new (clippy?) lint for these.
Until Rust 1.52, `for _ in [1..3] {}` produced:
```
error[E0277]: `[std::ops::Range<{integer}>; 1]` is not an iterator
--> src/main.rs:2:14
|
2 | for _ in [1..3] {}
| ^^^^^^ if you meant to iterate between two values, remove the square brackets
|
= help: the trait `std::iter::Iterator` is not implemented for `[std::ops::Range<{integer}>; 1]`
= note: `[start..end]` is an array of one `Range`; you might have meant to have a `Range` without the brackets: `start..end`
= note: required by `std::iter::IntoIterator::into_iter`
```
But in Rust 1.53 and later, it compiles fine. It iterates over the array by value, for one iteration with the element `1..3`.
This is probably a mistake, which is no longer caught. Should we have a lint for it? Should Clippy have a lint for it?
cc ```@estebank``` ```@flip1995```
cc https://github.com/rust-lang/rust/issues/84513
Update cc
Recent commits have improved `cc`'s finding of MSVC tools on Windows. In particular it should help to address these issues: #83043 and #43468
While stdlib implementations of the unchecked methods require unchecked
math, there is no reason to gate it behind this for external users. The
reasoning for a separate `step_trait_ext` feature is unclear, and as
such has been merged as well.
Add `TrustedRandomAccess` specialization for `Vec::extend()`
This should do roughly the same as the `TrustedLen` specialization but result in less IR by using `__iterator_get_unchecked`
instead of `Iterator::for_each`
Conflicting specializations are manually prioritized by grouping them under yet another helper trait.
Fix typo in core::array::IntoIter comment
Saw a small typo reading some internal comments and decided to just throw this up to fix it for future readers.
Remove num_as_ne_bytes feature
From the discussion in #76976, it is determined that eventual results of the safe transmute work as a more general mechanism will let these conversions happen in safe code without needing specialized methods.
Merging this PR closes#76976 and resolves#64464. Several T-libs members have raised their opinion that it doesn't pull its weight as a standalone method, and so we should not track it as a specific thing to add.
fix `matches!` and `assert_matches!` on edition 2021
Previously this code failed to compile on edition 2021. [(Playground)](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=53960f2f051f641777b9e458da747707)
```rust
fn main() {
matches!((), ());
}
```
```
Compiling playground v0.0.1 (/playground)
error: `$pattern:pat` may be followed by `|`, which is not allowed for `pat` fragments
|
= note: allowed there are: `=>`, `,`, `=`, `if` or `in`
error: aborting due to previous error
error: could not compile `playground`
To learn more, run the command again with --verbose.
```
Demote `ControlFlow::{from|into}_try` to `pub(crate)`
They have mediocre names and non-obvious semantics, so personally I don't think they're worth trying to stabilize, and thus might as well just be internal (they're used for convenience in iterator adapters), not something shown in the rustdocs.
I don't think anyone actually wanted to use them outside `core` -- they just got made public-but-unstable along with the whole type in https://github.com/rust-lang/rust/pull/76204 that promoted `LoopState` from an internal type to the exposed `ControlFlow` type.
cc https://github.com/rust-lang/rust/issues/75744, the tracking issue they mention.
cc https://github.com/rust-lang/rust/pull/85608, the PR where I'm proposing stabilizing the type.
Fix pointer provenance in <[T]>::copy_within
Previously the `self.as_mut_ptr()` invalidated the pointer created by the first `self.as_ptr()`. This also triggered miri when run with `-Zmiri-track-raw-pointers`
doc: clarify Mutex::try_lock, etc. errors
Clarify error returns from Mutex::try_lock, RwLock::try_read,
RwLock::try_write to make it more obvious that both poisoning
and the lock being already locked are possible errors.
Weak's type parameter may dangle on drop
Way back in 34076bc0c9, #\[may_dangle\] was added to Rc\<T\> and Arc\<T\>'s Drop impls. That appears to have been because a test added in #28929 used Arc and Rc with dangling references at drop time. However, Weak was not covered by that test, and therefore no #\[may_dangle\] was forced to be added at the time.
As far as dropping, Weak has *even less need* to interact with the T than Rc and Arc do. Roughly speaking #\[may_dangle\] describes generic parameters that the outer type's Drop impl does not interact with except by possibly dropping them; no other interaction (such as trait method calls on the generic type) is permissible. It's clear this applies to Rc's and Arc's drop impl, which sometimes drop T but otherwise do not interact with one. It applies *even more* to Weak. Dropping a Weak cannot ever cause T's drop impl to run. Either there are strong references still in existence, in which case better not drop the T. Or there are no strong references still in existence, in which case the T would already have been dropped previously by the drop of the last strong count.
Better English for documenting when to use unimplemented!()
I don't think "plan of using" is correct here. I considered "plan on using" but eventually decided "plan to use" is better.
Bump bootstrap compiler to beta 1.53.0
This PR bumps the bootstrap compiler to version 1.53.0 beta, as part of our usual release process (this was supposed to be Wednesday's step, but creating the beta release took longer than expected).
The PR also includes the "Bootstrap: skip rustdoc fingerprint for building docs" commit, see the reasoning [on Zulip](https://zulip-archive.rust-lang.org/241545trelease/88450153betabootstrap.html).
r? `@Mark-Simulacrum`
Extend `rustc_on_implemented` to improve more `?` error messages
`_Self` could match the generic definition; this adds that functionality for matching the generic definition of type parameters too.
Your advice welcome on the wording of all these messages, and which things belong in the message/label/note.
r? `@estebank`
fix pad_integral example
pad_integral's parameter `is_nonnegative - whether the original integer was either positive or zero`, but in example it checked as `self.nb > 0`, so it previously printed `-0` for `format!("{}", Foo::new(0)`, what is wrong.
Extremely outdated; not only are traits implemented on arrays of arbitrary length, those implementations are documented on the primitive type, not in this module.
Fix `vxworks`
Some PRs made the `vxworks` target not build anymore. This PR fixes that:
- #82973: copy `ExitStatusError` implementation from `unix`.
- #84716: no `libc::chroot` available on `vxworks`, so for now don't implement `os::unix::fs::chroot`.
Remove surplus prepend LinkedList fn
This nightly library feature provides a function on `LinkedList<T>` that is identical to `fn append` with a reversed order of arguments. Observe this diff against the `fn append` doctest:
```diff
+#![feature(linked_list_prepend)]
fn main() {
use std::collections::LinkedList;
let mut list1 = LinkedList::new();
list1.push_back('a');
let mut list2 = LinkedList::new();
list2.push_back('b');
list2.push_back('c');
- list1.append(&mut list2);
+ list2.prepend(&mut list1);
- let mut iter = list1.iter();
+ let mut iter = list2.iter();
assert_eq!(iter.next(), Some(&'a'));
assert_eq!(iter.next(), Some(&'b'));
assert_eq!(iter.next(), Some(&'c'));
assert!(iter.next().is_none());
- assert!(list2.is_empty());
+ assert!(list1.is_empty());
}
```
As this has received no obvious request to stabilize it, nor does it have a tracking issue, and was left on nightly and the consensus seems to have been to deprecate it in this pre-1.0 PR in 2014, https://github.com/rust-lang/rust/pull/20356, I propose simply removing it.
add an example to explain std::io::Read::read returning 0 in some cases
I have always found the explanation about `Read::read` returning 0 to indicate EOF but not indefinitely, so here's more info using Linux as example. I can also add example code if necessary
MSVC: Avoid using jmp stubs for dll function imports
Windows import libraries contain two symbols for every function: `__imp_FunctionName` and `FunctionName` (where `FunctionName` is the name of the function to be imported).
`__imp_FunctionName` contains the address of the imported function. This will be filled in by the Windows executable loader at runtime. `FunctionName` contains a jmp stub that simply jumps to the address given by `__imp_FunctionName`. E.g. it's a function that solely contains a single jmp instruction:
```asm
jmp __imp_FunctionName
```
When using an external DLL function in Rust, by default the linker will link to FunctionName, causing a bit of indirection at runtime. In Microsoft's C++ it's possible to instead tell it to insert calls to the address in `__imp_FunctionName` by using the `__declspec(dllimport)` attribute. In Rust it's possible to get effectively the same behaviour using the `#[link]` attribute on `extern` blocks.
----
The second commit also merges multiple `extern` blocks into one block. This is because otherwise Rust will currently create duplicate linker arguments for each block. In this case having duplicates shouldn't matter much other than the noise when displaying the linker command.
Windows implementation of feature `path_try_exists`
Draft of a Windows implementation of `try_exists` (#83186).
The first commit reorganizes the code so I would be interested to get some feedback on if this is a good idea or not. It moves the `Path::try_exists` function to `fs::exists`. leaving the former as a wrapper for the latter. This makes it easier to provide platform specific implementations and matches the `fs::metadata` function.
The other commit implements a Windows specific variant of `exists`. I'm still figuring out my approach so this is very much a first draft. Eventually this will need some more eyes from knowledgable Windows people.
Clarify error returns from Mutex::try_lock, RwLock::try_read,
RwLock::try_write to make it more obvious that both poisoning
and the lock being already locked are possible errors.
std: Don't inline TLS accessor on MinGW
This is causing [issues] on Cargo's own CI for MinGW and given the
original investigation there's no reason that MinGW should work when
MSVC doesn't, this this tweaks the MSVC exception to being a Windows exception.
[issues]: https://github.com/rust-lang/cargo/runs/2626676503?check_suite_focus=true#step:9:2453
Move `std::memchr` to `sys_common`
`std::memchr` is a thin abstraction over the different `memchr` implementations in `sys`, along with documentation and tests. The module is only used internally by `std`, nothing is exported externally. Code like this is exactly what the `sys_common` module is for, so this PR moves it there.
Update list of allowed aarch64 features
I recently added these features to std_detect for aarch64 linux, pending [review](https://github.com/rust-lang/stdarch/pull/1146).
I have commented any features not supported by LLVM 9, the current minimum version for Rust. Some (PAuth at least) were renamed between 9 & 12 and I've left them disabled. TME, however, is not in LLVM 9 but I've left it enabled.
See https://github.com/rust-lang/stdarch/issues/993
Rollup of 8 pull requests
Successful merges:
- #84717 (impl FromStr for proc_macro::Literal)
- #85169 (Add method-toggle to <details> for methods)
- #85287 (Expose `Concurrent` (private type in public i'face))
- #85315 (adding time complexity for partition_in_place iter method)
- #85439 (Add diagnostic item to `CStr`)
- #85464 (Fix UB in documented example for `ptr::swap`)
- #85470 (Fix invalid CSS rules for a:hover)
- #85472 (CTFE Machine: do not expose Allocation)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Introduce `sys_common::rt::rtprintpanic!` to replace `sys_common::util` functionality
This PR introduces a new macro `rtprintpanic!`, similar to `sys_common::util::dumb_print` and uses that macro to replace all `sys_common::util` functionality.
Avoid zero-length memcpy in formatting
This has two separate and somewhat orthogonal commits. The first change adjusts the ToString general impl for all types that implement Display; it no longer uses the full format machinery, rather directly falling onto a `std::fmt::Display::fmt` call. The second change directly adjusts the general core::fmt::write function which handles the production of format_args! to avoid zero-length push_str calls.
Both changes target the fact that push_str will still call memmove internally (or a similar function), as it doesn't know the length of the passed string. For zero-length strings in particular, this is quite expensive, and even for very short (several bytes long) strings, this is also expensive. Future work in this area may wish to have us fallback to write_char or similar, which may be cheaper on the (typically) short strings between the interpolated pieces in format_args!.
adding time complexity for partition_in_place iter method
I feel that one thing missing from rust docs compared to cpp references is existence of time complexity for all methods and functions. While it would be humongous task to include it for everything in single go, it is still doable if we as community keep on adding it in relevant places as and when we find them.
This PR adds the time complexity for partition_in_place method in iter.
Expose `Concurrent` (private type in public i'face)
#53410 introduced experimental support for custom test frameworks.
Such frameworks may wish to build upon `library/test` by calling into its publicly exposed API (which I entirely understand is wholly unstable). However, any that wish to call `test::run_test` cannot currently do so because `test::options::Concurrent` (the type of its `concurrent` parameter) is not publicly exposed.
impl FromStr for proc_macro::Literal
Note that unlike `impl FromStr for proc_macro::TokenStream`, this impl does not permit whitespace or comments. The input string must consist of nothing but your literal.
- `"1".parse::<Literal>()` ⟶ ok
- `"1.0".parse::<Literal>()` ⟶ ok
- `"'a'".parse::<Literal>()` ⟶ ok
- `"\"\n\"".parse::<Literal>()` ⟶ ok
- `"0 1".parse::<Literal>()` ⟶ LexError
- `" 0".parse::<Literal>()` ⟶ LexError
- `"0 ".parse::<Literal>()` ⟶ LexError
- `"/* comment */0".parse::<Literal>()` ⟶ LexError
- `"0/* comment */".parse::<Literal>()` ⟶ LexError
- `"0// comment".parse::<Literal>()` ⟶ LexError
---
## Use case
```rust
let hex_int: Literal = format!("0x{:x}", int).parse().unwrap();
```
The only way this is expressible in the current API is significantly worse.
```rust
let hex_int = match format!("0x{:x}", int)
.parse::<TokenStream>()
.unwrap()
.into_iter()
.next()
.unwrap()
{
TokenTree::Literal(literal) => literal,
_ => unreachable!(),
};
```
remove InPlaceIterable marker from Peekable due to unsoundness
The unsoundness is not in Peekable per se, it rather is due to the
interaction between Peekable being able to hold an extra item
and vec::IntoIter's clone implementation shortening the allocation.
An alternative solution would be to change IntoIter's clone implementation
to keep enough spare capacity available.
fixes#85322
std: Attempt again to inline thread-local-init across crates
Issue #25088 has been part of `thread_local!` for quite some time now.
Historical attempts have been made to add `#[inline]` to `__getit`
in #43931, #50252, and #59720, but these attempts ended up not landing
at the time due to segfaults on Windows.
In the interim though with `const`-initialized thread locals AFAIK this
is the only remaining bug which is why you might want to use
`#[thread_local]` over `thread_local!`. As a result I figured it was
time to resubmit this and see how it fares on CI and if I can help
debugging any issues that crop up.
Closes#25088
Override `clone_from` for some types
Override `clone_from` method of the `Clone` trait for:
- `cell::RefCell`
- `cmp::Reverse`
- `io::Cursor`
- `mem::ManuallyDrop`
This can bring performance improvements.
This also checks the contents and not only the capacity in case IntoIter's clone implementation is changed to add capacity at the end. Extra capacity at the beginning would be needed to make InPlaceIterable work.
Co-authored-by: Giacomo Stevanato <giaco.stevanato@gmail.com>
The unsoundness is not in Peekable per se, it rather is due to the
interaction between Peekable being able to hold an extra item
and vec::IntoIter's clone implementation shortening the allocation.
An alternative solution would be to change IntoIter's clone implementation
to keep enough spare capacity available.
Implement the new desugaring from `try_trait_v2`
~~Currently blocked on https://github.com/rust-lang/rust/issues/84782, which has a PR in https://github.com/rust-lang/rust/pull/84811~~ Rebased atop that fix.
`try_trait_v2` tracking issue: https://github.com/rust-lang/rust/issues/84277
Unfortunately this is already touching a ton of things, so if you have suggestions for good ways to split it up, I'd be happy to hear them. (The combination between the use in the library, the compiler changes, the corresponding diagnostic differences, even MIR tests mean that I don't really have a great plan for it other than trying to have decently-readable commits.
r? `@ghost`
~~(This probably shouldn't go in during the last week before the fork anyway.)~~ Fork happened.
Issue #25088 has been part of `thread_local!` for quite some time now.
Historical attempts have been made to add `#[inline]` to `__getit`
in #43931, #50252, and #59720, but these attempts ended up not landing
at the time due to segfaults on Windows.
In the interim though with `const`-initialized thread locals AFAIK this
is the only remaining bug which is why you might want to use
`#[thread_local]` over `thread_local!`. As a result I figured it was
time to resubmit this and see how it fares on CI and if I can help
debugging any issues that crop up.
Closes#25088
Implement more Iterator methods on core::iter::Repeat
`core::iter::Repeat` always returns the same element, which means we can
do better than implementing most `Iterator` methods in terms of
`Iterator::next`.
Fixes#81292.
#81292 raises the question of whether these changes violate the contract of `core::iter::Repeat`, but as far as I can tell `core::iter::repeat` doesn't make any guarantees around how it calls `Clone::clone`.
Provide ExitStatusError
Closes#73125
In MR #81452 "Add #[must_use] to [...] process::ExitStatus" we concluded that the existing arrangements in are too awkward so adding that `#[must_use]` is blocked on improving the ergonomics.
I wrote a mini-RFC-style discusion of the approach in https://github.com/rust-lang/rust/issues/73125#issuecomment-771092741
# Stabilization report
## Summary
This stabilizes using macro expansion in key-value attributes, like so:
```rust
#[doc = include_str!("my_doc.md")]
struct S;
#[path = concat!(env!("OUT_DIR"), "/generated.rs")]
mod m;
```
See the changes to the reference for details on what macros are allowed;
see Petrochenkov's excellent blog post [on internals](https://internals.rust-lang.org/t/macro-expansion-points-in-attributes/11455)
for alternatives that were considered and rejected ("why accept no more
and no less?")
This has been available on nightly since 1.50 with no major issues.
## Notes
### Accepted syntax
The parser accepts arbitrary Rust expressions in this position, but any expression other than a macro invocation will ultimately lead to an error because it is not expected by the built-in expression forms (e.g., `#[doc]`). Note that decorators and the like may be able to observe other expression forms.
### Expansion ordering
Expansion of macro expressions in "inert" attributes occurs after decorators have executed, analogously to macro expressions appearing in the function body or other parts of decorator input.
There is currently no way for decorators to accept macros in key-value position if macro expansion must be performed before the decorator executes (if the macro can simply be copied into the output for later expansion, that can work).
## Test cases
- https://github.com/rust-lang/rust/blob/master/src/test/ui/attributes/key-value-expansion-on-mac.rs
- https://github.com/rust-lang/rust/blob/master/src/test/rustdoc/external-doc.rs
The feature has also been dogfooded extensively in the compiler and
standard library:
- https://github.com/rust-lang/rust/pull/83329
- https://github.com/rust-lang/rust/pull/83230
- https://github.com/rust-lang/rust/pull/82641
- https://github.com/rust-lang/rust/pull/80534
## Implementation history
- Initial proposal: https://github.com/rust-lang/rust/issues/55414#issuecomment-554005412
- Experiment to see how much code it would break: https://github.com/rust-lang/rust/pull/67121
- Preliminary work to restrict expansion that would conflict with this
feature: https://github.com/rust-lang/rust/pull/77271
- Initial implementation: https://github.com/rust-lang/rust/pull/78837
- Fix for an ICE: https://github.com/rust-lang/rust/pull/80563
## Unresolved Questions
~~https://github.com/rust-lang/rust/pull/83366#issuecomment-805180738 listed some concerns, but they have been resolved as of this final report.~~
## Additional Information
There are two workarounds that have a similar effect for `#[doc]`
attributes on nightly. One is to emulate this behavior by using a limited version of this feature that was stabilized for historical reasons:
```rust
macro_rules! forward_inner_docs {
($e:expr => $i:item) => {
#[doc = $e]
$i
};
}
forward_inner_docs!(include_str!("lib.rs") => struct S {});
```
This also works for other attributes (like `#[path = concat!(...)]`).
The other is to use `doc(include)`:
```rust
#![feature(external_doc)]
#[doc(include = "lib.rs")]
struct S {}
```
The first works, but is non-trivial for people to discover, and
difficult to read and maintain. The second is a strange special-case for
a particular use of the macro. This generalizes it to work for any use
case, not just including files.
I plan to remove `doc(include)` when this is stabilized. The
`forward_inner_docs` workaround will still compile without warnings, but
I expect it to be used less once it's no longer necessary.
Simplify `cfg(any(unix, target_os="redox"))` in example to just `cfg(unix)`
Update example for `OsString` that handled `redox` seperately from `unix`: Redox has been completely integrated under `target_family="unix"`, so `cfg(unix)` implies `target_os="redox"`
35dbef2350/compiler/rustc_target/src/spec/redox_base.rs (L26)
Expand WASI abbreviation in docs
I was pretty sure this was related to something for WebAssembly but wasn't 100% sure so I checked but even on these top-level docs I couldn't find the abbreviation expanded. I'm normally used to Rust docs being detailed and explanatory and writing abbreviations like this out in full at least once so I thought it was worth the change. Feel free to close this if it's too much.
This avoids a zero-length write_str call, which boils down to a zero-length
memmove and ultimately costs quite a few instructions on some workloads.
This is approximately a 0.33% instruction count win on diesel-check.
Do not allocate or unwind after fork
### Objective scenarios
* Make (simple) panics safe in `Command::pre_exec_hook`, including most `panic!` calls, `Option::unwrap`, and array bounds check failures.
* Make it possible to `libc::fork` and then safely panic in the child (needed for the above, but this requirement means exposing the new raw hook API which the `Command` implementation needs).
* In singlethreaded programs, where panic in `pre_exec_hook` is already memory-safe, prevent the double-unwinding malfunction #79740.
I think we want to make panic after fork safe even though the post-fork child environment is only experienced by users of `unsafe`, beause the subset of Rust in which any panic is UB is really far too hazardous and unnatural.
#### Approach
* Provide a way for a program to, at runtime, switch to having panics abort. This makes it possible to panic without making *any* heap allocations, which is needed because on some platforms malloc is UB in a child forked from a multithreaded program (see https://github.com/rust-lang/rust/pull/80263#issuecomment-774272370, and maybe also the SuS [spec](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html)).
* Make that change in the child spawned by `Command`.
* Document the rules comprehensively enough that a programmer has a fighting chance of writing correct code.
* Test that this all works as expected (and in particular, that there aren't any heap allocations we missed)
Fixes#79740
#### Rejected (or previously attempted) approaches
* Change the panic machinery to be able to unwind without allocating, at least when the payload and message are both `'static`. This seems like it would be even more subtle. Also that is a potentially-hot path which I don't want to mess with.
* Change the existing panic hook mechanism to not convert the message to a `String` before calling the hook. This would be a surprising change for existing code and would not be detected by the type system.
* Provide a `raw_panic_hook` function to intercept panics in a way that doesn't allocate. (That was an earlier version of this MR.)
### History
This MR could be considered a v2 of #80263. Thanks to everyone who commented there. In particular, thanks to `@m-ou-se,` `@Mark-Simulacrum` and `@hyd-dev.` (Tagging you since I think you might be interested in this new MR.) Compared to #80263, this MR has very substantial changes and additions.
Additionally, I have recently (2021-04-20) completely revised this series following very helpful comments from `@m-ou-se.`
r? `@m-ou-se`
`core::iter::Repeat` always returns the same element, which means we can
do better than implementing most `Iterator` methods in terms of
`Iterator::next`.
Fixes#81292.
Some platforma (eg ARM64) apparently generate SIGTRAP for panic abort!
See eg
https://github.com/rust-lang/rust/pull/81858#issuecomment-840702765
This is probably a bug, but we don't want to entangle this MR with it.
When it's fixed, this commit should be reverted.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
add BITS associated constant to core::num::Wrapping
This keeps `Wrapping` synchronized with the primitives it wraps as for the #32463 `wrapping_int_impl` feature.
Remove rustc_args_required_const attribute
Now that stdarch no longer needs it (thanks `@Amanieu!),` we can kill the `rustc_args_required_const` attribute. This means that lifetime extension of references to temporaries is the only remaining job that promotion is performing. :-)
r? `@oli-obk`
Fixes https://github.com/rust-lang/rust/issues/69493
#[inline(always)] on basic pointer methods
Retryng #85201 with only inlining pointer methods. The goal is to make pointers behave just like pointers in O0, mainly to reduce overhead in debug builds.
cc `@scottmcm`
Add auto traits and clone trait migrations for RFC2229
This PR
- renames the existent RFC2229 migration `disjoint_capture_drop_reorder` to `disjoint_capture_migration`
- add additional migrations for auto traits and clone trait
Closesrust-lang/project-rfc-2229#29Closesrust-lang/project-rfc-2229#28
r? `@nikomatsakis`
It is unergnomic to have to say things like
bad.into_status().signal()
Implementing `ExitStatusExt` for `ExitStatusError` fixes this.
Unfortunately it does mean making a previously-infallible method
capable of panicing, although of course the existing impl remains
infallible.
The alternative would be a whole new `ExitStatusErrorExt` trait.
`<ExitStatus as ExitStatusExt>::into_raw()` is not particularly
ergonomic to call because of the often-required type annotation.
See for example the code in the test case in
library/std/src/sys/unix/process/process_unix/tests.rs
Perhaps we should provide equivalent free functions for `ExitStatus`
and `ExitStatusExt` in std::os::unix::process and maybe deprecate this
trait method. But I think that is for the future.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Closes#73125
This is in pursuance of
Issue #73127 Consider adding #[must_use] to std::process::ExitStatus
In
MR #81452 Add #[must_use] to [...] process::ExitStatus
we concluded that the existing arrangements in are too awkward
so adding that #[must_use] is blocked on improving the ergonomics.
I wrote a mini-RFC-style discusion of the approach in
https://github.com/rust-lang/rust/issues/73125#issuecomment-771092741
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
This PR implements span quoting, allowing proc-macros to produce spans
pointing *into their own crate*. This is used by the unstable
`proc_macro::quote!` macro, allowing us to get error messages like this:
```
error[E0412]: cannot find type `MissingType` in this scope
--> $DIR/auxiliary/span-from-proc-macro.rs:37:20
|
LL | pub fn error_from_attribute(_args: TokenStream, _input: TokenStream) -> TokenStream {
| ----------------------------------------------------------------------------------- in this expansion of procedural macro `#[error_from_attribute]`
...
LL | field: MissingType
| ^^^^^^^^^^^ not found in this scope
|
::: $DIR/span-from-proc-macro.rs:8:1
|
LL | #[error_from_attribute]
| ----------------------- in this macro invocation
```
Here, `MissingType` occurs inside the implementation of the proc-macro
`#[error_from_attribute]`. Previosuly, this would always result in a
span pointing at `#[error_from_attribute]`
This will make many proc-macro-related error message much more useful -
when a proc-macro generates code containing an error, users will get an
error message pointing directly at that code (within the macro
definition), instead of always getting a span pointing at the macro
invocation site.
This is implemented as follows:
* When a proc-macro crate is being *compiled*, it causes the `quote!`
macro to get run. This saves all of the sapns in the input to `quote!`
into the metadata of *the proc-macro-crate* (which we are currently
compiling). The `quote!` macro then expands to a call to
`proc_macro::Span::recover_proc_macro_span(id)`, where `id` is an
opaque identifier for the span in the crate metadata.
* When the same proc-macro crate is *run* (e.g. it is loaded from disk
and invoked by some consumer crate), the call to
`proc_macro::Span::recover_proc_macro_span` causes us to load the span
from the proc-macro crate's metadata. The proc-macro then produces a
`TokenStream` containing a `Span` pointing into the proc-macro crate
itself.
The recursive nature of 'quote!' can be difficult to understand at
first. The file `src/test/ui/proc-macro/quote-debug.stdout` shows
the output of the `quote!` macro, which should make this eaier to
understand.
This PR also supports custom quoting spans in custom quote macros (e.g.
the `quote` crate). All span quoting goes through the
`proc_macro::quote_span` method, which can be called by a custom quote
macro to perform span quoting. An example of this usage is provided in
`src/test/ui/proc-macro/auxiliary/custom-quote.rs`
Custom quoting currently has a few limitations:
In order to quote a span, we need to generate a call to
`proc_macro::Span::recover_proc_macro_span`. However, proc-macros
support renaming the `proc_macro` crate, so we can't simply hardcode
this path. Previously, the `quote_span` method used the path
`crate::Span` - however, this only works when it is called by the
builtin `quote!` macro in the same crate. To support being called from
arbitrary crates, we need access to the name of the `proc_macro` crate
to generate a path. This PR adds an additional argument to `quote_span`
to specify the name of the `proc_macro` crate. Howver, this feels kind
of hacky, and we may want to change this before stabilizing anything
quote-related.
Additionally, using `quote_span` currently requires enabling the
`proc_macro_internals` feature. The builtin `quote!` macro
has an `#[allow_internal_unstable]` attribute, but this won't work for
custom quote implementations. This will likely require some additional
tricks to apply `allow_internal_unstable` to the span of
`proc_macro::Span::recover_proc_macro_span`.
Change param name (k to key and v to value) in std::env module
1. When I was reading code the ide displayed `k` and `v`, so I
thought it would be better to show key and value?
2. I noticed var method already uses `key` instead of `k` so it
is more consistent to use `key` instead of `k`?
Thanks
BTree: no longer copy keys and values before dropping them
When dropping BTreeMap or BTreeSet instances, keys-value pairs are up to now each copied and then dropped, at least according to source code. This is because the code for dropping and for iterators is shared.
This PR postpones the treatment of doomed key-value pairs from the intermediate functions `deallocating_next`(`_back`) to the last minute, so the we can drop the keys and values in place. According to the library/alloc benchmarks, this does make a difference, (and a positive difference with an `#[inline]` on `drop_key_val`). It does not change anything for #81444 though.
r? `@Mark-Simulacrum`
Emit errors/warns on some wrong uses of rustdoc attributes
This PR adds a few diagnostics:
- error if conflicting `#[doc(inline)]`/`#[doc(no_inline)]` are found
- introduce the `invalid_doc_attributes` lint (warn-by-default) which triggers:
- if a crate-level attribute is used on a non-`crate` item
- if `#[doc(inline)]`/`#[doc(no_inline)]` is used on a non-`use` item
The code could probably be improved but I wanted to get feedback first. Also, some of those changes could be considered breaking changes, so I don't know what the procedure would be? ~~And finally, for the warnings, they are currently hard warnings, maybe it would be better to introduce a lint?~~ (EDIT: introduced the `invalid_doc_attributes` lint)
Closes#80275.
r? `@jyn514`
Provide io::Seek::rewind
Using `Seek::seek` is slightly clumsy because of the need to write (or import) `std::io::SeekFrom` to get at `SeekStart`. C already has `rewind` (although with broken error handling); we should have it too.
I'm motivated to do this because I've just found myself copy-pasting my 5-line extension trait between projects.
That the example ends up using `OpenOptions` makes this look like a niche use case, but it is very common to rewind temporary files. `tempfile` isn't available for use in this example or it would have looked shorter and more natural.
If this gets a positive reception I will open a tracking issue and update the feature gate.
Make unchecked_{add,sub,mul} inherent methods unstably const
The intrinsics are marked as being stably const (even though they're not stable by nature of being intrinsics), but the currently-unstable inherent versions are not marked as const. This fixes this inconsistency. Split out of #85017,
r? `@oli-obk`
Bump stdarch submodule
Major changes:
- More AVX-512 intrinsics.
- More ARM & AArch64 NEON intrinsics.
- Updated unstable WASM intrinsics to latest draft standards.
- Intrinsics that previously used `#[rustc_args_required_const]` now use const generics. See #83167 for more details.
- `std_detect` is now a separate crate instead of a submodule of `std`.
fork fails there. The failure message is confusing: so c.status()
returns an Err, the closure panics, and the test thinks the panic was
propagated from inside the child.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Rearrange SGX split module files
In #75979 several inlined modules were split out into multiple files.
This PR keeps the multiple files but moves a few things around to
organize things in a coherent way.
Cleanup of `wasm`
Some more cleanup of `sys`, this time `wasm`
- Reuse `unsupported::args` (functionally equivalent implementation, just an empty iterator).
- Split out `atomics` implementation of `wasm::thread`, the non-`atomics` implementation is reused from `unsupported`.
- Move all of the `atomics` code to a separate directory `wasm/atomics`.
````@rustbot```` label: +T-libs-impl
r? ````@m-ou-se````
In #75979 several inlined modules were split out into multiple files.
This PR keeps the multiple files but moves a few things around to
organize things in a coherent way.
This tests that we can indeed safely panic after fork, both
a raw libc::fork and in a Command pre_exec hook.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
This is safe (does not involve heap allocation) but we don't yet have
a test to ensure that stays true. That will come in a moment.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Unwinding after fork() in the child is UB on some platforms, because
on those (including musl) malloc can be UB in the child of a
multithreaded program, and unwinding must box for the payload.
Even if it's safe, unwinding past fork() in the child causes whatever
traps the unwind to return twice. This is very strange and clearly
not desirable. With the default behaviour of the thread library, this
can even result in a panic in the child being transformed into zero
exit status (ie, success) as seen in the parent!
Fixes#79740.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
We must change the atomic read on panic entry to `Acquire`, to pick up
a possible an `always_panic` on another thread.
We add `count` to the names of panic_count::get and ::is_zaero,
because now there is another reason why panic ought to maybe abort.
Renaming these ensures that we have checked every call site to ensure
that they don't need further adjustment.
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Disallows `#![feature(no_coverage)]` on stable and beta (using standard crate-level gating)
Fixes: #84836
Removes the function-level feature gating solution originally implemented, and solves the same problem using `allow_internal_unstable`, so normal crate-level feature gating mechanism can still be used (which disallows the feature on stable and beta).
I tested this, building the compiler with and without `CFG_DISABLE_UNSTABLE_FEATURES=1`
With unstable features disabled, I get the expected result as shown here:
```shell
$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc src/test/run-make-fulldeps/coverage/no_cov_crate.rs
error[E0554]: `#![feature]` may not be used on the dev release channel
--> src/test/run-make-fulldeps/coverage/no_cov_crate.rs:2:1
|
2 | #![feature(no_coverage)]
| ^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0554`.
```
r? ````@Mark-Simulacrum````
cc: ````@tmandry```` ````@wesleywiser````
Allow using `core::` in intra-doc links within core itself
I came up with this idea ages ago, but rustdoc used to ICE on it. Now it doesn't.
Helps with https://github.com/rust-lang/rust/issues/73445. Doesn't fix it completely since `extern crate self as std;` in std still gives strange errors.
Stablize {HashMap,BTreeMap}::into_{keys,values}
I would propose to stabilize `{HashMap,BTreeMap}::into_{keys,values}`( aka. `map_into_keys_values`).
Closes#75294.
For certain sorts of systems, programming, it's deemed essential that
all allocation failures be explicitly handled where they occur. For
example, see Linus Torvald's opinion in [1]. Merely not calling global
panic handlers, or always `try_reserving` first (for vectors), is not
deemed good enough, because the mere presence of the global OOM handlers
is burdens static analysis.
One option for these projects to use rust would just be to skip `alloc`,
rolling their own allocation abstractions. But this would, in my
opinion be a real shame. `alloc` has a few `try_*` methods already, and
we could easily have more. Features like custom allocator support also
demonstrate and existing to support diverse use-cases with the same
abstractions.
A natural way to add such a feature flag would a Cargo feature, but
there are currently uncertainties around how std library crate's Cargo
features may or not be stable, so to avoid any risk of stabilizing by
mistake we are going with a more low-level "raw cfg" token, which
cannot be interacted with via Cargo alone.
Note also that since there is no notion of "default cfg tokens" outside
of Cargo features, we have to invert the condition from
`global_oom_handling` to to `not(no_global_oom_handling)`. This breaks
the monotonicity that would be important for a Cargo feature (i.e.
turning on more features should never break compatibility), but it
doesn't matter for raw cfg tokens which are not intended to be
"constraint solved" by Cargo or anything else.
To support this use-case we create a new feature, "global-oom-handling",
on by default, and put the global OOM handler infra and everything else
it that depends on it behind it. By default, nothing is changed, but
users concerned about global handling can make sure it is disabled, and
be confident that all OOM handling is local and explicit.
For this first iteration, non-flat collections are outright disabled.
`Vec` and `String` don't yet have `try_*` allocation methods, but are
kept anyways since they can be oom-safely created "from parts", and we
hope to add those `try_` methods in the future.
[1]: https://lore.kernel.org/lkml/CAHk-=wh_sNLoz84AUUzuqXEsYH35u=8HV3vK-jbRbJ_B-JjGrg@mail.gmail.com/
Rollup of 11 pull requests
Successful merges:
- #83553 (Update `ptr` docs with regards to `ptr::addr_of!`)
- #84183 (Update RELEASES.md for 1.52.0)
- #84709 (Add doc alias for `chdir` to `std::env::set_current_dir`)
- #84803 (Reduce duplication in `impl_dep_tracking_hash` macros)
- #84808 (Account for unsatisfied bounds in E0599)
- #84843 (use else if in std library )
- #84865 (rustbuild: Pass a `threads` flag that works to windows-gnu lld)
- #84878 (Clarify documentation for `[T]::contains`)
- #84882 (platform-support: Center the contents of the `std` and `host` columns)
- #84903 (Remove `rustc_middle::mir::interpret::CheckInAllocMsg::NullPointerTest`)
- #84913 (Do not ICE on invalid const param)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Clarify documentation for `[T]::contains`
Change the documentation to correctly characterize when the suggested alternative to `contains` applies, and correctly explain why it works.
Fixes#84877
Add doc alias for `chdir` to `std::env::set_current_dir`
Searching for `chdir` in the Rust documentation produces no useful
results.
I wrote some code recently that called `libc::chdir` and manually
handled errors, because I didn't realize that the safe
`std::env::set_current_dir` existed. I searched for `chdir` and
`change_dir` and `change_directory` (the latter two based on the
precedent of unabbreviating set by `create_dir`), and I also read
through `std::fs` expecting to potentially find it there. Given that
none of those led to `std::env::set_current_dir`, I think that provides
sufficient justification to add this specific alias.
Update `ptr` docs with regards to `ptr::addr_of!`
This updates the documentation since `ptr::addr_of!` and `ptr::addr_of_mut!` are now stable. One might remove the distinction between the sections `# On packed structs` and `# Examples`, as the old section on packed structs was primarily to prevent users of doing undefined behavior, which is not necessary anymore.
Technically there is now wrong/outdated documentation on stable, but I don't think this is worth a point release 😉Fixes#83509.
``````````@rustbot`````````` modify labels: T-doc
using allow_internal_unstable (as recommended)
Fixes: #84836
```shell
$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc src/test/run-make-fulldeps/coverage/no_cov_crate.rs
error[E0554]: `#![feature]` may not be used on the dev release channel
--> src/test/run-make-fulldeps/coverage/no_cov_crate.rs:2:1
|
2 | #![feature(no_coverage)]
| ^^^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0554`.
```
Move all `sys::ext` modules to `os`
This PR moves all `sys::ext` modules to `os`, centralizing the location of all `os` code and simplifying the dependencies between `os` and `sys`.
Because this also removes all uses `cfg_if!` on publicly exported items, where after #81969 there were still a few left, this should properly work around https://github.com/rust-analyzer/rust-analyzer/issues/6038.
`@rustbot` label: +T-libs-impl
This updates the documentation since `ptr::addr_of!` and
`ptr::addr_of_mut!` are now stable. One might remove the distinction
between the sections `# On packed structs` and `# Examples`, as the old
section on packed structs was primarily to prevent users of doing unde-
fined behavior, which is not necessary anymore.
There is also a new section in "how to obtain a pointer", which referen-
ces the `ptr::addr_of!` macros.
This commit contains squashed commits from code review.
Co-authored-by: Joshua Nelson <joshua@yottadb.com>
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Co-authored-by: Soveu <marx.tomasz@gmail.com>
Co-authored-by: Ralf Jung <post@ralfj.de>
Replace 'NULL' with 'null'
This replaces occurrences of "NULL" with "null" in docs, comments, and compiler error/lint messages. This is for the sake of consistency, as the lowercase "null" is already the dominant form in Rust. The all-caps NULL looks like the C macro (or SQL keyword), which seems out of place in a Rust context, given that NULL does not exist in the Rust language or standard library (instead having [`ptr::null()`](https://doc.rust-lang.org/stable/std/ptr/fn.null.html)).
Rollup of 6 pull requests
Successful merges:
- #84072 (Allow setting `target_family` to multiple values, and implement `target_family="wasm"`)
- #84744 (Add ErrorKind::OutOfMemory)
- #84784 (Add help message to suggest const for unused type param)
- #84811 (RustDoc: Fix bounds linking trait.Foo instead of traitalias.Foo)
- #84818 (suggestion for unit enum variant when matched with a patern)
- #84832 (Do not print visibility in external traits)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
i8 and u8::to_string() specialisation (far less asm).
Take 2. Around 1/6th of the assembly to without specialisation.
https://godbolt.org/z/bzz8Mq
(partially fixes#73533 )