Commit Graph

13316 Commits

Author SHA1 Message Date
Ayush Singh
92d4060176
Implement SystemTime for UEFI
- Uses SystemTable->RuntimeServices->GetTime()

Signed-off-by: Ayush Singh <ayushdevel1325@gmail.com>
2024-02-09 00:21:36 +05:30
Matthias Krüger
8c6cf3c934
Rollup merge of #119305 - compiler-errors:async-fn-traits, r=oli-obk
Add `AsyncFn` family of traits

I'm proposing to add a new family of `async`hronous `Fn`-like traits to the standard library for experimentation purposes.

## Why do we need new traits?

On the user side, it is useful to be able to express `AsyncFn` trait bounds natively via the parenthesized sugar syntax, i.e. `x: impl AsyncFn(&str) -> String` when experimenting with async-closure code.

This also does not preclude `AsyncFn` becoming something else like a trait alias if a more fundamental desugaring (which can take many[^1] different[^2] forms) comes around. I think we should be able to play around with `AsyncFn` well before that, though.

I'm also not proposing stabilization of these trait names any time soon (we may even want to instead express them via new syntax, like `async Fn() -> ..`), but I also don't think we need to introduce an obtuse bikeshedding name, since `AsyncFn` just makes sense.

## The lending problem: why not add a more fundamental primitive of `LendingFn`/`LendingFnMut`?

