Commit graph

3127 commits

Author SHA1 Message Date
Chris Martin 3de6c2ca33 Address review feedback 2022-05-13 18:14:03 -04: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
bors 8c4fc9d9a4 Auto merge of #94598 - scottmcm:prefix-free-hasher-methods, r=Amanieu
Add a dedicated length-prefixing method to `Hasher`

This accomplishes two main goals:
- Make it clear who is responsible for prefix-freedom, including how they should do it
- Make it feasible for a `Hasher` that *doesn't* care about Hash-DoS resistance to get better performance by not hashing lengths

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.

Fixes #94026

r? rust-lang/libs

---

The core of this change is the following two new methods on `Hasher`:

```rust
pub trait Hasher {
    /// Writes a length prefix into this hasher, as part of being prefix-free.
    ///
    /// If you're implementing [`Hash`] for a custom collection, call this before
    /// writing its contents to this `Hasher`.  That way
    /// `(collection![1, 2, 3], collection![4, 5])` and
    /// `(collection![1, 2], collection![3, 4, 5])` will provide different
    /// sequences of values to the `Hasher`
    ///
    /// The `impl<T> Hash for [T]` includes a call to this method, so if you're
    /// hashing a slice (or array or vector) via its `Hash::hash` method,
    /// you should **not** call this yourself.
    ///
    /// This method is only for providing domain separation.  If you want to
    /// hash a `usize` that represents part of the *data*, then it's important
    /// that you pass it to [`Hasher::write_usize`] instead of to this method.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(hasher_prefixfree_extras)]
    /// # // Stubs to make the `impl` below pass the compiler
    /// # struct MyCollection<T>(Option<T>);
    /// # impl<T> MyCollection<T> {
    /// #     fn len(&self) -> usize { todo!() }
    /// # }
    /// # impl<'a, T> IntoIterator for &'a MyCollection<T> {
    /// #     type Item = T;
    /// #     type IntoIter = std::iter::Empty<T>;
    /// #     fn into_iter(self) -> Self::IntoIter { todo!() }
    /// # }
    ///
    /// use std:#️⃣:{Hash, Hasher};
    /// impl<T: Hash> Hash for MyCollection<T> {
    ///     fn hash<H: Hasher>(&self, state: &mut H) {
    ///         state.write_length_prefix(self.len());
    ///         for elt in self {
    ///             elt.hash(state);
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Note to Implementers
    ///
    /// If you've decided that your `Hasher` is willing to be susceptible to
    /// Hash-DoS attacks, then you might consider skipping hashing some or all
    /// of the `len` provided in the name of increased performance.
    #[inline]
    #[unstable(feature = "hasher_prefixfree_extras", issue = "88888888")]
    fn write_length_prefix(&mut self, len: usize) {
        self.write_usize(len);
    }

    /// Writes a single `str` into this hasher.
    ///
    /// If you're implementing [`Hash`], you generally do not need to call this,
    /// as the `impl Hash for str` does, so you can just use that.
    ///
    /// This includes the domain separator for prefix-freedom, so you should
    /// **not** call `Self::write_length_prefix` before calling this.
    ///
    /// # Note to Implementers
    ///
    /// The default implementation of this method includes a call to
    /// [`Self::write_length_prefix`], so if your implementation of `Hasher`
    /// doesn't care about prefix-freedom and you've thus overridden
    /// that method to do nothing, there's no need to override this one.
    ///
    /// This method is available to be overridden separately from the others
    /// as `str` being UTF-8 means that it never contains `0xFF` bytes, which
    /// can be used to provide prefix-freedom cheaper than hashing a length.
    ///
    /// For example, if your `Hasher` works byte-by-byte (perhaps by accumulating
    /// them into a buffer), then you can hash the bytes of the `str` followed
    /// by a single `0xFF` byte.
    ///
    /// If your `Hasher` works in chunks, you can also do this by being careful
    /// about how you pad partial chunks.  If the chunks are padded with `0x00`
    /// bytes then just hashing an extra `0xFF` byte doesn't necessarily
    /// provide prefix-freedom, as `"ab"` and `"ab\u{0}"` would likely hash
    /// the same sequence of chunks.  But if you pad with `0xFF` bytes instead,
    /// ensuring at least one padding byte, then it can often provide
    /// prefix-freedom cheaper than hashing the length would.
    #[inline]
    #[unstable(feature = "hasher_prefixfree_extras", issue = "88888888")]
    fn write_str(&mut self, s: &str) {
        self.write_length_prefix(s.len());
        self.write(s.as_bytes());
    }
}
```

