Commit graph

4602 commits

Author SHA1 Message Date
Dominik Stolz 2a4d012103 Add dummy FileDesc struct for doc target 2021-08-01 09:45:00 +02:00
Dominik Stolz c3321d3eb3 Add tracking issue and link to man-page 2021-07-21 10:49:11 +02:00
Dominik Stolz 619fd96868 Add PidFd type and seal traits
Improve docs

Split do_fork into two

Make do_fork unsafe

Add target attribute to create_pidfd field in Command

Add method to get create_pidfd value
2021-07-21 10:49:11 +02:00
Josh Triplett ef03de2e6a Typo fix
Co-authored-by: bjorn3 <bjorn3@users.noreply.github.com>
2021-07-21 10:49:11 +02:00
Aaron Hill 694be09b7b Add Linux-specific pidfd process extensions
Background:

Over the last year, pidfd support was added to the Linux kernel. This
allows interacting with other processes. In particular, this allows
waiting on a child process with a timeout in a race-free way, bypassing
all of the awful signal-handler tricks that are usually required.

Pidfds can be obtained for a child process (as well as any other
process) via the `pidfd_open` syscall. Unfortunately, this requires
several conditions to hold in order to be race-free (i.e. the pid is not
reused).
Per `man pidfd_open`:

```
· the disposition of SIGCHLD has not been explicitly set to SIG_IGN
 (see sigaction(2));

· the SA_NOCLDWAIT flag was not specified while establishing a han‐
 dler for SIGCHLD or while setting the disposition of that signal to
 SIG_DFL (see sigaction(2)); and

· the zombie process was not reaped elsewhere in the program (e.g.,
 either by an asynchronously executed signal handler or by wait(2)
 or similar in another thread).

If any of these conditions does not hold, then the child process
(along with a PID file descriptor that refers to it) should instead
be created using clone(2) with the CLONE_PIDFD flag.
```

Sadly, these conditions are impossible to guarantee once any libraries
are used. For example, C code runnng in a different thread could call
`wait()`, which is impossible to detect from Rust code trying to open a
pidfd.

While pid reuse issues should (hopefully) be rare in practice, we can do
better. By passing the `CLONE_PIDFD` flag to `clone()` or `clone3()`, we
can obtain a pidfd for the child process in a guaranteed race-free
manner.

This PR:

This PR adds Linux-specific process extension methods to allow obtaining
pidfds for processes spawned via the standard `Command` API. Other than
being made available to user code, the standard library does not make
use of these pidfds in any way. In particular, the implementation of
`Child::wait` is completely unchanged.

Two Linux-specific helper methods are added: `CommandExt::create_pidfd`
and `ChildExt::pidfd`. These methods are intended to serve as a building
block for libraries to build higher-level abstractions - in particular,
waiting on a process with a timeout.

I've included a basic test, which verifies that pidfds are created iff
the `create_pidfd` method is used. This test is somewhat special - it
should always succeed on systems with the `clone3` system call
available, and always fail on systems without `clone3` available. I'm
not sure how to best ensure this programatically.

This PR relies on the newer `clone3` system call to pass the `CLONE_FD`,
rather than the older `clone` system call. `clone3` was added to Linux
in the same release as pidfds, so this shouldn't unnecessarily limit the
kernel versions that this code supports.

Unresolved questions:
* What should the name of the feature gate be for these newly added
  methods?
* Should the `pidfd` method distinguish between an error occurring
  and `create_pidfd` not being called?
2021-07-21 10:49:11 +02:00
bors dfd7b8d03f Auto merge of #85953 - inquisitivecrystal:weak-linkat-in-fs-hardlink, r=joshtriplett
Fix linker error

Currently, `fs::hard_link` determines whether platforms have `linkat` based on the OS, and uses `link` if they don't. However, this heuristic does not work well if a platform provides `linkat` on newer versions but not on older ones. On old MacOS, this currently causes a linking error.

This commit fixes `fs::hard_link` by telling it to use `weak!` on macOS. This means that, on  that operating system, we now check for `linkat` at runtime and use `link` if it is not available.