Firstly, for `async` closures to be as flexible as possible, they must be allowed to return futures which borrow from the async closure's captures. This can be done by introducing `LendingFn`/`LendingFnMut` traits, or (equivalently) by adding a new generic associated type to `FnMut` which allows the return type to capture lifetimes from the `&mut self` argument of the trait. This was proposed in one of [Niko's blog posts](https://smallcultfollowing.com/babysteps/blog/2023/05/09/giving-lending-and-async-closures/).

Upon further experimentation, for the purposes of closure type- and borrow-checking, I've come to the conclusion that it's significantly harder to teach the compiler how to handle *general* lending closures which may borrow from their captures. This is, because unlike `Fn`/`FnMut`, the `LendingFn`/`LendingFnMut` traits don't form a simple "inheritance" hierarchy whose top trait is `FnOnce`.

```mermaid
flowchart LR
    Fn
    FnMut
    FnOnce
    LendingFn
    LendingFnMut

    Fn -- isa --> FnMut
    FnMut -- isa --> FnOnce

    LendingFn -- isa --> LendingFnMut

    Fn -- isa --> LendingFn
    FnMut -- isa --> LendingFnMut
```

For example:

```
fn main() {
  let s = String::from("hello, world");
  let f = move || &s;
  let x = f(); // This borrows `f` for some lifetime `'1` and returns `&'1 String`.
```

That trait hierarchy means that in general for "lending" closures, like `f` above, there's not really a meaningful return type for `<typeof(f) as FnOnce>::Output` -- it can't return `&'static str`, for example.

### Special-casing this problem:

By splitting out these traits manually, and making sure that each trait has its own associated future type, we side-step the issue of having to answer the questions of a general `LendingFn`/`LendingFnMut` implementation, since the compiler knows how to generate built-in implementations for first-class constructs like async closures, including the required future types for the (by-move) `AsyncFnOnce` and (by-ref) `AsyncFnMut`/`AsyncFn` trait implementations.

[^1]: For example, with trait transformers, we may eventually be able to write: `trait AsyncFn = async Fn;`
[^2]: For example, via the introduction of a more fundamental "`LendingFn`" trait, plus a [special desugaring with augmented trait aliases](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Lending.20closures.20and.20Fn*.28.29.20-.3E.20impl.20Trait/near/408471480).
2024-01-25 08:39:41 +01:00
bors
039d887928 Auto merge of #119911 - NCGThompson:is-statically-known, r=oli-obk
Replacement of #114390: Add new intrinsic `is_var_statically_known` and optimize pow for powers of two

This adds a new intrinsic `is_val_statically_known` that lowers to [``@llvm.is.constant.*`](https://llvm.org/docs/LangRef.html#llvm-is-constant-intrinsic).` It also applies the intrinsic in the int_pow methods to recognize and optimize the idiom `2isize.pow(x)`. See #114390 for more discussion.

While I have extended the scope of the power of two optimization from #114390, I haven't added any new uses for the intrinsic. That can be done in later pull requests.

Note: When testing or using the library, be sure to use `--stage 1` or higher. Otherwise, the intrinsic will be a noop and the doctests will be skipped. If you are trying out edits, you may be interested in [`--keep-stage 0`](https://rustc-dev-guide.rust-lang.org/building/suggested.html#faster-builds-with---keep-stage).

Fixes #47234
Resolves #114390
`@Centri3`
2024-01-25 05:16:53 +00:00
León Orell Valerian Liehr
e0a4f43903
Rollup merge of #119616 - rylev:wasm32-wasi-preview2, r=petrochenkov,m-ou-se
Add a new `wasm32-wasi-preview2` target

This is the initial implementation of the MCP https://github.com/rust-lang/compiler-team/issues/694 creating a new tier 3 target `wasm32-wasi-preview2`. That MCP has been seconded and will most likely be approved in a little over a week from now. For more information on the need for this target, please read the [MCP](https://github.com/rust-lang/compiler-team/issues/694).

There is one aspect of this PR that will become insta-stable once these changes reach a stable compiler:
* A new `target_family` named `wasi` is introduced. This target family incorporates all wasi targets including `wasm32-wasi` and its derivative `wasm32-wasi-preview1-threads`. The difference between `target_family = wasi` and `target_os = wasi` will become much clearer when `wasm32-wasi` is renamed to `wasm32-wasi-preview1` and the `target_os` becomes `wasm32-wasi-preview1`. You can read about this target rename in [this MCP](https://github.com/rust-lang/compiler-team/issues/695) which has also been seconded and will hopefully be officially approved soon.

Additional technical details include:
* Both `std::sys::wasi_preview2` and `std::os::wasi_preview2` have been created and mostly use `#[path]` annotations on their submodules to reach into the existing `wasi` (soon to be `wasi_preview1`) modules. Over time the differences between `wasi_preview1` and `wasi_preview2` will grow and most like all `#[path]` based module aliases will fall away.
* Building `wasi-preview2` relies on a [`wasi-sdk`](https://github.com/WebAssembly/wasi-sdk) in the same way that `wasi-preview1` does (one must include a `wasi-root` path in the `Config.toml` pointing to sysroot included in the wasi-sdk). The target should build against [wasi-sdk v21](https://github.com/WebAssembly/wasi-sdk/releases/tag/wasi-sdk-21) without modifications. However, the wasi-sdk itself is growing [preview2 support](https://github.com/WebAssembly/wasi-sdk/pull/370) so this might shift rapidly. We will be following along quickly to make sure that building the target remains possible as the wasi-sdk changes.
* This requires a [patch to libc](https://github.com/rylev/rust-libc/tree/wasm32-wasi-preview2) that we'll need to land in conjunction with this change. Until that patch lands the target won't actually build.
2024-01-24 15:43:12 +01:00
León Orell Valerian Liehr
3529d45b74
Rollup merge of #118326 - WaffleLapkin:nz_count_ones, r=scottmcm
Add `NonZero*::count_ones`

This PR adds the following APIs to the standard library:

```rust
impl NonZero* {
    pub const fn count_ones(self) -> NonZeroU32;
}
```

This is potentially interesting, given that `count_ones` can't ever return 0.

r? libs-api
2024-01-24 15:43:11 +01:00
Maybe Waffle
0b1d7ffbd4 Add NonZero*::count_ones 2024-01-24 00:15:14 +00:00
bors
0b7730105f Auto merge of #120283 - fmease:rollup-rk0f6r5, r=fmease
Rollup of 9 pull requests

Successful merges:

 - #112806 (Small code improvements in `collect_intra_doc_links.rs`)
 - #119766 (Split tait and impl trait in assoc items logic)
 - #120139 (Do not normalize closure signature when building `FnOnce` shim)
 - #120160 (Manually implement derived `NonZero` traits.)
 - #120171 (Fix assume and assert in jump threading)
 - #120183 (Add `#[coverage(off)]` to closures introduced by `#[test]` and `#[bench]`)
 - #120195 (add several resolution test cases)
 - #120259 (Split Diagnostics for Uncommon Codepoints: Add List to Display Characters Involved)
 - #120261 (Provide structured suggestion to use trait objects in some cases of `if` arm type divergence)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-23 22:44:44 +00:00
León Orell Valerian Liehr
ecb8702308
Rollup merge of #120183 - Zalathar:test-closure, r=compiler-errors
Add `#[coverage(off)]` to closures introduced by `#[test]` and `#[bench]`

These closures are an internal implementation detail of the `#[test]` and `#[bench]` attribute macros, so from a user perspective there is no reason to instrument them for coverage.

Skipping them makes coverage reports slightly cleaner, and will also allow other changes to span processing during coverage instrumentation, without having to worry about how they affect the `#[test]` macro.

The `#[coverage(off)]` attribute has no effect when `-Cinstrument-coverage` is not used.

Fixes #120046.

---

Note that this PR has no effect on the user-written function that has the `#[test]` attribute attached to it. That function will still be instrumented as normal.
2024-01-23 21:53:58 +01:00
León Orell Valerian Liehr
6cca9b33ec
Rollup merge of #120171 - cjgillot:jump-threading-assume-assert, r=tmiasko
Fix assume and assert in jump threading

r? ``@tmiasko``
2024-01-23 21:53:57 +01:00
León Orell Valerian Liehr
19a840d676
Rollup merge of #120160 - reitermarkus:nonzero-traits, r=dtolnay
Manually implement derived `NonZero` traits.

Step 3 as mentioned in https://github.com/rust-lang/rust/pull/100428#pullrequestreview-1767139731.

Manually implement the traits that would cause “borrow of layout constrained field with interior mutability” errors when switching to `NonZero<T>`.

r? ```@dtolnay```
2024-01-23 21:53:57 +01:00
León Orell Valerian Liehr
8fea4a8cab
Rollup merge of #120244 - reitermarkus:nonzero-self, r=dtolnay
Use `Self` in `NonZero*` implementations.

This slightly reduces the size of the eventual diff when making these generic, since this can be merged independently.
2024-01-23 21:19:54 +01:00
León Orell Valerian Liehr
1e5ec4d82a
Rollup merge of #120188 - devnexen:update_bsd_compiler_base_specs, r=wesleywiser
compiler: update freebsd and netbsd base specs.

both support thread local.
2024-01-23 21:19:53 +01:00
Nicholas Thompson
9dccd5dce1 Further Implement Power of Two Optimization 2024-01-23 12:03:50 -05:00
Nicholas Thompson
971e37ff7e Further Implement is_val_statically_known 2024-01-23 12:02:31 -05:00
bors
dfe53afaeb Auto merge of #119433 - taiki-e:rc-uninit-ref, r=Nilstrieb
rc,sync: Do not create references to uninitialized values

Closes #119241

r? `@RalfJung`
2024-01-23 16:43:45 +00:00
Ryan Levick
31ecf34125 Add the wasm32-wasi-preview2 target
Signed-off-by: Ryan Levick <me@ryanlevick.com>
2024-01-23 13:26:16 +01:00
bors
8b94152af6 Auto merge of #117958 - risc0:erik/target-triple, r=davidtwco,Mark-Simulacrum
riscv32im-risc0-zkvm-elf: add target

This pull request adds RISC Zero's Zero Knowledge Virtual Machine (zkVM) as a target for rust. The zkVM used to produce proofs of execution of RISC-V ELF binaries. In order to do this, the target will execute the ELF to generate a receipt containing the output of the computation along with a cryptographic seal. This receipt can be verified to ensure the integrity of the computation and its result. This target is implemented as software only; it has no hardware implementation.

## Tier 3 target policy:

Here is a copy of the tier 3 target policy:

> Tier 3 target policy:
>
> At this tier, the Rust project provides no official support for a target, so we
> place minimal requirements on the introduction of targets.
>
> A proposed new tier 3 target must be reviewed and approved by a member of the
> compiler team based on these requirements. The reviewer may choose to gauge
> broader compiler team consensus via a [[Major Change Proposal (MCP)](https://forge.rust-lang.org/compiler/mcp.html)](https://forge.rust-lang.org/compiler/mcp.html).
>
> A proposed target or target-specific patch that substantially changes code
> shared with other targets (not just target-specific code) must be reviewed and
> approved by the appropriate team for that shared code before acceptance.
>
> - A tier 3 target must have a designated developer or developers (the "target
> maintainers") on record to be CCed when issues arise regarding the target.
> (The mechanism to track and CC such developers may evolve over time.)

The maintainers are named in the target description file

> - Targets must use naming consistent with any existing targets; for instance, a
> target for the same CPU or OS as an existing Rust target should use the same
> name for that CPU or OS. Targets should normally use the same names and
> naming conventions as used elsewhere in the broader ecosystem beyond Rust
> (such as in other toolchains), unless they have a very good reason to
> diverge. Changing the name of a target can be highly disruptive, especially
> once the target reaches a higher tier, so getting the name right is important
> even for a tier 3 target.
> - Target names should not introduce undue confusion or ambiguity unless
> absolutely necessary to maintain ecosystem compatibility. For example, if
> the name of the target makes people extremely likely to form incorrect
> beliefs about what it targets, the name should be changed or augmented to
> disambiguate it.
> - If possible, use only letters, numbers, dashes and underscores for the name.
> Periods (`.`) are known to cause issues in Cargo.
>

We understand.

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

We understand and will not introduce incompatibilities. All of our code that we publish is licensed under Apache-2.0.

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

We understand. We are open to either license for the Rust repository.

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

We understand. The runtime libraries and the execution environment and software associated with this environment uses `Apache-2.0` so this should not be an issue.

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

We understand. We only depend on FOSS libraries. Dependencies such as runtime libraries for this target are licensed as `Apache-2.0`.

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

There are no such terms present

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

I am not the reviewer of this pull request

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

We understand.

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

The target implements core and alloc. And std support is currently experimental as some functionalities in std are either a) not applicable to our target or b) more work in research and experimentation needs to be done. For more information about the characteristics of this target, please refer to the target description file.

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

See file target description file

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

We understand.

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

We understand.

> - Patches adding or updating tier 3 targets must not break any existing tier 2
> or tier 1 target, and must not knowingly break another tier 3 target without
> approval of either the compiler team or the maintainers of the other tier 3
> target.
>     - In particular, this may come up when working on closely related targets,
>     such as variations of the same architecture with different features. Avoid
>     introducing unconditional uses of features that another variation of the
>     target may not have; use conditional compilation or runtime detection, as
>     appropriate, to let each target run code supported by that target.

We understand.

> If a tier 3 target stops meeting these requirements, or the target maintainers
> no longer have interest or time, or the target shows no signs of activity and
> has not built for some time, or removing the target would improve the quality
> of the Rust codebase, we may post a PR to remove it; any such PR will be CCed
> to the target maintainers (and potentially other people who have previously
> worked on the target), to check potential interest in improving the situation.

We understand.
2024-01-23 09:30:36 +00:00
bors
e35a56d96f Auto merge of #119892 - joboet:libs_use_assert_unchecked, r=Nilstrieb,cuviper
Use `assert_unchecked` instead of `assume` intrinsic in the standard library

Now that a public wrapper for the `assume` intrinsic exists, we can use it in the standard library.

CC #119131
2024-01-23 06:45:58 +00:00
Camille GILLOT
161c674ef0 Add Assume custom MIR. 2024-01-22 23:55:10 +00:00
David Carlier
ed4b99a99c fixing build for the BSD 2024-01-22 21:17:46 +00:00
Matthias Krüger
a787232abb
Rollup merge of #120233 - oli-obk:revert_trait_obj_upcast_stabilization, r=lcnr
Revert stabilization of trait_upcasting feature

Reverts #118133

This reverts commit 6d2b84b3ed, reversing changes made to 73bc12199e.

The feature has a soundness bug:

* #120222

It is unclear to me whether we'll actually want to destabilize, but I thought it was still prudent to open the PR for easy destabilization once we get there.
2024-01-22 22:12:10 +01:00
Matthias Krüger
a4307184be
Rollup merge of #120220 - nnethercote:TokenStream-Display-docs, r=petrochenkov
Document `Token{Stream,Tree}::Display` more thoroughly.

To expressly warn against the kind of proc macro implementation that was broken in #119875.

r? ``@petrochenkov``
2024-01-22 22:12:10 +01:00
Matthias Krüger
221115cbd6
Rollup merge of #120143 - compiler-errors:consolidate-instance-resolve-for-coroutines, r=oli-obk
Consolidate logic around resolving built-in coroutine trait impls

Deduplicates a lot of code. Requires defining a new lang item for `Coroutine::resume` for consistency, but it seems not harmful at worst, and potentially later useful at best.

r? oli-obk
2024-01-22 22:12:08 +01:00
Matthias Krüger
42e1db52ac
Rollup merge of #120109 - joboet:move_pal_cmath, r=ChrisDenton
Move cmath into `sys`

Part of #117276.

r? ``@ChrisDenton``
2024-01-22 22:12:08 +01:00
Matthias Krüger
67d093682c
Rollup merge of #119664 - ChrisDenton:mingw-pty, r=thomcc
Fix tty detection for msys2's `/dev/ptmx`

Our "true negative" detection assumes that if at least one std handle is a Windows console then no other handle will be a msys2 tty pipe. This turns out to be a faulty assumption in the case of redirection to  `/dev/ptmx` in an msys2 shell. Maybe this is an msys2 bug but in any case we should try to make it work.

An alternative to this would be to replace the "true negative" detection with an attempt to detect if we're in an msys environment (e.g. by sniffing environment variables) but that seems like it'd be flaky too.

Fixes #119658
2024-01-22 22:12:06 +01:00
Markus Reiter
a77cc2ce97
Use Self in NonZero* implementations. 2024-01-22 19:44:38 +01:00
bors
d5fd099729 Auto merge of #120242 - matthiaskrgr:rollup-a93yj3i, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #117910 (Refactor uses of `objc_msgSend` to no longer have clashing definitions)
 - #118639 (Undeprecate lint `unstable_features` and make use of it in the compiler)
 - #119801 (Fix deallocation with wrong allocator in (A)Rc::from_box_in)
 - #120058 (bootstrap: improvements for compiler builds)
 - #120059 (Make generic const type mismatches not hide trait impls from the trait solver)
 - #120097 (Report unreachable subpatterns consistently)
 - #120137 (Validate AggregateKind types in MIR)
 - #120164 (`maybe_lint_impl_trait`: separate `is_downgradable` from `is_object_safe`)
 - #120181 (Allow any `const` expression blocks in `thread_local!`)
 - #120218 (rustfmt: Check that a token can begin a nonterminal kind before parsing it as a macro arg)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 18:22:32 +00:00
Erik Kaneda
75d7d7091a
zkvm: add partial std support
Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: nils <nils@risc0.com>
Co-authored-by: Victor Graf <victor@risczero.com>
Co-authored-by: weikengchen <w.k@berkeley.edu>
2024-01-22 10:15:11 -08:00
Erik Kaneda
966b94e0a2
rustc: implement support for riscv32im_risc0_zkvm_elf
This also adds changes in the rust test suite in order to get a few of them to
pass.

Co-authored-by: Frank Laub <flaub@risc0.com>
Co-authored-by: Urgau <3616612+Urgau@users.noreply.github.com>
2024-01-22 10:07:36 -08:00
Matthias Krüger
d3761de43f
Rollup merge of #120181 - dtolnay:tlconst, r=thomcc
Allow any `const` expression blocks in `thread_local!`

This PR contains a rebase of the macro change from #116392, together with adding a test under library/std/tests.

Testing this feature by making the documentation's example code needlessly more complicated was not appropriate as pointed out in https://github.com/rust-lang/rust/pull/116392#pullrequestreview-1753097757.

Without the macro change, this new test would fail to build as follows:

```console
error: no rules expected the token `let`
   --> library/std/tests/thread.rs:26:13
    |
26  |             let value = 1;
    |             ^^^ no rules expected this token in macro call
    |
note: while trying to match meta-variable `$init:expr`
   --> library/std/src/thread/local.rs:189:69
    |
189 |     ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
    |                                                                     ^^^^^^^^^^
```

Closes #116392.
2024-01-22 16:55:00 +01:00
Matthias Krüger
97bcf0da7c
Rollup merge of #119801 - zachs18:zachs18-patch-1, r=steffahn,Nilstrieb
Fix deallocation with wrong allocator in (A)Rc::from_box_in

Deallocate the `Box` with the original allocator (via `&A`), not `Global`.

Fixes #119749

<details> <summary>Example code with error and Miri output</summary>

(Note that this UB is not observable on stable, because the only usable allocator on stable is `Global` anyway.)

Code ([playground link](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=96193c2c6a1912d7f669fbbe39174b09)):

```rs
#![feature(allocator_api)]
use std::alloc::System;

// uncomment one of these
use std::rc::Rc;
//use std::sync::Arc as Rc;

fn main() {
    let x: Box<[u32], System> = Box::new_in([1,2,3], System);
    let _: Rc<[u32], System> = Rc::from(x);
}
```

Miri output:

```rs
error: Undefined Behavior: deallocating alloc904, which is C heap memory, using Rust heap deallocation operation
   --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14
    |
117 |     unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) }
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ deallocating alloc904, which is C heap memory, using Rust heap deallocation operation
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
    = note: BACKTRACE:
    = note: inside `std::alloc::dealloc` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:117:14: 117:64
    = note: inside `<std::alloc::Global as std::alloc::Allocator>::deallocate` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:254:22: 254:51
    = note: inside `<std::boxed::Box<std::mem::ManuallyDrop<[u32]>> as std::ops::Drop>::drop` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:1244:17: 1244:66
    = note: inside `std::ptr::drop_in_place::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>> - shim(Some(std::boxed::Box<std::mem::ManuallyDrop<[u32]>>))` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:507:1: 507:56
    = note: inside `std::mem::drop::<std::boxed::Box<std::mem::ManuallyDrop<[u32]>>>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:992:24: 992:25
    = note: inside `std::rc::Rc::<[u32], std::alloc::System>::from_box_in` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:1928:13: 1928:22
    = note: inside `<std::rc::Rc<[u32], std::alloc::System> as std::convert::From<std::boxed::Box<[u32], std::alloc::System>>>::from` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/rc.rs:2504:9: 2504:27
note: inside `main`
   --> src/main.rs:10:32
    |
10  |     let _: Rc<[u32], System> = Rc::from(x);
    |                                ^^^^^^^^^^^

note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace

error: aborting due to 1 previous error
```

</details>
2024-01-22 16:54:57 +01:00
Matthias Krüger
e355b276bd
Rollup merge of #117910 - madsmtm:msg-send-no-clashing, r=thomcc
Refactor uses of `objc_msgSend` to no longer have clashing definitions

This is very similar to what Apple's own headers encourage you to do (cast the function pointer before use instead of making new declarations).

Additionally, I'm documenting a few of the memory management rules we're following, ensuring that the `args` function doesn't leak memory (if you wrap it in an autorelease pool).

Motivation is to avoid issues with clashing definitions, like described in https://github.com/rust-lang/rust/issues/12707#issuecomment-1570735643 and https://github.com/rust-lang/rust/issues/46188#issuecomment-1288058453, CC ``@bjorn3.``
2024-01-22 16:54:56 +01:00
Matthias Krüger
8c3c8bba03
Rollup merge of #119943 - devnexen:listener_update3, r=thomcc
std::net: bind update for using backlog as `-1` too.

Albeit not documented, macOs also support negative value for the backlog argument.

ref: 2ff845c2e0/bsd/kern/uipc_socket.c (L1061)
2024-01-22 16:13:27 +01:00
Matthias Krüger
e9c2e1bfbe
Rollup merge of #119408 - betrusted-io:xous-fixes-add-network, r=Mark-Simulacrum
xous: misc fixes + add network support

This patchset makes several fixes to Xous support. Additionally, this patch adds networking support.

Many of these fixes are the result of the recent patch to get `unwinding` support merged. As a result of this patch, we can now run rust tests. As a result of these tests, we now have 729 tests passing:

```
failures:
    env::tests::test
    env::tests::test_self_exe_path
    env::tests::vars_debug
    env::tests::vars_os_debug
    os::raw::tests::same
    path::tests::test_push
    path::tests::test_set_file_name
    time::tests::since_epoch
test result: FAILED. 729 passed; 8 failed; 1 ignored; 0 measured; 0 filtered out; finished in 214.54s
```

In the course of fixing several tests and getting the test sequence to reliably run, several issues were found. This patchset fixes those issues.
2024-01-22 16:13:26 +01:00
Matthias Krüger
99b4f80f73
Rollup merge of #118578 - mina86:c, r=dtolnay
core: introduce split_at{,_mut}_checked

Introduce split_at_checked and split_at_mut_checked methods to slices
types (including str) which are non-panicking versions of split_at and
split_at_mut  respectively.  This is analogous to get method being
non-panicking version of indexing.

- https://github.com/rust-lang/libs-team/issues/308
- https://github.com/rust-lang/rust/issues/119128
2024-01-22 16:13:24 +01:00
joboet
f88e64343e
std: move cmath into sys 2024-01-22 15:30:54 +01:00
Oli Scherer
9a20cf1697 Revert "Auto merge of #118133 - Urgau:stabilize_trait_upcasting, r=WaffleLapkin"
This reverts commit 6d2b84b3ed, reversing
changes made to 73bc12199e.
2024-01-22 14:24:31 +00:00
Chris Denton
e74c667a53
Fix msys2 tty detection for /dev/ptmx
Our "true negative" detection assumes that if at least one std handle is a Windows console then no other handle will be a msys2 tty pipe. This turns out to be a faulty assumption in the case of  `/dev/ptmx`.
2024-01-22 13:44:21 +00:00
bors
366d112fa6 Auto merge of #120226 - matthiaskrgr:rollup-9xwx0si, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #118714 ( Explanation that fields are being used when deriving `(Partial)Ord` on enums)
 - #119710 (Improve `let_underscore_lock`)
 - #119726 (Tweak Library Integer Division Docs)
 - #119746 (rustdoc: hide modals when resizing the sidebar)
 - #119986 (Fix error counting)
 - #120194 (Shorten `#[must_use]` Diagnostic Message for `Option::is_none`)
 - #120200 (Correct the anchor of an URL in an error message)
 - #120203 (Replace `#!/bin/bash` with `#!/usr/bin/env bash` in rust-installer tests)
 - #120212 (Give nnethercote more reviews)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 11:08:57 +00:00
bors
6fff796eac Auto merge of #120196 - matthiaskrgr:rollup-id2zocf, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #120005 (Update Readme)
 - #120045 (Un-hide `iter::repeat_n`)
 - #120128 (Make stable_mir::with_tables sound)
 - #120145 (fix: Drop guard was deallocating with the incorrect size)
 - #120158 (`rustc_mir_dataflow`: Restore removed exports)
 - #120167 (Capture the rationale for `-Zallow-features=` in bootstrap.py)
 - #120174 (Warn users about limited review for tier 2 and 3 code)
 - #120180 (Document some alternatives to `Vec::split_off`)

Failed merges:

 - #120171 (Fix assume and assert in jump threading)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-22 08:56:22 +00:00
Matthias Krüger
1df60b2257
Rollup merge of #120194 - HTGAzureX1212:HTGAzureX1212shorten-option-must-use, r=Nilstrieb
Shorten `#[must_use]` Diagnostic Message for `Option::is_none`

This shortens the `#[must_use]` diagnostics displayed, in light of the [review comment](https://github.com/rust-lang/rust/pull/62431/files#r300819839) on when this was originally added.
2024-01-22 07:56:43 +01:00
Matthias Krüger
7d7c2257d3
Rollup merge of #119726 - NCGThompson:div-overflow-doc, r=Nilstrieb
Tweak Library Integer Division Docs

Improved the documentation and diagnostics related to panicking in the division-like methods in std:

* For signed methods that can overflow, clarified "results in overflow" to "self is -1 and rhs is Self::MIN." This is more concise than saying "results in overflow" and then explaining how it could overflow.
* For floor/ceil_div, corrected the documentation and made it more like the documentation in other methods.
* For signed methods that can overflow, explicitly mention that they are not affected by compiler flags.
* Removed all unused rustc_inherit_overflow_checks attributes. The non-division-like operations will never overflow.
* Added track_caller attributes to all methods that can panic. The panic messages will always be correct. For example, division methods all have / before %.
* Edited the saturating_div documentation to be consistent with similar methods.
2024-01-22 07:56:42 +01:00
Matthias Krüger
6f7222c1e6
Rollup merge of #118714 - The-Ludwig:explain_ord_derive_enum_field, r=Nilstrieb
Explanation that fields are being used when deriving `(Partial)Ord` on enums

When deriving `std::cmp::Ord` or `std::cmp::PartialOrd` on enums, their fields are compared if the variants are equal.
This means that the last assertion in the following snipped panics.
```rust
use std::cmp::{PartialEq, Eq, PartialOrd, Ord};

#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Sizes {
    Small(usize),
    Big(usize),
}

fn main() {
    let a = Sizes::Big(3);
    let b = Sizes::Big(5);
    let c = Sizes::Small(10);
    assert!( c < a);
    assert_eq!(a, c);
}
```

This is more often expected behavior than not, and can be easily circumvented, as discussed in [this thread](https://users.rust-lang.org/t/how-to-sort-enum-variants/52291/4).
But it is addressed nowhere in the documentation, yet.
So I stumbled across this, as I personally did not expect fields being used in `PartialOrd`.
I added the explanation to the documentation.
2024-01-22 07:56:41 +01:00
Nicholas Nethercote
c4fc9ff0d3 Document Token{Stream,Tree}::Display more thoroughly.
To expressly warn against the kind of proc macro implementation that was
broken in #119875.
2024-01-22 13:31:52 +11:00
Michal Nazarewicz
50cbbef86a review 2024-01-21 20:12:00 +01:00
Markus Reiter
0e3035b512
Manually implement derived NonZero traits. 2024-01-21 16:28:50 +01:00
bors
d9d89fd53d Auto merge of #119807 - Emilgardis:track_caller_from_impl_into, r=Nilstrieb
Add `#[track_caller]` to the "From implies Into" impl

This pr implements what was mentioned in https://github.com/rust-lang/rust/issues/77474#issuecomment-1074480790

This follows from my URLO https://users.rust-lang.org/t/104497

```rust
#![allow(warnings)]
fn main() {
    // Gives a good location
    let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(|e| e.into()));

    // still doesn't work, gives location of `FnOnce::call_once()`
    let _: Result<(), Loc> = dbg!(Err::<(), _>(()).map_err(Into::into));
}

#[derive(Debug)]
pub struct Loc {
    pub l: &'static std::panic::Location<'static>,
}

impl From<()> for Loc {
    #[track_caller]
    fn from(_: ()) -> Self {
        Loc {
            l: std::panic::Location::caller(),
        }
    }
}
```
2024-01-21 14:17:25 +00:00
Zalathar
6d7e80c5bc Add #[coverage(off)] to closures introduced by #[test]/#[bench] 2024-01-21 23:17:00 +11:00
Matthias Krüger
3eb7fe32a1
Rollup merge of #120180 - Zalathar:vec-split-off-alternatives, r=dtolnay
Document some alternatives to `Vec::split_off`

One of the discussion points that came up in #119917 is that some people use `Vec::split_off` in cases where they probably shouldn't, because the alternatives (like `mem::take`) are hard to discover.

This PR adds some suggestions to the documentation of `split_off` that should point people towards alternatives that might be more appropriate for their use-case.

I've deliberately tried to keep these changes as simple and uncontroversial as possible, so that they don't depend on how the team decides to handle the concerns raised in #119917. That's why I haven't touched the existing documentation for `split_off`, and haven't added links to `split_off` to the documentation of other methods.
2024-01-21 12:28:55 +01:00
Matthias Krüger
4a941d384d
Rollup merge of #120145 - the8472:fix-inplace-dest-drop, r=cuviper
fix: Drop guard was deallocating with the incorrect size

InPlaceDstBufDrop holds onto the allocation before the shrinking happens which means it must deallocate the destination elements but the source allocation.

Thanks `@cuviper` for spotting this.
2024-01-21 12:28:53 +01:00