With updates to the `Hash` implementations for slices and containers to call `write_length_prefix` instead of `write_usize`.

`write_str` defaults to using `write_length_prefix` since, as was pointed out in the issue, the `write_u8(0xFF)` approach is insufficient for hashers that work in chunks, as those would hash `"a\u{0}"` and `"a"` to the same thing.  But since `SipHash` works byte-wise (there's an internal buffer to accumulate bytes until a full chunk is available) it overrides `write_str` to continue to use the add-non-UTF-8-byte approach.

---

Compatibility:

Because the default implementation of `write_length_prefix` calls `write_usize`, the changed hash implementation for slices will do the same thing the old one did on existing `Hasher`s.
2022-05-06 09:43:57 +00:00
bors 7f9e013ba6 Auto merge of #96510 - m-ou-se:futex-bsd, r=Amanieu
Use futex-based locks and thread parker on {Free, Open, DragonFly}BSD.

This switches *BSD to our futex-based locks and thread parker.

Tracking issue: https://github.com/rust-lang/rust/issues/93740

This is a draft, because this still needs a new version of the `libc` crate to be published that includes https://github.com/rust-lang/libc/pull/2770.

r? `@Amanieu`
2022-05-06 07:20:04 +00:00
Scott McMurray 98054377ee Add a dedicated length-prefixing method to Hasher
This accomplishes two main goals:
- Make it clear who is responsible for prefix-freedom, including how they should do it
- Make it feasible for a `Hasher` that *doesn't* care about Hash-DoS resistance to get better performance by not hashing lengths

This does not change rustc-hash, since that's in an external crate, but that could potentially use it in future.
2022-05-06 00:03:38 -07:00
Michael Goulet 8bcf4b0efc
Rollup merge of #96744 - est31:join_osstr, r=thomcc
Implement [OsStr]::join

Implements join for `OsStr` and `OsString` slices:

```Rust
    let strings = [OsStr::new("hello"), OsStr::new("dear"), OsStr::new("world")];
    assert_eq!("hello dear world", strings.join(OsStr::new(" ")));
````

This saves one from converting to strings and back, or from implementing it manually.
2022-05-05 19:34:26 -07:00
est31 4fcbc53820 Implement [OsStr]::join 2022-05-05 21:58:11 +02:00
Mara Bos 21c5f780f4 Remove condvar::two_mutexes test.
We don't guarantee this panics. On most platforms it doesn't anymore.
2022-05-05 21:47:13 +02:00
bors 322a14919d Auto merge of #96649 - tbu-:pr_to_ipv4_loopback_doc, r=m-ou-se
Make it clear that `to_ipv4` returns an IPv4 address for the IPv6 loopback
2022-05-05 09:45:53 +00:00
Yuki Okushi b792258b32
Rollup merge of #96619 - akiekintveld:same_mutex_check_relaxed_ordering, r=m-ou-se
Relax memory ordering used in SameMutexCheck

`SameMutexCheck` only requires atomicity for `self.addr`, but does not need ordering of other memory accesses in either the success or failure case. Using `Relaxed`, the code still correctly handles the case when two threads race to store an address.
2022-05-05 10:20:34 +09:00
Yuki Okushi 8385d1713e
Rollup merge of #96616 - akiekintveld:min_stack_relaxed_ordering, r=joshtriplett
Relax memory ordering used in `min_stack`

`min_stack` does not provide any synchronization guarantees to its callers, and only requires atomicity for `MIN` itself, so relaxed memory ordering is sufficient.
2022-05-05 10:20:33 +09:00
Tobias Bucher ed95d502c6 Make it clear that to_ipv4 returns an IPv4 address for the IPv6 loopback 2022-05-05 00:45:55 +02:00
Mara Bos 9299e6915d Round timeouts up to infinite in futex_wait on DragonFlyBSD. 2022-05-03 12:37:52 +02:00
Mara Bos 8ee9b93c4f Add #[cfg] in cfg_if for linux in unix/futex. 2022-05-03 12:37:52 +02:00
Mara Bos 7b7d1d6c48 Don't use futexes on netbsd.
The latest NetBSD release doesn't include the futex syscall yet.
2022-05-03 12:26:17 +02:00
Austin Kiekintveld 55a7d18189 Add comment 2022-05-01 19:07:36 -07:00
Austin Kiekintveld a05df2ea19 Fix formatting 2022-05-01 19:02:28 -07:00
Austin Kiekintveld df4457e20b
Relax memory ordering used in SameMutexCheck
`SameMutexCheck` only requires atomicity for `self.addr`, but does not need ordering of other memory accesses in either the success or failure case. Using `Relaxed`, the code still correctly handles the case when two threads race to store an address.
2022-05-01 16:46:19 -07:00
Austin Kiekintveld 63a90efe2f
Relax memory ordering used in min_stack
`min_stack` does not provide any synchronization guarantees to its callers, and only requires atomicity for `MIN` itself, so relaxed memory ordering is sufficient.
2022-05-01 15:55:54 -07:00
bors 4dd8b420c0 Auto merge of #96521 - petrochenkov:docrules, r=notriddle,GuillaumeGomez
rustdoc: Resolve doc links referring to `macro_rules` items

cc https://github.com/rust-lang/rust/issues/81633

UPD: the fallback to considering *all* `macro_rules` in the crate for unresolved names is not removed in this PR, it will be removed separately and will be run through crater.
2022-05-01 20:28:10 +00:00
bors 61469b682c Auto merge of #96490 - dtolnay:writetmpbackport, r=Mark-Simulacrum
Make [e]println macros eagerly drop temporaries (for backport)

This PR extracts the subset of #96455 which is only the parts necessary for fixing the 1.61-beta regressions in #96434.

My larger PR #96455 contains a few other changes relative to the pre-#94868 behavior; those are not necessary to backport into 1.61.

argument position | before #94868 | after #94868 | after this PR
--- |:---:|:---:|:---:
`write!($tmp, "…", …)` | 😡 | 😡 | 😡
`write!(…, "…", $tmp)` | 😡 | 😡 | 😡
`writeln!($tmp, "…", …)` | 😡 | 😡 | 😡
`writeln!(…, "…", $tmp)` | 😡 | 😡 | 😡
`print!("…", $tmp)` | 😡 | 😡 | 😡
`println!("…", $tmp)` | 😺 | 😡 | 😺
`eprint!("…", $tmp)` | 😡 | 😡 | 😡
`eprintln!("…", $tmp)` | 😺 | 😡 | 😺
`panic!("…", $tmp)` | 😺 | 😺 | 😺
2022-05-01 03:18:53 +00:00
Vadim Petrochenkov 6083db7c4e Fix some links in the standard library 2022-05-01 00:02:34 +03:00
Mara Bos 1b9c7e6f1a Disable pthread thread parker on futex platforms. 2022-04-29 16:45:17 +02:00
Mara Bos c4c69143a9 Always return false in futex_wake on {Free,DragonFly}BSD. 2022-04-29 16:45:17 +02:00
Mara Bos 0b4df22f55 Update libc dependency of std to 0.2.125. 2022-04-29 16:45:17 +02:00
Mara Bos 04b0bc97bb Use futex-based locks and thread parker on FreeBSD. 2022-04-29 16:45:17 +02:00
Mara Bos 69f0bcb26d Use futex-based locks and thread parker on DragonFlyBSD. 2022-04-29 16:30:54 +02:00
Mara Bos 2dfad1e3f8 Use futex-based locks and thread parker on NetBSD. 2022-04-29 16:30:54 +02:00
Mara Bos afe1a256ce Use futex-based locks and thread parker on OpenBSD. 2022-04-29 16:30:54 +02:00
Dylan DPC cd5dc49379
Rollup merge of #96492 - joshtriplett:revert-std-ffi-re-export, r=yaahc
Revert "Re-export core::ffi types from std::ffi"

This reverts commit 9aed829fe6.

Fixes https://github.com/rust-lang/rust/issues/96435 , a regression
in crates doing `use std::ffi::*;` and `use std::os::raw::*;`.

We can re-add this re-export once the `core::ffi` types
are stable, and thus the `std::os::raw` types can become re-exports as
well, which will avoid the conflict. (Type aliases to the same type
still conflict, but re-exports of the same type don't.)
2022-04-29 11:23:14 +02:00
Dylan DPC db1ec25224
Rollup merge of #96481 - aDotInTheVoid:hashmap-docs-monospace, r=joshtriplett
HashMap doc: Don't use monospace font for 'Entry Api'
2022-04-29 11:23:13 +02:00
bors ddb7fbe843 Auto merge of #96441 - ChrisDenton:sync-pipes, r=m-ou-se
Windows: Make stdin pipes synchronous

Stdin pipes do not need to be used asynchronously within the standard library. This is a first step in making pipes mostly synchronous.

r? `@m-ou-se`
2022-04-29 03:06:45 +00:00
bors baaa3b6829 Auto merge of #96393 - joboet:pthread_parker, r=thomcc
std: directly use pthread in UNIX parker implementation

`Mutex` and `Condvar` are being replaced by more efficient implementations, which need thread parking themselves (see #93740). Therefore we should use the `pthread` synchronization primitives directly. Also, we can avoid allocating the mutex and condition variable because the `Parker` struct is being placed in an `Arc` anyways.

This basically is just a copy of the current `Mutex` and `Condvar` code, which will however be removed (again, see #93740). An alternative implementation could be to use dedicated private `OsMutex` and `OsCondvar` types, but all the other platforms supported by std actually have their own thread parking primitives.

I used `Pin` to guarantee a stable address for the `Parker` struct, while the current implementation does not, rather using extra unsafe declaration. Since the thread struct is shared anyways, I assumed this would not add too much clutter while being clearer.
2022-04-28 21:58:08 +00:00
joboet 550273361d
std: simplify UNIX parker timeouts 2022-04-28 12:31:19 +02:00
Dylan DPC c4dd0d3bb7
Rollup merge of #96397 - AronParker:issue-96368-fix, r=dtolnay
Make EncodeWide implement FusedIterator

[`EncodeUtf16`](https://doc.rust-lang.org/std/str/struct.EncodeUtf16.html) and [`EncodeWide`](https://doc.rust-lang.org/std/os/windows/ffi/struct.EncodeWide.html) currently serve similar purposes: They convert from UTF-8 to UTF-16 and WTF-8 to WTF-16, respectively. `EncodeUtf16` wraps a &str, whereas `EncodeWide` wraps an &OsStr.

When Iteration has concluded, these iterators wrap an empty slice, which will forever yield `None` values. Hence, `EncodeUtf16` rightfully implements `FusedIterator`. However, `EncodeWide` in contrast does not, even though it serves an almost identical purpose.

This PR attempts to fix that issue. I consider this change minor and non-controversial, hence why I have not added a RFC/FCP. Please let me know if the stability attribute is wrong or contains a wrong version number. Thanks in advance.

Fixes https://github.com/rust-lang/rust/issues/96368
2022-04-28 02:40:33 +02:00
Josh Triplett 07ea143f96 Revert "Re-export core::ffi types from std::ffi"
This reverts commit 9aed829fe6.

Fixes https://github.com/rust-lang/rust/issues/96435 , a regression
in crates doing `use std::ffi::*;` and `use std::os::raw::*;`.

We can re-add this re-export once the `core::ffi` types
are stable, and thus the `std::os::raw` types can become re-exports as
well, which will avoid the conflict. (Type aliases to the same type
still conflict, but re-exports of the same type don't.)
2022-04-27 14:01:04 -07:00
David Tolnay 3a8f81aac9
Make [e]println macros eagerly drop temporaries (for backport) 2022-04-27 13:22:41 -07:00
Nixon Enraght-Moony d34f8d269a HashMap doc: Don't use monospace font for 'Entry Api' 2022-04-27 17:59:29 +01:00
Chris Denton 1e7c15634d
Note the importance of using sync pipes 2022-04-27 13:56:59 +01:00
bors bb85bcaca9 Auto merge of #96195 - sunfishcode:sunfishcode/handle-or-error-type, r=joshtriplett
Define a dedicated error type for `HandleOrNull` and `HandleOrInvalid`.

Define `NullHandleError` and `InvalidHandleError` types, that implement std::error::Error, and use them as the error types in `HandleOrNull` and `HandleOrInvalid`,

This addresses [this concern](https://github.com/rust-lang/rust/issues/87074#issuecomment-1080031167).

This is the same as #95387.

r? `@joshtriplett`
2022-04-27 03:42:59 +00:00
Chris Denton 949b978ec9
Windows: Make stdin pipes synchronous
Stdin pipes do not need to be used asynchronously within the standard library.
2022-04-26 16:31:27 +01:00
Chris Denton b89b056742
Add set_inheritable for Windows Handles 2022-04-26 15:56:26 +01:00
Eric Huss 159b95d5bb Remove references to git.io 2022-04-25 17:05:58 -07:00
Aron Parker fc6af819c4 Make EncodeWide implement FusedIterator 2022-04-25 18:38:47 +02:00
joboet 54daf496e2
std: directly use pthread in UNIX parker implementation
Mutex and Condvar are being replaced by more efficient implementations, which need thread parking themselves (see #93740). Therefore use the pthread synchronization primitives directly. Also, avoid allocating because the Parker struct is being placed in an Arc anyways.
2022-04-25 15:19:50 +02:00
bors 756ffb8d0b Auto merge of #95246 - ChrisDenton:command-args, r=joshtriplett
Windows Command: Don't run batch files using verbatim paths

Fixes #95178

Note that the first commit does some minor refactoring (moving command line argument building to args.rs). The actual changes are in the second.
2022-04-25 07:28:09 +00:00
bors 18f314e702 Auto merge of #94609 - esp-rs:esp-idf-stat-type-fixes, r=Mark-Simulacrum
espidf: fix stat

Marking as draft as currently dependant on [a libc fix](https://github.com/rust-lang/libc/pull/2708) and release.
2022-04-24 19:16:20 +00:00
bors 64c5deb0e3 Auto merge of #96314 - AronParker:issue-96297-fix, r=thomcc
Reduce allocations for path conversions on Windows

Previously, UTF-8 to UTF-16 Path conversions on Windows unnecessarily allocate twice, as described in #96297. This commit fixes that issue.
2022-04-23 04:17:50 +00:00
bors 8834629b86 Auto merge of #94887 - dylni:move-normpath-crate-impl-to-libstd, r=ChrisDenton
Improve Windows path prefix parsing

This PR fixes improves parsing of Windows path prefixes. `parse_prefix` now supports both types of separators on Windows (`/` and `\`).
2022-04-23 00:58:22 +00:00
Aron Parker 6cfdeaf1a1 Remove redundant type annotation 2022-04-22 11:42:53 +02:00