about summary refs log tree commit diff
path: root/library/std/src
AgeCommit message (Collapse)AuthorLines
2020-10-18Add std::panic::panic_box.Mara Bos-0/+14
2020-10-18`#[deny(unsafe_op_in_unsafe_fn)]` in sys/cloudabichansuke-64/+75
2020-10-18Auto merge of #74480 - yoshuawuyts:hardware_threads, r=dtolnaybors-0/+163
Add std::thread::available_concurrency This PR adds a counterpart to [C++'s `std::thread::hardware_concurrency`](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) to Rust, tracking issue https://github.com/rust-lang/rust/issues/74479. cc/ `@rust-lang/libs` ## Motivation Being able to know how many hardware threads a platform supports is a core part of building multi-threaded code. In C++ 11 this has become available through the [`std::thread::hardware_concurrency`](https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency) API. Currently in Rust most of the ecosystem depends on the [`num_cpus` crate](https://docs.rs/num_cpus/1.13.0/num_cpus/) ([no.35 in top 500 crates](https://docs.google.com/spreadsheets/d/1wwahRMHG3buvnfHjmPQFU4Kyfq15oTwbfsuZpwHUKc4/edit#gid=1253069234)) to provide this functionality. This PR proposes an API to provide access to the number of hardware threads available on a given platform. __edit (2020-07-24):__ The purpose of this PR is to provide a hint for how many threads to spawn to saturate the processor. There's value in introducing APIs for NUMA and Windows processor groups, but those are intentionally out of scope for this PR. See: https://github.com/rust-lang/rust/pull/74480#issuecomment-662116186. ## Naming Discussing the naming of the API on Zulip surfaced two options: - `std::thread::hardware_concurrency` - `std::thread::hardware_threads` Both options seemed acceptable, but overall people seem to gravitate the most towards `hardware_threads`. Additionally `@jonas-schievink` pointed out that the "hardware threads" terminology is well-established and is used in among other the [RISC-V specification](https://riscv.org/specifications/isa-spec-pdf/) (page 20): > A component is termed a core if it contains an independent instruction fetch unit. A RISC-V-compatible core might support multiple RISC-V-compatible __hardware threads__, or harts, through multithreading. It's also worth noting that [the original paper introducing C++'s `std::thread` submodule](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html) unfortunately doesn't feature any discussion on the naming of `hardware_concurrency`, so we can't use that to help inform our decision here. ## Return type An important consideration `@joshtriplett` brought up is that we don't want to default to `1` for platforms where the number of available threads cannot be retrieved. Instead we want to inform the users of the fact that we don't know and allow them to handle that case. Which is why this PR uses `Option<NonZeroUsize>` as its return type, where `None` is returned on platforms where we don't know the number of hardware threads available. The reasoning for `NonZeroUsize` vs `usize` is that if the number of threads for a platform are known, they'll always be at least 1. As evidenced by the example the `NonZero*` family of APIs may currently not be the most ergonomic to use, but improving the ergonomics of them is something that I think we can address separately. ## Implementation `@Mark-Simulacrum` pointed out that most of the code we wanted to expose here was already available under `libtest`. So this PR mostly moves the internal code of libtest into a public API.
2020-10-17Auto merge of #77455 - asm89:faster-spawn, r=kennytmbors-1/+7
Use posix_spawn() on unix if program is a path Previously `Command::spawn` would fall back to the non-posix_spawn based implementation if the `PATH` environment variable was possibly changed. On systems with a modern (g)libc `posix_spawn()` can be significantly faster. If program is a path itself the `PATH` environment variable is not used for the lookup and it should be safe to use the `posix_spawnp()` method. [1] We found this, because we have a cli application that effectively runs a lot of subprocesses. It would sometimes noticeably hang while printing output. Profiling showed that the process was spending the majority of time in the kernel's `copy_page_range` function while spawning subprocesses. During this time the process is completely blocked from running, explaining why users were reporting the cli app hanging. Through this we discovered that `std::process::Command` has a fast and slow path for process execution. The fast path is backed by `posix_spawnp()` and the slow path by fork/exec syscalls being called explicitly. Using fork for process creation is supposed to be fast, but it slows down as your process uses more memory. It's not because the kernel copies the actual memory from the parent, but it does need to copy the references to it (see `copy_page_range` above!). We ended up using the slow path, because the command spawn implementation in falls back to the slow path if it suspects the PATH environment variable was changed. Here is a smallish program demonstrating the slowdown before this code change: ``` use std::process::Command; use std::time::Instant; fn main() { let mut args = std::env::args().skip(1); if let Some(size) = args.next() { // Allocate some memory let _xs: Vec<_> = std::iter::repeat(0) .take(size.parse().expect("valid number")) .collect(); let mut command = Command::new("/bin/sh"); command .arg("-c") .arg("echo hello"); if args.next().is_some() { println!("Overriding PATH"); command.env("PATH", std::env::var("PATH").expect("PATH env var")); } let now = Instant::now(); let child = command .spawn() .expect("failed to execute process"); println!("Spawn took: {:?}", now.elapsed()); let output = child.wait_with_output().expect("failed to wait on process"); println!("Output: {:?}", output); } else { eprintln!("Usage: prog [size]"); std::process::exit(1); } () } ``` Running it and passing different amounts of elements to use to allocate memory shows that the time taken for `spawn()` can differ quite significantly. In latter case the `posix_spawnp()` implementation is 30x faster: ``` $ cargo run --release 10000000 ... Spawn took: 324.275µs hello $ cargo run --release 10000000 changepath ... Overriding PATH Spawn took: 2.346809ms hello $ cargo run --release 100000000 ... Spawn took: 387.842µs hello $ cargo run --release 100000000 changepath ... Overriding PATH Spawn took: 13.434677ms hello ``` [1]: https://github.com/bminor/glibc/blob/5f72f9800b250410cad3abfeeb09469ef12b2438/posix/execvpe.c#L81
2020-10-16Add std::thread::available_concurrencyYoshua Wuyts-0/+163
2020-10-17Rollup merge of #77971 - jyn514:broken-intra-doc-links, r=mark-simulacrumYuki Okushi-1/+2
Deny broken intra-doc links in linkchecker Since rustdoc isn't warning about these links, check for them manually. This also fixes the broken links that popped up from the lint.
2020-10-17Rollup merge of #77900 - Thomasdezeeuw:fdatasync, r=dtolnayYuki Okushi-2/+16
Use fdatasync for File::sync_data on more OSes Add support for the following OSes: * Android * FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=fdatasync&sektion=2 * OpenBSD: https://man.openbsd.org/OpenBSD-5.8/fsync.2 * NetBSD: https://man.netbsd.org/fdatasync.2 * illumos: https://illumos.org/man/3c/fdatasync
2020-10-17Rollup merge of #77547 - RalfJung:stable-union-drop, r=matthewjasperYuki Okushi-1/+1
stabilize union with 'ManuallyDrop' fields and 'impl Drop for Union' As [discussed by @SimonSapin and @withoutboats](https://github.com/rust-lang/rust/issues/55149#issuecomment-634692020), this PR proposes to stabilize parts of the `untagged_union` feature gate: * It will be possible to have a union with field type `ManuallyDrop<T>` for any `T`. * While at it I propose we also stabilize `impl Drop for Union`; to my knowledge, there are no open concerns around this feature. In the RFC discussion, we also talked about allowing `&mut T` as another non-`Copy` non-dropping type, but that felt to me like an overly specific exception so I figured we'd wait if there is actually any use for such a special case. Some things remain unstable and still require the `untagged_union` feature gate: * Union with fields that do not drop, are not `Copy`, and are not `ManuallyDrop<_>`. The reason to not stabilize this is to avoid semver concerns around libraries adding `Drop` implementations later. (This is already not fully semver compatible as, to my knowledge, the borrow checker will exploit the non-dropping nature of any type, but it seems prudent to avoid further increasing the amount of trouble adding an `impl Drop` can cause.) Due to this, quite a few tests still need the `untagged_union` feature, but I think the ones where I could remove the feature flag provide good test coverage for the stable part. Cc @rust-lang/lang
2020-10-16stop relying on feature(untagged_unions) in stdlibRalf Jung-1/+1
2020-10-16Take some of sys/vxworks/process/* from sys/unix instead.Mara Bos-407/+77
2020-10-16Take sys/vxworks/{os,path,pipe} from sys/unix instead.Mara Bos-446/+33
2020-10-16Take sys/vxworks/{fd,fs,io} from sys/unix instead.Mara Bos-909/+81
2020-10-16Take sys/vxworks/cmath from sys/unix instead.Mara Bos-32/+1
2020-10-16Take sys/vxworks/args from sys/unix instead.Mara Bos-96/+3
2020-10-16Take sys/vxworks/memchar from sys/unix instead.Mara Bos-21/+1
2020-10-16Take sys/vxworks/net from sys/unix instead.Mara Bos-360/+9
2020-10-16Take sys/vxworks/ext/* from sys/unix instead.Mara Bos-1321/+1
2020-10-16Add weak macro to vxworks.Mara Bos-0/+4
2020-10-16Take sys/vxworks/alloc from sys/unix instead.Mara Bos-49/+1
2020-10-16Take sys/vxworks/thread_local_key from sys/unix instead.Mara Bos-34/+1
2020-10-16Take sys/vxworks/stdio from sys/unix instead.Mara Bos-69/+1
2020-10-16Take sys/vxworks/thread from sys/unix instead.Mara Bos-158/+7
2020-10-16Take sys/vxworks/stack_overflow from sys/unix instead.Mara Bos-39/+2
2020-10-16Take sys/vxworks/time from sys/unix instead.Mara Bos-197/+1
2020-10-16Take sys/vxworks/rwlock from sys/unix instead.Mara Bos-114/+1
2020-10-16Take sys/vxworks/condvar from sys/unix instead.Mara Bos-91/+1
2020-10-16Take sys/vxworks/mutex from sys/unix instead.Mara Bos-133/+1
2020-10-15Deny broken intra-doc links in linkcheckerJoshua Nelson-1/+2
Since rustdoc isn't warning about these links, check for them manually.
2020-10-16Rollup merge of #77657 - fusion-engineering-forks:cleanup-cloudabi-sync, ↵Dylan DPC-77/+65
r=dtolnay Cleanup cloudabi mutexes and condvars This gets rid of lots of unnecessary unsafety. All the AtomicU32s were wrapped in UnsafeCell or UnsafeCell<MaybeUninit>, and raw pointers were used to get to the AtomicU32 inside. This change cleans that up by using AtomicU32 directly. Also replaces a UnsafeCell<u32> by a safer Cell<u32>. @rustbot modify labels: +C-cleanup
2020-10-16Rollup merge of #77648 - fusion-engineering-forks:static-mutex, r=dtolnayDylan DPC-14/+8
Static mutex is static StaticMutex is only ever used with as a static (as the name already suggests). So it doesn't have to be generic over a lifetime, but can simply assume 'static. This 'static lifetime guarantees the object is never moved, so this is no longer a manually checked requirement for unsafe calls to lock(). @rustbot modify labels: +T-libs +A-concurrency +C-cleanup
2020-10-16Rollup merge of #77646 - fusion-engineering-forks:use-static-mutex, r=dtolnayDylan DPC-19/+9
For backtrace, use StaticMutex instead of a raw sys Mutex. The code used the very unsafe `sys::mutex::Mutex` directly, and built its own unlock-on-drop wrapper around it. The StaticMutex wrapper already provides that and is easier to use safely. @rustbot modify labels: +T-libs +C-cleanup
2020-10-16Rollup merge of #77619 - fusion-engineering-forks:wasm-parker, r=dtolnayDylan DPC-1/+24
Use futex-based thread-parker for Wasm32. This uses the existing `sys_common/thread_parker/futex.rs` futex-based thread parker (that was already used for Linux) for wasm32 as well (if the wasm32 atomics target feature is enabled, which is not the case by default). Wasm32 provides the basic futex operations as instructions: https://webassembly.github.io/threads/syntax/instructions.html These are now exposed from `sys::futex::{futex_wait, futex_wake}`, just like on Linux. So, `thread_parker/futex.rs` stays completely unmodified.
2020-10-16Rollup merge of #76084 - Lucretiel:split-buffered, r=dtolnayDylan DPC-1438/+1463
Refactor io/buffered.rs into submodules This pull request splits `BufWriter`, `BufReader`, `LineWriter`, and `LineWriterShim` (along with their associated tests) into separate submodules. It contains no functional changes. This change is being made in anticipation of adding another type of buffered writer which can be switched between line- and block-buffering mode. Part of a series of pull requests resolving #60673.
2020-10-15Fix link to foreign calling conventionsMatthew Kraai-0/+2
2020-10-14Remove lifetime from StaticMutex and assume 'static.Mara Bos-14/+7
StaticMutex is only ever used with as a static (as the name already suggests). So it doesn't have to be generic over a lifetime, but can simply assume 'static. This 'static lifetime guarantees the object is never moved, so this is no longer a manually checked requirement for unsafe calls to lock().
2020-10-14Fix comment about non-reentrant StaticMutex::lock().Mara Bos-2/+3
The comment said it's UB to call lock() while it is locked. That'd be quite a useless Mutex. :) It was supposed to say 'locked by the same thread', not just 'locked'.
2020-10-14Rollup merge of #77870 - camelid:intra-doc-super, r=jyn514Dylan DPC-4/+4
Use intra-doc links for links to module-level docs r? @jyn514
2020-10-13fmtwcampbell-1/+1
Signed-off-by: wcampbell <wcampbell1995@gmail.com>
2020-10-13use matches! in library/std/src/net/ip.rs wcampbell-4/+1
Apply suggestion from review Co-authored-by: LingMan <LingMan@users.noreply.github.com>
2020-10-13[net] clippy: identity_opwcampbell-4/+4
warning: the operation is ineffective. Consider reducing it to `self.segments()[0]` --> library/std/src/net/ip.rs:1265:9 | 1265 | (self.segments()[0] & 0xffff) == 0xfe80 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(clippy::identity_op)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[1]` --> library/std/src/net/ip.rs:1266:16 | 1266 | && (self.segments()[1] & 0xffff) == 0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[2]` --> library/std/src/net/ip.rs:1267:16 | 1267 | && (self.segments()[2] & 0xffff) == 0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op warning: the operation is ineffective. Consider reducing it to `self.segments()[3]` --> library/std/src/net/ip.rs:1268:16 | 1268 | && (self.segments()[3] & 0xffff) == 0 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#identity_op Signed-off-by: wcampbell <wcampbell1995@gmail.com>
2020-10-13[net] clippy: match_like_matches_macrowcampbell-4/+1
warning: match expression looks like `matches!` macro --> library/std/src/net/ip.rs:459:9 | 459 | / match self.octets() { 460 | | [169, 254, ..] => true, 461 | | _ => false, 462 | | } | |_________^ help: try this: `matches!(self.octets(), [169, 254, ..])` | = note: `#[warn(clippy::match_like_matches_macro)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#match_like_matches_macro Signed-off-by: wcampbell <wcampbell1995@gmail.com>
2020-10-13[net] clippy: needless_updatewcampbell-1/+0
warning: struct update has no effect, all the fields in the struct have already been specified --> library/std/src/net/addr.rs:367:19 | 367 | ..unsafe { mem::zeroed() } | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(clippy::needless_update)]` on by default = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_update
2020-10-13Refactor collapsible_ifwcampbell-14/+12
Signed-off-by: wcampbell <wcampbell1995@gmail.com>
2020-10-13box mutex to get a movable mutexStefan Lankes-1/+1
the commit avoid an alignement issue in Mutex implementation
2020-10-14Rollup merge of #77722 - fusion-engineering-forks:safe-unsupported-locks, ↵Yuki Okushi-37/+34
r=Mark-Simulacrum Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn). Replacing `UnsafeCell`s by a `Cell`s simplifies things and makes the mutex and rwlock implementations safe. Other than that, only unsafety in strlen() contained unsafe code. @rustbot modify labels: +F-unsafe-block-in-unsafe-fn +C-cleanup
2020-10-14Rollup merge of #77719 - ↵Yuki Okushi-2/+0
fusion-engineering-forks:const-new-mutex-attr-cleanup, r=Mark-Simulacrum Remove unnecessary rustc_const_stable attributes. These attributes were added in https://github.com/rust-lang/rust/pull/74033#discussion_r450593156 because of [std::io::lazy::Lazy::new](https://github.com/rust-lang/rust/blob/0c03aee8b81185d65b5821518661c30ecdb42de5/src/libstd/io/lazy.rs#L21-L23). But [std::io::lazy::Lazy is gone now](https://github.com/rust-lang/rust/pull/77154), so this can be cleaned up. @rustbot modify labels: +T-libs +C-cleanup
2020-10-13Use is_ok() instead of empty Ok(_)wcampbell-10/+4
Signed-off-by: wcampbell <wcampbell1995@gmail.com>
2020-10-13Join map operatorswcampbell-2/+1
Signed-off-by: wcampbell <wcampbell1995@gmail.com>
2020-10-13Deny unsafe_op_in_unsafe_fn for unsupported/common.rs through sys/wasm too.Mara Bos-0/+2
2020-10-13Use fdatasync for File::sync_data on more OSesThomas de Zeeuw-2/+16
Add support for the following OSes: * Android * FreeBSD: https://www.freebsd.org/cgi/man.cgi?query=fdatasync&sektion=2 * OpenBSD: https://man.openbsd.org/OpenBSD-5.8/fsync.2 * NetBSD: https://man.netbsd.org/fdatasync.2 * illumos: https://illumos.org/man/3c/fdatasync