Fixes #80804.

`@rustbot` label T-libs-impl
2021-07-10 21:42:40 +00:00
Aris Merchant 5999a5fbdc Make tests pass on old macos
On old macos systems, `fs::hard_link()` will follow symlinks.
This changes the test `symlink_hard_link` to exit early on
these systems, so that tests can pass.
2021-07-10 12:59:25 -07:00
Aris Merchant fd0cb0cdc2 Change weak! and linkat! to macros 2.0
`weak!` is needed in a test in another module. With macros
1.0, importing `weak!` would require reordering module
declarations in `std/src/lib.rs`, which is a bit too
evil.
2021-07-10 12:55:09 -07:00
Yuki Okushi 0ca5fc2e33
Rollup merge of #87011 - RalfJung:thread-id-supply-shortage, r=nagisa
avoid reentrant lock acquire when ThreadIds run out

Discovered by `@bjorn3`
2021-07-11 01:15:40 +09:00
Ralf Jung dbc2b55baf rename variable 2021-07-10 14:14:09 +02:00
Ralf Jung 2750d3ac6a avoid reentrant lock acquire when ThreadIds run out 2021-07-10 11:54:38 +02:00
Aris Merchant 5022c0638d Update docs for fs::hard_link 2021-07-09 23:24:36 -07:00
Aris Merchant dc38d87505 Fix linker error
This makes `fs::hard_link` use weak! for some platforms,
thereby preventing a linker error.
2021-07-09 23:24:36 -07:00
Kornel bc67f6bc95 Debug formatting of raw_arg() 2021-07-09 14:24:34 +01:00
Kornel 8f9d0f12eb Use AsRef in CommandExt for raw_arg 2021-07-09 14:09:48 +01:00
Kornel d868da7796 Unescaped command-line arguments for Windows
Fixes #29494
2021-07-09 14:09:48 +01:00
Kornel fcd5cecdcf Test escaping of trialing slashes in Windows command-line args 2021-07-09 14:09:48 +01:00
bors ee86f96ba1 Auto merge of #85828 - scottmcm:raw-eq, r=oli-obk
Stop generating `alloca`s & `memcmp` for simple short array equality

Example:
```rust
pub fn demo(x: [u16; 6], y: [u16; 6]) -> bool { x == y }
```

Before:
```llvm
define zeroext i1 `@_ZN10playground4demo17h48537f7eac23948fE(i96` %0, i96 %1) unnamed_addr #0 {
start:
  %y = alloca [6 x i16], align 8
  %x = alloca [6 x i16], align 8
  %.0..sroa_cast = bitcast [6 x i16]* %x to i96*
  store i96 %0, i96* %.0..sroa_cast, align 8
  %.0..sroa_cast3 = bitcast [6 x i16]* %y to i96*
  store i96 %1, i96* %.0..sroa_cast3, align 8
  %_11.i.i.i = bitcast [6 x i16]* %x to i8*
  %_14.i.i.i = bitcast [6 x i16]* %y to i8*
  %bcmp.i.i.i = call i32 `@bcmp(i8*` nonnull dereferenceable(12) %_11.i.i.i, i8* nonnull dereferenceable(12) %_14.i.i.i, i64 12) #2, !alias.scope !2
  %2 = icmp eq i32 %bcmp.i.i.i, 0
  ret i1 %2
}
```
```x86
playground::demo: # `@playground::demo`
	sub	rsp, 32
	mov	qword ptr [rsp], rdi
	mov	dword ptr [rsp + 8], esi
	mov	qword ptr [rsp + 16], rdx
	mov	dword ptr [rsp + 24], ecx
	xor	rdi, rdx
	xor	esi, ecx
	or	rsi, rdi
	sete	al
	add	rsp, 32
	ret
```

After:
```llvm
define zeroext i1 `@_ZN4mini4demo17h7a8994aaa314c981E(i96` %0, i96 %1) unnamed_addr #0 {
start:
  %2 = icmp eq i96 %0, %1
  ret i1 %2
}
```
```x86
_ZN4mini4demo17h7a8994aaa314c981E:
	xor	rcx, r8
	xor	edx, r9d
	or	rdx, rcx
	sete	al
	ret
```
2021-07-09 09:16:27 +00:00
bors 95fb131521 Auto merge of #86904 - m-ou-se:prelude-collision-check-trait, r=nikomatsakis
Check FromIterator trait impl in prelude collision check.

Fixes #86902.
2021-07-09 06:35:42 +00:00
Scott McMurray b63b2f1e42 PR feedback
- Add `:Sized` assertion in interpreter impl
- Use `Scalar::from_bool` instead of `ScalarInt: From<bool>`
- Remove unneeded comparison in intrinsic typeck
- Make this UB to call with undef, not just return undef in that case
2021-07-08 14:55:57 -07:00
Scott McMurray 2456495a26 Stop generating allocas+memcmp for simple array equality 2021-07-08 14:55:54 -07:00
Scott McMurray d05eafae2f Move the PartialEq and Eq impls for arrays to a separate file 2021-07-08 14:53:37 -07:00
bors 8b87e85394 Auto merge of #86930 - tspiteri:int_log10, r=kennytm
special case for integer log10

Now that #80918 has been merged, this PR provides a faster version of `log10`.

The PR also adds some tests for values close to all powers of 10.
2021-07-08 20:19:00 +00:00
bors aa65b08b1d Auto merge of #86982 - GuillaumeGomez:rollup-7sbye3c, r=GuillaumeGomez
Rollup of 8 pull requests

Successful merges:

 - #84961 (Rework SESSION_GLOBALS API)
 - #86726 (Use diagnostic items instead of lang items for rfc2229 migrations)
 - #86789 (Update BTreeSet::drain_filter documentation)
 - #86838 (Checking that function is const if marked with rustc_const_unstable)
 - #86903 (Fix small headers display)
 - #86913 (Document rustdoc with `--document-private-items`)
 - #86957 (Update .mailmap file)
 - #86971 (mailmap: Add alternative addresses for myself)

Failed merges:

 - #86869 (Account for capture kind in auto traits migration)

r? `@ghost`
`@rustbot` modify labels: rollup
2021-07-08 17:51:10 +00:00
Guillaume Gomez ff4bf73a42
Rollup merge of #86789 - janikrabe:btreeset-drainfilter-doc, r=kennytm
Update BTreeSet::drain_filter documentation

This commit makes the documentation of `BTreeSet::drain_filter` more
consistent with that of `BTreeMap::drain_filter` after the changes in
f0b8166870.

In particular, this explicitly documents the iteration order.
2021-07-08 18:30:34 +02:00
Guillaume Gomez d12b16887b
Rollup merge of #86726 - sexxi-goose:use-diagnostic-item-for-rfc2229-migration, r=nikomatsakis
Use diagnostic items instead of lang items for rfc2229 migrations

This PR removes the `Send`, `UnwindSafe` and `RefUnwindSafe` lang items introduced in https://github.com/rust-lang/rust/pull/84730, and uses diagnostic items instead to check for `Send`, `UnwindSafe` and `RefUnwindSafe` traits for RFC2229 migrations.

r? ```@nikomatsakis```
2021-07-08 18:30:33 +02:00
bors d0485c7986 Auto merge of #86520 - ssomers:btree_iterators_checked_unwrap, r=Mark-Simulacrum
BTree: consistently avoid unwrap_unchecked in iterators

Some iterator support functions named `_unchecked` internally use `unwrap`, some use `unwrap_unchecked`. This PR tries settling on `unwrap`. #86195 went up the same road but travelled way further and doesn't seem successful.

r? `@Mark-Simulacrum`
2021-07-08 15:06:43 +00:00
bors 0cd0709f19 Auto merge of #86823 - the8472:opt-chunk-tra, r=kennytm
Optimize unchecked indexing into chunks and chunks_mut

Fixes #53340

```
# BEFORE

$ rustc +nightly -Copt-level=3 -Ccodegen-units=1 -Clto=fat chunks.rs
$ perf stat ./chunks

 Performance counter stats for './chunks':

          3,177.03 msec task-clock                #    1.000 CPUs utilized
                 4      context-switches          #    0.001 K/sec
                 0      cpu-migrations            #    0.000 K/sec
           984,006      page-faults               #    0.310 M/sec
    13,092,199,322      cycles                    #    4.121 GHz                      (83.29%)
       384,543,475      stalled-cycles-frontend   #    2.94% frontend cycles idle     (83.35%)
     7,414,280,722      stalled-cycles-backend    #   56.63% backend cycles idle      (83.38%)
    50,493,980,662      instructions              #    3.86  insn per cycle
                                                  #    0.15  stalled cycles per insn  (83.29%)
     6,625,375,297      branches                  # 2085.396 M/sec                    (83.38%)
         3,087,652      branch-misses             #    0.05% of all branches          (83.31%)

       3.178079469 seconds time elapsed

       2.327156000 seconds user
       0.762041000 seconds sys

# AFTER

$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc -Copt-level=3 -Ccodegen-units=1 -Clto=fat chunks.rs
$ perf stat ./chunks

 Performance counter stats for './chunks':

          2,705.76 msec task-clock                #    1.000 CPUs utilized
                 4      context-switches          #    0.001 K/sec
                 0      cpu-migrations            #    0.000 K/sec
           984,005      page-faults               #    0.364 M/sec
    11,156,763,039      cycles                    #    4.123 GHz                      (83.26%)
       342,198,882      stalled-cycles-frontend   #    3.07% frontend cycles idle     (83.37%)
     6,486,263,637      stalled-cycles-backend    #   58.14% backend cycles idle      (83.37%)
    40,553,476,617      instructions              #    3.63  insn per cycle
                                                  #    0.16  stalled cycles per insn  (83.37%)
     6,668,429,113      branches                  # 2464.532 M/sec                    (83.37%)
         3,099,636      branch-misses             #    0.05% of all branches          (83.26%)

       2.706725288 seconds time elapsed

       1.782083000 seconds user
       0.848424000 seconds sys
```
2021-07-08 09:44:52 +00:00
Yuki Okushi 01474ad92c
Rollup merge of #86956 - cuviper:unalias-every, r=m-ou-se
Revert "Add "every" as a doc alias for "all"."

This reverts commit 35450365ac (#81697) for "every" and closes #86554 in kind for "some".

The new [doc alias policy](https://std-dev-guide.rust-lang.org/documentation/doc-alias-policy.html) is that we don't want language-specific aliases like these JavaScript names, and we especially don't want to conflict with real names. While "every" is okay in the latter regard, its natural pair "some" makes a doc-search collision with `Option::Some`.

r? ```@m-ou-se```
2021-07-08 10:44:37 +09:00
Yuki Okushi 0f37050b74
Rollup merge of #86955 - Swordelf2:patch-1, r=cuviper
Fix typo in `ops::Drop` docs
2021-07-08 10:44:36 +09:00
Yuki Okushi a57a2e991d
Rollup merge of #86917 - notriddle:notriddle/from-try-reserve-error, r=JohnTitor
Add doc comment for `impl From<LayoutError> for TryReserveError`
2021-07-08 10:44:31 +09:00
Josh Stone ace3989d55 Revert "Add "every" as a doc alias for "all"."
This reverts commit 35450365ac.
2021-07-07 13:13:26 -07:00
Swordelf2 7677f5fe31
Fix typo in ops::Drop docs 2021-07-07 22:26:32 +03:00
Mara Bos 60535441c8 Check FromIterator trait impl in prelude collision check. 2021-07-07 13:26:38 +00:00
Trevor Spiteri ed76c11202 special case for integer log10 2021-07-07 14:10:05 +02:00
Trevor Spiteri b0f98c60a6 test integer log10 values close to all powers of 10 2021-07-07 14:07:32 +02:00
Yuki Okushi 9aee3c2883
Rollup merge of #86916 - godmar:@godmar/thread-yield-documentation-fix, r=joshtriplett
rewrote documentation for thread::yield_now()

The old documentation suggested the use of yield_now for repeated
polling instead of discouraging it; it also made the false claim that
channels are implemented using yield_now. (They are not, except for
a corner case).
2021-07-07 12:17:44 +09:00
Yuki Okushi fe3d6a74d9
Rollup merge of #86906 - juniorbassani:update-sync-docs, r=yaahc
Replace deprecated compare_and_swap and fix typo in core::sync::atomic::{fence, compiler_fence} docs
2021-07-07 12:17:42 +09:00
Yuki Okushi c630b6b0fc
Rollup merge of #86880 - m-ou-se:test-manuallydrop-clone-from, r=Mark-Simulacrum
Test ManuallyDrop::clone_from.

See #86288
2021-07-07 12:17:41 +09:00
Yuki Okushi 7e95290caa
Rollup merge of #86717 - rylev:rename, r=nikomatsakis
Rename some Rust 2021 lints to better names

Based on conversation in https://github.com/rust-lang/rust/issues/85894.

Rename a bunch of Rust 2021 related lints:

Lints that are officially renamed because they are already in beta or stable:
* `disjoint_capture_migration` => `rust_2021_incompatible_closure_captures`
* `or_patterns_back_compat` => `rust_2021_incompatible_or_patterns`
* `non_fmt_panic` => `non_fmt_panics`

Lints that are renamed but don't require any back -compat work since they aren't yet in stable:
* `future_prelude_collision` => `rust_2021_prelude_collisions`
* `reserved_prefix` => `rust_2021_token_prefixes`

Lints that have been discussed but that I did not rename:
* ~`non_fmt_panic` and `bare_trait_object`: is making this plural worth the headache we might cause users?~
* `array_into_iter`: I'm unsure of a good name and whether bothering users with a name change is worth it.

r? `@nikomatsakis`
2021-07-07 12:17:39 +09:00
Yuki Okushi 9bbc470e97
Rollup merge of #80918 - yoshuawuyts:int-log2, r=m-ou-se
Add Integer::log variants

_This is another attempt at landing https://github.com/rust-lang/rust/pull/70835, which was approved by the libs team but failed on Android tests through Bors. The text copied here is from the original issue. The only change made so far is the addition of non-`checked_` variants of the log methods._

_Tracking issue: #70887_

---

This implements `{log,log2,log10}` methods for all integer types. The implementation was provided by `@substack` for use in the stdlib.

_Note: I'm not big on math, so this PR is a best effort written with limited knowledge. It's likely I'll be getting things wrong, but happy to learn and correct. Please bare with me._

## Motivation
Calculating the logarithm of a number is a generally useful operation. Currently the stdlib only provides implementations for floats, which means that if we want to calculate the logarithm for an integer we have to cast it to a float and then back to an int.

> would be nice if there was an integer log2 instead of having to either use the f32 version or leading_zeros() which i have to verify the results of every time to be sure

_— [`@substack,` 2020-03-08](https://twitter.com/substack/status/1236445105197727744)_

At higher numbers converting from an integer to a float we also risk overflows. This means that Rust currently only provides log operations for a limited set of integers.

The process of doing log operations by converting between floats and integers is also prone to rounding errors. In the following example we're trying to calculate `base10` for an integer. We might try and calculate the `base2` for the values, and attempt [a base swap](https://www.rapidtables.com/math/algebra/Logarithm.html#log-rules) to arrive at `base10`. However because we're performing intermediate rounding we arrive at the wrong result:

```rust
// log10(900) = ~2.95 = 2
dbg!(900f32.log10() as u64);

// log base change rule: logb(x) = logc(x) / logc(b)
// log2(900) / log2(10) = 9/3 = 3
dbg!((900f32.log2() as u64) / (10f32.log2() as u64));
```
_[playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bd6c68b3539e400f9ca4fdc6fc2eed0)_

This is somewhat nuanced as a lot of the time it'll work well, but in real world code this could lead to some hard to track bugs. By providing correct log implementations directly on integers we can help prevent errors around this.

## Implementation notes

I checked whether LLVM intrinsics existed before implementing this, and none exist yet. ~~Also I couldn't really find a better way to write the `ilog` function. One option would be to make it a private method on the number, but I didn't see any precedent for that. I also didn't know where to best place the tests, so I added them to the bottom of the file. Even though they might seem like quite a lot they take no time to execute.~~

## References

- [Log rules](https://www.rapidtables.com/math/algebra/Logarithm.html#log-rules)
- [Rounding error playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bd6c68b3539e400f9ca4fdc6fc2eed0)
- [substack's tweet asking about integer log2 in the stdlib](https://twitter.com/substack/status/1236445105197727744)
- [Integer Logarithm, A. Jaffer 2008](https://people.csail.mit.edu/jaffer/III/ilog.pdf)
2021-07-07 12:17:32 +09:00
Michael Howell a151982af3 Add doc comment for impl From<LayoutError> for TryReserveError 2021-07-06 14:44:18 -07:00
Godmar Back fb464a3b39 rewrote documentation for thread::yield_now()
The old documentation suggested the use of yield_now for repeated
polling instead of discouraging it; it also made the false claim that
channels are implementing using yield_now. (They are not, except for
a corner case).
2021-07-06 15:50:42 -04:00
Ryan Levick a902e25f58 Add s to non_fmt_panic 2021-07-06 20:12:56 +02:00
Ryan Levick 1d49658f5c Change or_patterns_back_compat lint to rust_2021_incompatible_or_patterns 2021-07-06 20:11:45 +02:00
Júnior Bassani 0d61e6e8d6
Fix typo in core::sync::atomic::compiler_fence example 2021-07-06 10:53:14 -03:00
Júnior Bassani a87fb18027
Replace deprecated compare_and_swap by compare_exchange_weak in core::sync::atomic::fence example 2021-07-06 10:50:17 -03:00
Yuki Okushi 470ed70a86
Rollup merge of #86852 - Amanieu:remove_doc_aliases, r=joshtriplett
Remove some doc aliases

As per the new doc alias policy in https://github.com/rust-lang/std-dev-guide/pull/25, this removes some controversial doc aliases:
- `malloc`, `alloc`, `realloc`, etc.
- `length` (alias for `len`)
- `delete` (alias for `remove` in collections and also file/directory deletion)

r? `@joshtriplett`
2021-07-06 02:33:16 +09:00
Yuki Okushi 2bc7d4d70a
Rollup merge of #86794 - inquisitivecrystal:seek-rewind, r=m-ou-se
Stabilize `Seek::rewind()`

This stabilizes `Seek::rewind`. It seemed to fit into one of the existing tests, so I extended that test rather than adding a new one.

Closes #85149.
2021-07-06 02:33:15 +09:00
Yuki Okushi add24d2f4f
Rollup merge of #85377 - ijackson:abort-docs, r=m-ou-se
aborts: Clarify documentation and comments

In the docs for intrinsics::abort():

 * Strengthen the recommendation by to use process::abort instead.
 * Document the fact that it sometimes (ab)uses an LLVM debug trap and what the likely consequences are.
 * State that the precise behaviour is unstable.

In the docs for process::abort():

 * Promise that we have the same behaviour as C `abort()`.
 * Document the likely consequences, including, specifically, the consequences on Unix.

In the internal comment for unix::abort_internal:

 * Refer to the public docs for the public API functions.
 * Correct and expand the description of libc::abort.  Specifically:
 * Do not claim that abort() unregisters signal handlers.  It doesn't; it honours the SIGABRT handler.
 * Discuss, extensively, the issue with abort() flushing stdio buffers.
 * Describe the glibc behaviour in some detail.

Co-authored-by: Mark Wooding <mdw@distorted.org.uk>
Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>

Fixes #40230
2021-07-06 02:33:13 +09:00