2018-04-06 07:34:45 +00:00
|
|
|
|
//! Manually manage memory through raw pointers.
|
2014-04-07 21:00:19 +00:00
|
|
|
|
//!
|
2020-12-19 13:23:59 +00:00
|
|
|
|
//! *[See also the pointer primitive types](pointer).*
|
2018-04-06 07:34:45 +00:00
|
|
|
|
//!
|
|
|
|
|
//! # Safety
|
|
|
|
|
//!
|
2018-08-29 12:34:59 +00:00
|
|
|
|
//! Many functions in this module take raw pointers as arguments and read from
|
|
|
|
|
//! or write to them. For this to be safe, these pointers must be *valid*.
|
|
|
|
|
//! Whether a pointer is valid depends on the operation it is used for
|
|
|
|
|
//! (read or write), and the extent of the memory that is accessed (i.e.,
|
|
|
|
|
//! how many bytes are read/written). Most functions use `*mut T` and `*const T`
|
|
|
|
|
//! to access only a single value, in which case the documentation omits the size
|
|
|
|
|
//! and implicitly assumes it to be `size_of::<T>()` bytes.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
//!
|
2019-02-09 21:23:30 +00:00
|
|
|
|
//! The precise rules for validity are not determined yet. The guarantees that are
|
2018-08-29 17:27:20 +00:00
|
|
|
|
//! provided at this point are very minimal:
|
2018-07-04 18:30:23 +00:00
|
|
|
|
//!
|
2018-08-29 12:34:59 +00:00
|
|
|
|
//! * A [null] pointer is *never* valid, not even for accesses of [size zero][zst].
|
2019-11-05 20:50:55 +00:00
|
|
|
|
//! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
|
2020-03-06 11:13:55 +00:00
|
|
|
|
//! be *dereferenceable*: the memory range of the given size starting at the pointer must all be
|
2019-11-05 08:55:33 +00:00
|
|
|
|
//! within the bounds of a single allocated object. Note that in Rust,
|
|
|
|
|
//! every (stack-allocated) variable is considered a separate allocated object.
|
2020-11-20 09:25:59 +00:00
|
|
|
|
//! * Even for operations of [size zero][zst], the pointer must not be pointing to deallocated
|
|
|
|
|
//! memory, i.e., deallocation makes pointers invalid even for zero-sized operations. However,
|
|
|
|
|
//! casting any non-zero integer *literal* to a pointer is valid for zero-sized accesses, even if
|
|
|
|
|
//! some memory happens to exist at that address and gets deallocated. This corresponds to writing
|
|
|
|
|
//! your own allocator: allocating zero-sized objects is not very hard. The canonical way to
|
|
|
|
|
//! obtain a pointer that is valid for zero-sized accesses is [`NonNull::dangling`].
|
2022-05-28 16:15:04 +00:00
|
|
|
|
//FIXME: mention `ptr::invalid` above, once it is stable.
|
2018-09-01 16:00:10 +00:00
|
|
|
|
//! * All accesses performed by functions in this module are *non-atomic* in the sense
|
|
|
|
|
//! of [atomic operations] used to synchronize between threads. This means it is
|
|
|
|
|
//! undefined behavior to perform two concurrent accesses to the same location from different
|
|
|
|
|
//! threads unless both accesses only read from memory. Notice that this explicitly
|
|
|
|
|
//! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
|
|
|
|
|
//! be used for inter-thread synchronization.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
//! * The result of casting a reference to a pointer is valid for as long as the
|
|
|
|
|
//! underlying object is live and no reference (just raw pointers) is used to
|
2022-11-05 03:28:54 +00:00
|
|
|
|
//! access the same memory. That is, reference and pointer accesses cannot be
|
|
|
|
|
//! interleaved.
|
2018-07-04 18:30:23 +00:00
|
|
|
|
//!
|
2018-10-22 16:21:55 +00:00
|
|
|
|
//! These axioms, along with careful use of [`offset`] for pointer arithmetic,
|
2018-08-29 17:27:20 +00:00
|
|
|
|
//! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
|
|
|
|
|
//! will be provided eventually, as the [aliasing] rules are being determined. For more
|
2018-07-04 18:30:23 +00:00
|
|
|
|
//! information, see the [book] as well as the section in the reference devoted
|
2018-06-17 09:45:38 +00:00
|
|
|
|
//! to [undefined behavior][ub].
|
2018-06-15 23:00:07 +00:00
|
|
|
|
//!
|
|
|
|
|
//! ## Alignment
|
2018-04-06 07:34:45 +00:00
|
|
|
|
//!
|
2018-09-01 15:50:54 +00:00
|
|
|
|
//! Valid raw pointers as defined above are not necessarily properly aligned (where
|
2018-09-11 05:30:30 +00:00
|
|
|
|
//! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
|
2018-08-31 15:01:53 +00:00
|
|
|
|
//! aligned to `mem::align_of::<T>()`). However, most functions require their
|
|
|
|
|
//! arguments to be properly aligned, and will explicitly state
|
2018-06-17 09:45:38 +00:00
|
|
|
|
//! this requirement in their documentation. Notable exceptions to this are
|
2018-06-05 18:22:40 +00:00
|
|
|
|
//! [`read_unaligned`] and [`write_unaligned`].
|
2018-05-24 03:55:39 +00:00
|
|
|
|
//!
|
2018-08-29 12:34:59 +00:00
|
|
|
|
//! When a function requires proper alignment, it does so even if the access
|
|
|
|
|
//! has size 0, i.e., even if memory is not actually touched. Consider using
|
|
|
|
|
//! [`NonNull::dangling`] in such cases.
|
|
|
|
|
//!
|
2021-03-27 18:26:10 +00:00
|
|
|
|
//! ## Allocated object
|
|
|
|
|
//!
|
|
|
|
|
//! For several operations, such as [`offset`] or field projections (`expr.field`), the notion of an
|
|
|
|
|
//! "allocated object" becomes relevant. An allocated object is a contiguous region of memory.
|
|
|
|
|
//! Common examples of allocated objects include stack-allocated variables (each variable is a
|
|
|
|
|
//! separate allocated object), heap allocations (each allocation created by the global allocator is
|
|
|
|
|
//! a separate allocated object), and `static` variables.
|
|
|
|
|
//!
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! # Strict Provenance
|
|
|
|
|
//!
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! **The following text is non-normative, insufficiently formal, and is an extremely strict
|
|
|
|
|
//! interpretation of provenance. It's ok if your code doesn't strictly conform to it.**
|
|
|
|
|
//!
|
|
|
|
|
//! [Strict Provenance][] is an experimental set of APIs that help tools that try
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! to validate the memory-safety of your program's execution. Notably this includes [Miri][]
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! and [CHERI][], which can detect when you access out of bounds memory or otherwise violate
|
|
|
|
|
//! Rust's memory model.
|
|
|
|
|
//!
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! Provenance must exist in some form for any programming
|
|
|
|
|
//! language compiled for modern computer architectures, but specifying a model for provenance
|
|
|
|
|
//! in a way that is useful to both compilers and programmers is an ongoing challenge.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! The [Strict Provenance][] experiment seeks to explore the question: *what if we just said you
|
|
|
|
|
//! couldn't do all the nasty operations that make provenance so messy?*
|
|
|
|
|
//!
|
|
|
|
|
//! What APIs would have to be removed? What APIs would have to be added? How much would code
|
|
|
|
|
//! have to change, and is it worse or better now? Would any patterns become truly inexpressible?
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! Could we carve out special exceptions for those patterns? Should we?
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
2022-03-31 13:56:36 +00:00
|
|
|
|
//! A secondary goal of this project is to see if we can disambiguate the many functions of
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! pointer<->integer casts enough for the definition of `usize` to be loosened so that it
|
|
|
|
|
//! isn't *pointer*-sized but address-space/offset/allocation-sized (we'll probably continue
|
|
|
|
|
//! to conflate these notions). This would potentially make it possible to more efficiently
|
|
|
|
|
//! target platforms where pointers are larger than offsets, such as CHERI and maybe some
|
2022-08-18 02:13:37 +00:00
|
|
|
|
//! segmented architectures.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! ## Provenance
|
|
|
|
|
//!
|
|
|
|
|
//! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
|
|
|
|
|
//!
|
|
|
|
|
//! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial
|
|
|
|
|
//! to say that a Use After Free is clearly Undefined Behaviour, even if you "get lucky"
|
|
|
|
|
//! and the freed memory gets reallocated before your read/write (in fact this is the
|
|
|
|
|
//! worst-case scenario, UAFs would be much less concerning if this didn't happen!).
|
|
|
|
|
//! To rationalize this claim, pointers need to somehow be *more* than just their addresses:
|
|
|
|
|
//! they must have provenance.
|
|
|
|
|
//!
|
|
|
|
|
//! When an allocation is created, that allocation has a unique Original Pointer. For alloc
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! APIs this is literally the pointer the call returns, and for local variables and statics,
|
|
|
|
|
//! this is the name of the variable/static. This is mildly overloading the term "pointer"
|
|
|
|
|
//! for the sake of brevity/exposition.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! The Original Pointer for an allocation is guaranteed to have unique access to the entire
|
|
|
|
|
//! allocation and *only* that allocation. In this sense, an allocation can be thought of
|
|
|
|
|
//! as a "sandbox" that cannot be broken into or out of. *Provenance* is the permission
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! to access an allocation's sandbox and has both a *spatial* and *temporal* component:
|
|
|
|
|
//!
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! * Spatial: A range of bytes that the pointer is allowed to access.
|
2022-03-28 17:16:04 +00:00
|
|
|
|
//! * Temporal: The lifetime (of the allocation) that access to these bytes is tied to.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! Spatial provenance makes sure you don't go beyond your sandbox, while temporal provenance
|
|
|
|
|
//! makes sure that you can't "get lucky" after your permission to access some memory
|
|
|
|
|
//! has been revoked (either through deallocations or borrows expiring).
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! Provenance is implicitly shared with all pointers transitively derived from
|
|
|
|
|
//! The Original Pointer through operations like [`offset`], borrowing, and pointer casts.
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! Some operations may *shrink* the derived provenance, limiting how much memory it can
|
|
|
|
|
//! access or how long it's valid for (i.e. borrowing a subfield and subslicing).
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! Shrinking provenance cannot be undone: even if you "know" there is a larger allocation, you
|
|
|
|
|
//! can't derive a pointer with a larger provenance. Similarly, you cannot "recombine"
|
|
|
|
|
//! two contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`).
|
|
|
|
|
//!
|
|
|
|
|
//! A reference to a value always has provenance over exactly the memory that field occupies.
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! A reference to a slice always has provenance over exactly the range that slice describes.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! If an allocation is deallocated, all pointers with provenance to that allocation become
|
|
|
|
|
//! invalidated, and effectively lose their provenance.
|
|
|
|
|
//!
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! The strict provenance experiment is mostly only interested in exploring stricter *spatial*
|
|
|
|
|
//! provenance. In this sense it can be thought of as a subset of the more ambitious and
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! formal [Stacked Borrows][] research project, which is what tools like [Miri][] are based on.
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! In particular, Stacked Borrows is necessary to properly describe what borrows are allowed
|
|
|
|
|
//! to do and when they become invalidated. This necessarily involves much more complex
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! *temporal* reasoning than simply identifying allocations. Adjusting APIs and code
|
|
|
|
|
//! for the strict provenance experiment will also greatly help Stacked Borrows.
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//!
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! ## Pointer Vs Addresses
|
|
|
|
|
//!
|
|
|
|
|
//! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
|
|
|
|
|
//!
|
|
|
|
|
//! One of the largest historical issues with trying to define provenance is that programmers
|
|
|
|
|
//! freely convert between pointers and integers. Once you allow for this, it generally becomes
|
|
|
|
|
//! impossible to accurately track and preserve provenance information, and you need to appeal
|
|
|
|
|
//! to very complex and unreliable heuristics. But of course, converting between pointers and
|
|
|
|
|
//! integers is very useful, so what can we do?
|
|
|
|
|
//!
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! Also did you know WASM is actually a "Harvard Architecture"? As in function pointers are
|
|
|
|
|
//! handled completely differently from data pointers? And we kind of just shipped Rust on WASM
|
|
|
|
|
//! without really addressing the fact that we let you freely convert between function pointers
|
|
|
|
|
//! and data pointers, because it mostly Just Works? Let's just put that on the "pointer casts
|
|
|
|
|
//! are dubious" pile.
|
|
|
|
|
//!
|
|
|
|
|
//! Strict Provenance attempts to square these circles by decoupling Rust's traditional conflation
|
2022-03-27 19:06:06 +00:00
|
|
|
|
//! of pointers and `usize` (and `isize`), and defining a pointer to semantically contain the
|
|
|
|
|
//! following information:
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
2022-03-31 13:56:36 +00:00
|
|
|
|
//! * The **address-space** it is part of (e.g. "data" vs "code" in WASM).
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! * The **address** it points to, which can be represented by a `usize`.
|
|
|
|
|
//! * The **provenance** it has, defining the memory it has permission to access.
|
|
|
|
|
//!
|
|
|
|
|
//! Under Strict Provenance, a usize *cannot* accurately represent a pointer, and converting from
|
|
|
|
|
//! a pointer to a usize is generally an operation which *only* extracts the address. It is
|
|
|
|
|
//! therefore *impossible* to construct a valid pointer from a usize because there is no way
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! to restore the address-space and provenance. In other words, pointer-integer-pointer
|
2022-08-18 02:13:37 +00:00
|
|
|
|
//! roundtrips are not possible (in the sense that the resulting pointer is not dereferenceable).
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! The key insight to making this model *at all* viable is the [`with_addr`][] method:
|
|
|
|
|
//!
|
|
|
|
|
//! ```text
|
|
|
|
|
//! /// Creates a new pointer with the given address.
|
|
|
|
|
//! ///
|
|
|
|
|
//! /// This performs the same operation as an `addr as ptr` cast, but copies
|
|
|
|
|
//! /// the *address-space* and *provenance* of `self` to the new pointer.
|
|
|
|
|
//! /// This allows us to dynamically preserve and propagate this important
|
|
|
|
|
//! /// information in a way that is otherwise impossible with a unary cast.
|
|
|
|
|
//! ///
|
|
|
|
|
//! /// This is equivalent to using `wrapping_offset` to offset `self` to the
|
|
|
|
|
//! /// given address, and therefore has all the same capabilities and restrictions.
|
|
|
|
|
//! pub fn with_addr(self, addr: usize) -> Self;
|
|
|
|
|
//! ```
|
|
|
|
|
//!
|
|
|
|
|
//! So you're still able to drop down to the address representation and do whatever
|
|
|
|
|
//! clever bit tricks you want *as long as* you're able to keep around a pointer
|
|
|
|
|
//! into the allocation you care about that can "reconstitute" the other parts of the pointer.
|
|
|
|
|
//! Usually this is very easy, because you only are taking a pointer, messing with the address,
|
|
|
|
|
//! and then immediately converting back to a pointer. To make this use case more ergonomic,
|
|
|
|
|
//! we provide the [`map_addr`][] method.
|
|
|
|
|
//!
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! To help make it clear that code is "following" Strict Provenance semantics, we also provide an
|
|
|
|
|
//! [`addr`][] method which promises that the returned address is not part of a
|
|
|
|
|
//! pointer-usize-pointer roundtrip. In the future we may provide a lint for pointer<->integer
|
|
|
|
|
//! casts to help you audit if your code conforms to strict provenance.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//!
|
|
|
|
|
//! ## Using Strict Provenance
|
|
|
|
|
//!
|
|
|
|
|
//! Most code needs no changes to conform to strict provenance, as the only really concerning
|
|
|
|
|
//! operation that *wasn't* obviously already Undefined Behaviour is casts from usize to a
|
|
|
|
|
//! pointer. For code which *does* cast a usize to a pointer, the scope of the change depends
|
|
|
|
|
//! on exactly what you're doing.
|
|
|
|
|
//!
|
|
|
|
|
//! In general you just need to make sure that if you want to convert a usize address to a
|
|
|
|
|
//! pointer and then use that pointer to read/write memory, you need to keep around a pointer
|
|
|
|
|
//! that has sufficient provenance to perform that read/write itself. In this way all of your
|
|
|
|
|
//! casts from an address to a pointer are essentially just applying offsets/indexing.
|
|
|
|
|
//!
|
|
|
|
|
//! This is generally trivial to do for simple cases like tagged pointers *as long as you
|
|
|
|
|
//! represent the tagged pointer as an actual pointer and not a usize*. For instance:
|
|
|
|
|
//!
|
|
|
|
|
//! ```
|
|
|
|
|
//! #![feature(strict_provenance)]
|
|
|
|
|
//!
|
|
|
|
|
//! unsafe {
|
|
|
|
|
//! // A flag we want to pack into our pointer
|
|
|
|
|
//! static HAS_DATA: usize = 0x1;
|
|
|
|
|
//! static FLAG_MASK: usize = !HAS_DATA;
|
|
|
|
|
//!
|
|
|
|
|
//! // Our value, which must have enough alignment to have spare least-significant-bits.
|
|
|
|
|
//! let my_precious_data: u32 = 17;
|
|
|
|
|
//! assert!(core::mem::align_of::<u32>() > 1);
|
|
|
|
|
//!
|
|
|
|
|
//! // Create a tagged pointer
|
|
|
|
|
//! let ptr = &my_precious_data as *const u32;
|
|
|
|
|
//! let tagged = ptr.map_addr(|addr| addr | HAS_DATA);
|
|
|
|
|
//!
|
|
|
|
|
//! // Check the flag:
|
|
|
|
|
//! if tagged.addr() & HAS_DATA != 0 {
|
|
|
|
|
//! // Untag and read the pointer
|
|
|
|
|
//! let data = *tagged.map_addr(|addr| addr & FLAG_MASK);
|
|
|
|
|
//! assert_eq!(data, 17);
|
|
|
|
|
//! } else {
|
|
|
|
|
//! unreachable!()
|
|
|
|
|
//! }
|
|
|
|
|
//! }
|
|
|
|
|
//! ```
|
|
|
|
|
//!
|
2022-03-27 19:06:06 +00:00
|
|
|
|
//! (Yes, if you've been using AtomicUsize for pointers in concurrent datastructures, you should
|
|
|
|
|
//! be using AtomicPtr instead. If that messes up the way you atomically manipulate pointers,
|
|
|
|
|
//! we would like to know why, and what needs to be done to fix it.)
|
|
|
|
|
//!
|
2022-03-31 13:56:36 +00:00
|
|
|
|
//! Something more complicated and just generally *evil* like an XOR-List requires more significant
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! changes like allocating all nodes in a pre-allocated Vec or Arena and using a pointer
|
|
|
|
|
//! to the whole allocation to reconstitute the XORed addresses.
|
|
|
|
|
//!
|
|
|
|
|
//! Situations where a valid pointer *must* be created from just an address, such as baremetal code
|
|
|
|
|
//! accessing a memory-mapped interface at a fixed address, are an open question on how to support.
|
|
|
|
|
//! These situations *will* still be allowed, but we might require some kind of "I know what I'm
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! doing" annotation to explain the situation to the compiler. It's also possible they need no
|
|
|
|
|
//! special attention at all, because they're generally accessing memory outside the scope of
|
|
|
|
|
//! "the abstract machine", or already using "I know what I'm doing" annotations like "volatile".
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
2022-03-31 13:56:36 +00:00
|
|
|
|
//! Under [Strict Provenance] it is Undefined Behaviour to:
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! * Access memory through a pointer that does not have provenance over that memory.
|
|
|
|
|
//!
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! * [`offset`] a pointer to or from an address it doesn't have provenance over.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! This means it's always UB to offset a pointer derived from something deallocated,
|
|
|
|
|
//! even if the offset is 0. Note that a pointer "one past the end" of its provenance
|
|
|
|
|
//! is not actually outside its provenance, it just has 0 bytes it can load/store.
|
|
|
|
|
//!
|
|
|
|
|
//! But it *is* still sound to:
|
|
|
|
|
//!
|
|
|
|
|
//! * Create an invalid pointer from just an address (see [`ptr::invalid`][]). This can
|
|
|
|
|
//! be used for sentinel values like `null` *or* to represent a tagged pointer that will
|
2022-08-18 02:13:37 +00:00
|
|
|
|
//! never be dereferenceable. In general, it is always sound for an integer to pretend
|
2022-03-27 19:06:06 +00:00
|
|
|
|
//! to be a pointer "for fun" as long as you don't use operations on it which require
|
|
|
|
|
//! it to be valid (offset, read, write, etc).
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//!
|
|
|
|
|
//! * Forge an allocation of size zero at any sufficiently aligned non-null address.
|
|
|
|
|
//! i.e. the usual "ZSTs are fake, do what you want" rules apply *but* this only applies
|
2022-03-27 19:06:06 +00:00
|
|
|
|
//! for actual forgery (integers cast to pointers). If you borrow some struct's field
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! that *happens* to be zero-sized, the resulting pointer will have provenance tied to
|
|
|
|
|
//! that allocation and it will still get invalidated if the allocation gets deallocated.
|
|
|
|
|
//! In the future we may introduce an API to make such a forged allocation explicit.
|
|
|
|
|
//!
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! * [`wrapping_offset`][] a pointer outside its provenance. This includes invalid pointers
|
|
|
|
|
//! which have "no" provenance. Unfortunately there may be practical limits on this for a
|
|
|
|
|
//! particular platform, and it's an open question as to how to specify this (if at all).
|
|
|
|
|
//! Notably, [CHERI][] relies on a compression scheme that can't handle a
|
|
|
|
|
//! pointer getting offset "too far" out of bounds. If this happens, the address
|
|
|
|
|
//! returned by `addr` will be the value you expect, but the provenance will get invalidated
|
|
|
|
|
//! and using it to read/write will fault. The details of this are architecture-specific
|
|
|
|
|
//! and based on alignment, but the buffer on either side of the pointer's range is pretty
|
|
|
|
|
//! generous (think kilobytes, not bytes).
|
|
|
|
|
//!
|
2022-03-27 19:06:06 +00:00
|
|
|
|
//! * Compare arbitrary pointers by address. Addresses *are* just integers and so there is
|
|
|
|
|
//! always a coherent answer, even if the pointers are invalid or from different
|
|
|
|
|
//! address-spaces/provenances. Of course, comparing addresses from different address-spaces
|
|
|
|
|
//! is generally going to be *meaningless*, but so is comparing Kilograms to Meters, and Rust
|
|
|
|
|
//! doesn't prevent that either. Similarly, if you get "lucky" and notice that a pointer
|
|
|
|
|
//! one-past-the-end is the "same" address as the start of an unrelated allocation, anything
|
|
|
|
|
//! you do with that fact is *probably* going to be gibberish. The scope of that gibberish
|
|
|
|
|
//! is kept under control by the fact that the two pointers *still* aren't allowed to access
|
|
|
|
|
//! the other's allocation (bytes), because they still have different provenance.
|
|
|
|
|
//!
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! * Perform pointer tagging tricks. This falls out of [`wrapping_offset`] but is worth
|
|
|
|
|
//! mentioning in more detail because of the limitations of [CHERI][]. Low-bit tagging
|
2022-03-28 04:37:28 +00:00
|
|
|
|
//! is very robust, and often doesn't even go out of bounds because types ensure
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! size >= align (and over-aligning actually gives CHERI more flexibility). Anything
|
|
|
|
|
//! more complex than this rapidly enters "extremely platform-specific" territory as
|
|
|
|
|
//! certain things may or may not be allowed based on specific supported operations.
|
|
|
|
|
//! For instance, ARM explicitly supports high-bit tagging, and so CHERI on ARM inherits
|
|
|
|
|
//! that and should support it.
|
|
|
|
|
//!
|
2023-11-30 20:45:57 +00:00
|
|
|
|
//! ## Exposed Provenance
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//!
|
2023-11-30 20:45:57 +00:00
|
|
|
|
//! **This section is *non-normative* and is an extension to the [Strict Provenance] experiment.**
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//!
|
|
|
|
|
//! As discussed above, pointer-usize-pointer roundtrips are not possible under [Strict Provenance].
|
2023-11-30 20:45:57 +00:00
|
|
|
|
//! This is by design: the goal of Strict Provenance is to provide a clear specification that we are
|
|
|
|
|
//! confident can be formalized unambiguously and can be subject to precise formal reasoning.
|
|
|
|
|
//!
|
|
|
|
|
//! However, there exist situations where pointer-usize-pointer roundtrips cannot be avoided, or
|
|
|
|
|
//! where avoiding them would require major refactoring. Legacy platform APIs also regularly assume
|
|
|
|
|
//! that `usize` can capture all the information that makes up a pointer. The goal of Strict
|
|
|
|
|
//! Provenance is not to rule out such code; the goal is to put all the *other* pointer-manipulating
|
|
|
|
|
//! code onto a more solid foundation. Strict Provenance is about improving the situation where
|
|
|
|
|
//! possible (all the code that can be written with Strict Provenance) without making things worse
|
|
|
|
|
//! for situations where Strict Provenance is insufficient.
|
|
|
|
|
//!
|
|
|
|
|
//! For these situations, there is a highly experimental extension to Strict Provenance called
|
|
|
|
|
//! *Exposed Provenance*. This extension permits pointer-usize-pointer roundtrips. However, its
|
|
|
|
|
//! semantics are on much less solid footing than Strict Provenance, and at this point it is not yet
|
|
|
|
|
//! clear where a satisfying unambiguous semantics can be defined for Exposed Provenance.
|
|
|
|
|
//! Furthermore, Exposed Provenance will not work (well) with tools like [Miri] and [CHERI].
|
|
|
|
|
//!
|
|
|
|
|
//! Exposed Provenance is provided by the [`expose_addr`] and [`from_exposed_addr`] methods, which
|
|
|
|
|
//! are meant to replace `as` casts between pointers and integers. [`expose_addr`] is a lot like
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! [`addr`], but additionally adds the provenance of the pointer to a global list of 'exposed'
|
|
|
|
|
//! provenances. (This list is purely conceptual, it exists for the purpose of specifying Rust but
|
|
|
|
|
//! is not materialized in actual executions, except in tools like [Miri].) [`from_exposed_addr`]
|
|
|
|
|
//! can be used to construct a pointer with one of these previously 'exposed' provenances.
|
|
|
|
|
//! [`from_exposed_addr`] takes only `addr: usize` as arguments, so unlike in [`with_addr`] there is
|
|
|
|
|
//! no indication of what the correct provenance for the returned pointer is -- and that is exactly
|
|
|
|
|
//! what makes pointer-usize-pointer roundtrips so tricky to rigorously specify! There is no
|
|
|
|
|
//! algorithm that decides which provenance will be used. You can think of this as "guessing" the
|
|
|
|
|
//! right provenance, and the guess will be "maximally in your favor", in the sense that if there is
|
|
|
|
|
//! any way to avoid undefined behavior, then that is the guess that will be taken. However, if
|
|
|
|
|
//! there is *no* previously 'exposed' provenance that justifies the way the returned pointer will
|
|
|
|
|
//! be used, the program has undefined behavior.
|
|
|
|
|
//!
|
2023-11-30 20:45:57 +00:00
|
|
|
|
//! Using [`expose_addr`] or [`from_exposed_addr`] (or the `as` casts) means that code is
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! *not* following Strict Provenance rules. The goal of the Strict Provenance experiment is to
|
2023-11-30 20:45:57 +00:00
|
|
|
|
//! determine how far one can get in Rust without the use of [`expose_addr`] and
|
|
|
|
|
//! [`from_exposed_addr`], and to encourage code to be written with Strict Provenance APIs only.
|
|
|
|
|
//! Maximizing the amount of such code is a major win for avoiding specification complexity and to
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! facilitate adoption of tools like [CHERI] and [Miri] that can be a big help in increasing the
|
|
|
|
|
//! confidence in (unsafe) Rust code.
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//!
|
2018-06-17 09:45:38 +00:00
|
|
|
|
//! [aliasing]: ../../nomicon/aliasing.html
|
2018-11-21 00:49:47 +00:00
|
|
|
|
//! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
|
2018-06-17 09:45:38 +00:00
|
|
|
|
//! [ub]: ../../reference/behavior-considered-undefined.html
|
2018-07-04 18:30:23 +00:00
|
|
|
|
//! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
|
2020-09-08 21:36:36 +00:00
|
|
|
|
//! [atomic operations]: crate::sync::atomic
|
2020-12-19 13:23:59 +00:00
|
|
|
|
//! [`offset`]: pointer::offset
|
2022-03-28 18:06:16 +00:00
|
|
|
|
//! [`wrapping_offset`]: pointer::wrapping_offset
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! [`with_addr`]: pointer::with_addr
|
|
|
|
|
//! [`map_addr`]: pointer::map_addr
|
|
|
|
|
//! [`addr`]: pointer::addr
|
|
|
|
|
//! [`ptr::invalid`]: core::ptr::invalid
|
2022-04-03 17:37:03 +00:00
|
|
|
|
//! [`expose_addr`]: pointer::expose_addr
|
|
|
|
|
//! [`from_exposed_addr`]: from_exposed_addr
|
|
|
|
|
//! [Miri]: https://github.com/rust-lang/miri
|
2022-03-22 05:27:28 +00:00
|
|
|
|
//! [CHERI]: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
|
|
|
|
|
//! [Strict Provenance]: https://github.com/rust-lang/rust/issues/95228
|
2022-03-26 19:55:05 +00:00
|
|
|
|
//! [Stacked Borrows]: https://plv.mpi-sws.org/rustbelt/stacked-borrows/
|
2012-03-10 08:04:09 +00:00
|
|
|
|
|
2015-01-24 05:48:20 +00:00
|
|
|
|
#![stable(feature = "rust1", since = "1.0.0")]
|
2014-12-19 16:57:12 +00:00
|
|
|
|
|
2019-12-08 20:22:18 +00:00
|
|
|
|
use crate::cmp::Ordering;
|
2019-04-15 02:23:21 +00:00
|
|
|
|
use crate::fmt;
|
|
|
|
|
use crate::hash;
|
2022-01-09 04:55:09 +00:00
|
|
|
|
use crate::intrinsics::{
|
|
|
|
|
self, assert_unsafe_precondition, is_aligned_and_not_null, is_nonoverlapping,
|
|
|
|
|
};
|
2023-04-21 13:33:04 +00:00
|
|
|
|
use crate::marker::FnPtr;
|
2022-01-09 04:55:09 +00:00
|
|
|
|
|
2019-04-15 02:23:21 +00:00
|
|
|
|
use crate::mem::{self, MaybeUninit};
|
2013-02-28 16:57:33 +00:00
|
|
|
|
|
2022-09-20 21:20:21 +00:00
|
|
|
|
mod alignment;
|
|
|
|
|
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
|
|
|
|
|
pub use alignment::Alignment;
|
|
|
|
|
|
2015-02-23 19:39:16 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2020-04-23 00:59:30 +00:00
|
|
|
|
#[doc(inline)]
|
2019-04-15 02:23:21 +00:00
|
|
|
|
pub use crate::intrinsics::copy_nonoverlapping;
|
2014-12-09 01:12:35 +00:00
|
|
|
|
|
2015-02-23 19:39:16 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2020-04-23 00:59:30 +00:00
|
|
|
|
#[doc(inline)]
|
2019-04-15 02:23:21 +00:00
|
|
|
|
pub use crate::intrinsics::copy;
|
2014-12-09 01:12:35 +00:00
|
|
|
|
|
2015-02-23 19:39:16 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2020-04-23 00:59:30 +00:00
|
|
|
|
#[doc(inline)]
|
2019-04-15 02:23:21 +00:00
|
|
|
|
pub use crate::intrinsics::write_bytes;
|
2014-12-03 22:21:51 +00:00
|
|
|
|
|
2020-10-19 13:38:11 +00:00
|
|
|
|
mod metadata;
|
2021-01-29 13:38:48 +00:00
|
|
|
|
#[unstable(feature = "ptr_metadata", issue = "81513")]
|
2021-01-18 15:19:29 +00:00
|
|
|
|
pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
|
2020-10-19 13:38:11 +00:00
|
|
|
|
|
2019-05-25 07:03:45 +00:00
|
|
|
|
mod non_null;
|
|
|
|
|
#[stable(feature = "nonnull", since = "1.25.0")]
|
|
|
|
|
pub use non_null::NonNull;
|
|
|
|
|
|
|
|
|
|
mod unique;
|
2019-12-21 11:16:18 +00:00
|
|
|
|
#[unstable(feature = "ptr_internals", issue = "none")]
|
2019-05-25 07:03:45 +00:00
|
|
|
|
pub use unique::Unique;
|
|
|
|
|
|
2019-12-08 20:22:18 +00:00
|
|
|
|
mod const_ptr;
|
|
|
|
|
mod mut_ptr;
|
|
|
|
|
|
2017-03-13 23:08:21 +00:00
|
|
|
|
/// Executes the destructor (if any) of the pointed-to value.
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// This is semantically equivalent to calling [`ptr::read`] and discarding
|
|
|
|
|
/// the result, but has the following advantages:
|
2017-03-13 23:08:21 +00:00
|
|
|
|
///
|
|
|
|
|
/// * It is *required* to use `drop_in_place` to drop unsized types like
|
|
|
|
|
/// trait objects, because they can't be read out onto the stack and
|
|
|
|
|
/// dropped normally.
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// * It is friendlier to the optimizer to do this over [`ptr::read`] when
|
2020-10-30 03:09:29 +00:00
|
|
|
|
/// dropping manually allocated memory (e.g., in the implementations of
|
|
|
|
|
/// `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
|
|
|
|
|
/// sound to elide the copy.
|
2017-03-13 23:08:21 +00:00
|
|
|
|
///
|
2020-04-27 21:50:55 +00:00
|
|
|
|
/// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
|
|
|
|
|
/// (pinned data must not be moved before it is dropped).
|
|
|
|
|
///
|
2019-07-03 18:13:42 +00:00
|
|
|
|
/// Unaligned values cannot be dropped in place, they must be copied to an aligned
|
2020-04-27 21:50:55 +00:00
|
|
|
|
/// location first using [`ptr::read_unaligned`]. For packed structs, this move is
|
|
|
|
|
/// done automatically by the compiler. This means the fields of packed structs
|
|
|
|
|
/// are not dropped in-place.
|
2019-07-03 18:13:42 +00:00
|
|
|
|
///
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// [`ptr::read`]: self::read
|
|
|
|
|
/// [`ptr::read_unaligned`]: self::read_unaligned
|
|
|
|
|
/// [pinned]: crate::pin
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2017-08-17 21:45:01 +00:00
|
|
|
|
/// # Safety
|
2017-03-13 23:08:21 +00:00
|
|
|
|
///
|
2023-05-21 15:34:01 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2020-02-14 23:34:15 +00:00
|
|
|
|
/// * `to_drop` must be [valid] for both reads and writes.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2023-05-20 21:46:47 +00:00
|
|
|
|
/// * `to_drop` must be properly aligned, even if `T` has size 0.
|
2022-11-17 23:40:46 +00:00
|
|
|
|
///
|
2023-05-20 21:46:47 +00:00
|
|
|
|
/// * `to_drop` must be nonnull, even if `T` has size 0.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2022-11-17 23:40:46 +00:00
|
|
|
|
/// * The value `to_drop` points to must be valid for dropping, which may mean
|
|
|
|
|
/// it must uphold additional invariants. These invariants depend on the type
|
|
|
|
|
/// of the value being dropped. For instance, when dropping a Box, the box's
|
|
|
|
|
/// pointer to the heap must be valid.
|
|
|
|
|
///
|
|
|
|
|
/// * While `drop_in_place` is executing, the only way to access parts of
|
|
|
|
|
/// `to_drop` is through the `&mut self` references supplied to the
|
|
|
|
|
/// `Drop::drop` methods that `drop_in_place` invokes.
|
2020-02-14 23:34:15 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Additionally, if `T` is not [`Copy`], using the pointed-to value after
|
|
|
|
|
/// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
|
2018-11-10 12:31:49 +00:00
|
|
|
|
/// foo` counts as a use because it will cause the value to be dropped
|
2020-09-09 02:24:57 +00:00
|
|
|
|
/// again. [`write()`] can be used to overwrite data without causing it to be
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// dropped.
|
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Manually remove the last item from a vector:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
/// use std::rc::Rc;
|
|
|
|
|
///
|
|
|
|
|
/// let last = Rc::new(1);
|
|
|
|
|
/// let weak = Rc::downgrade(&last);
|
|
|
|
|
///
|
|
|
|
|
/// let mut v = vec![Rc::new(0), last];
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
2018-08-31 16:25:42 +00:00
|
|
|
|
/// // Get a raw pointer to the last element in `v`.
|
|
|
|
|
/// let ptr = &mut v[1] as *mut _;
|
2019-02-09 21:23:30 +00:00
|
|
|
|
/// // Shorten `v` to prevent the last item from being dropped. We do that first,
|
2018-08-31 15:01:53 +00:00
|
|
|
|
/// // to prevent issues if the `drop_in_place` below panics.
|
|
|
|
|
/// v.set_len(1);
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// // Without a call `drop_in_place`, the last item would never be dropped,
|
|
|
|
|
/// // and the memory it manages would be leaked.
|
2018-08-31 16:25:42 +00:00
|
|
|
|
/// ptr::drop_in_place(ptr);
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(v, &[0.into()]);
|
|
|
|
|
///
|
|
|
|
|
/// // Ensure that the last item was dropped.
|
|
|
|
|
/// assert!(weak.upgrade().is_none());
|
|
|
|
|
/// ```
|
2017-03-13 23:08:21 +00:00
|
|
|
|
#[stable(feature = "drop_in_place", since = "1.8.0")]
|
2017-09-28 08:30:25 +00:00
|
|
|
|
#[lang = "drop_in_place"]
|
2017-03-13 23:08:21 +00:00
|
|
|
|
#[allow(unconditional_recursion)]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_drop_in_place"]
|
2020-01-16 21:18:17 +00:00
|
|
|
|
pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
|
2017-03-13 23:08:21 +00:00
|
|
|
|
// Code here does not matter - this is replaced by the
|
|
|
|
|
// real drop glue by the compiler.
|
2020-06-30 17:10:22 +00:00
|
|
|
|
|
|
|
|
|
// SAFETY: see comment above
|
|
|
|
|
unsafe { drop_in_place(to_drop) }
|
2017-03-13 23:08:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2022-02-14 19:05:45 +00:00
|
|
|
|
/// Creates a null raw pointer.
|
|
|
|
|
///
|
2023-10-20 17:10:16 +00:00
|
|
|
|
/// This function is equivalent to zero-initializing the pointer:
|
|
|
|
|
/// `MaybeUninit::<*const T>::zeroed().assume_init()`.
|
|
|
|
|
/// The resulting pointer has the address 0.
|
|
|
|
|
///
|
2022-02-14 19:05:45 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let p: *const i32 = ptr::null();
|
|
|
|
|
/// assert!(p.is_null());
|
2023-10-20 17:10:16 +00:00
|
|
|
|
/// assert_eq!(p as usize, 0); // this pointer has the address 0
|
2022-02-14 19:05:45 +00:00
|
|
|
|
/// ```
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
#[must_use]
|
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
|
#[rustc_promotable]
|
|
|
|
|
#[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
|
|
|
|
|
#[rustc_allow_const_fn_unstable(ptr_metadata)]
|
|
|
|
|
#[rustc_diagnostic_item = "ptr_null"]
|
|
|
|
|
pub const fn null<T: ?Sized + Thin>() -> *const T {
|
2022-06-05 15:44:12 +00:00
|
|
|
|
from_raw_parts(invalid(0), ())
|
2022-02-14 19:05:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2022-11-27 12:02:34 +00:00
|
|
|
|
/// Creates a null mutable raw pointer.
|
|
|
|
|
///
|
2023-10-20 17:10:16 +00:00
|
|
|
|
/// This function is equivalent to zero-initializing the pointer:
|
|
|
|
|
/// `MaybeUninit::<*mut T>::zeroed().assume_init()`.
|
|
|
|
|
/// The resulting pointer has the address 0.
|
|
|
|
|
///
|
2022-11-27 12:02:34 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let p: *mut i32 = ptr::null_mut();
|
|
|
|
|
/// assert!(p.is_null());
|
2023-10-20 17:10:16 +00:00
|
|
|
|
/// assert_eq!(p as usize, 0); // this pointer has the address 0
|
2022-11-27 12:02:34 +00:00
|
|
|
|
/// ```
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
#[must_use]
|
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
|
|
|
|
#[rustc_promotable]
|
|
|
|
|
#[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
|
|
|
|
|
#[rustc_allow_const_fn_unstable(ptr_metadata)]
|
|
|
|
|
#[rustc_diagnostic_item = "ptr_null_mut"]
|
|
|
|
|
pub const fn null_mut<T: ?Sized + Thin>() -> *mut T {
|
|
|
|
|
from_raw_parts_mut(invalid_mut(0), ())
|
|
|
|
|
}
|
|
|
|
|
|
2022-03-22 05:27:28 +00:00
|
|
|
|
/// Creates an invalid pointer with the given address.
|
|
|
|
|
///
|
2022-05-28 10:39:36 +00:00
|
|
|
|
/// This is different from `addr as *const T`, which creates a pointer that picks up a previously
|
|
|
|
|
/// exposed provenance. See [`from_exposed_addr`] for more details on that operation.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
///
|
2022-03-26 19:55:05 +00:00
|
|
|
|
/// The module's top-level documentation discusses the precise meaning of an "invalid"
|
2022-03-22 05:27:28 +00:00
|
|
|
|
/// pointer but essentially this expresses that the pointer is not associated
|
|
|
|
|
/// with any actual allocation and is little more than a usize address in disguise.
|
|
|
|
|
///
|
|
|
|
|
/// This pointer will have no provenance associated with it and is therefore
|
|
|
|
|
/// UB to read/write/offset. This mostly exists to facilitate things
|
2022-05-28 10:39:36 +00:00
|
|
|
|
/// like `ptr::null` and `NonNull::dangling` which make invalid pointers.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
///
|
2022-03-26 19:55:05 +00:00
|
|
|
|
/// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
|
|
|
|
|
/// may be desirable to give them their own API just to make that 100% clear.)
|
|
|
|
|
///
|
2022-03-22 05:27:28 +00:00
|
|
|
|
/// This API and its claimed semantics are part of the Strict Provenance experiment,
|
|
|
|
|
/// see the [module documentation][crate::ptr] for details.
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
#[must_use]
|
2022-03-31 19:46:30 +00:00
|
|
|
|
#[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")]
|
2022-03-22 05:27:28 +00:00
|
|
|
|
#[unstable(feature = "strict_provenance", issue = "95228")]
|
|
|
|
|
pub const fn invalid<T>(addr: usize) -> *const T {
|
|
|
|
|
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
|
2022-05-20 15:16:41 +00:00
|
|
|
|
// We use transmute rather than a cast so tools like Miri can tell that this
|
|
|
|
|
// is *not* the same as from_exposed_addr.
|
|
|
|
|
// SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
|
|
|
|
|
// pointer).
|
|
|
|
|
unsafe { mem::transmute(addr) }
|
2022-03-22 05:27:28 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Creates an invalid mutable pointer with the given address.
|
|
|
|
|
///
|
2022-05-28 10:39:36 +00:00
|
|
|
|
/// This is different from `addr as *mut T`, which creates a pointer that picks up a previously
|
|
|
|
|
/// exposed provenance. See [`from_exposed_addr_mut`] for more details on that operation.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
///
|
2022-03-26 19:55:05 +00:00
|
|
|
|
/// The module's top-level documentation discusses the precise meaning of an "invalid"
|
2022-03-22 05:27:28 +00:00
|
|
|
|
/// pointer but essentially this expresses that the pointer is not associated
|
|
|
|
|
/// with any actual allocation and is little more than a usize address in disguise.
|
|
|
|
|
///
|
|
|
|
|
/// This pointer will have no provenance associated with it and is therefore
|
|
|
|
|
/// UB to read/write/offset. This mostly exists to facilitate things
|
2022-05-28 10:39:36 +00:00
|
|
|
|
/// like `ptr::null` and `NonNull::dangling` which make invalid pointers.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
///
|
2022-03-26 19:55:05 +00:00
|
|
|
|
/// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
|
|
|
|
|
/// may be desirable to give them their own API just to make that 100% clear.)
|
|
|
|
|
///
|
2022-03-22 05:27:28 +00:00
|
|
|
|
/// This API and its claimed semantics are part of the Strict Provenance experiment,
|
|
|
|
|
/// see the [module documentation][crate::ptr] for details.
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
#[must_use]
|
2022-03-31 19:46:30 +00:00
|
|
|
|
#[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")]
|
2022-03-22 05:27:28 +00:00
|
|
|
|
#[unstable(feature = "strict_provenance", issue = "95228")]
|
|
|
|
|
pub const fn invalid_mut<T>(addr: usize) -> *mut T {
|
|
|
|
|
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
|
2022-05-20 15:16:41 +00:00
|
|
|
|
// We use transmute rather than a cast so tools like Miri can tell that this
|
|
|
|
|
// is *not* the same as from_exposed_addr.
|
|
|
|
|
// SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
|
|
|
|
|
// pointer).
|
|
|
|
|
unsafe { mem::transmute(addr) }
|
2019-12-07 04:18:12 +00:00
|
|
|
|
}
|
2012-09-14 23:12:18 +00:00
|
|
|
|
|
2022-04-03 17:37:03 +00:00
|
|
|
|
/// Convert an address back to a pointer, picking up a previously 'exposed' provenance.
|
|
|
|
|
///
|
2023-11-30 20:45:57 +00:00
|
|
|
|
/// This is a more rigorously specified alternative to `addr as *const T`. The provenance of the
|
|
|
|
|
/// returned pointer is that of *any* pointer that was previously exposed by passing it to
|
|
|
|
|
/// [`expose_addr`][pointer::expose_addr], or a `ptr as usize` cast. In addition, memory which is
|
|
|
|
|
/// outside the control of the Rust abstract machine (MMIO registers, for example) is always
|
|
|
|
|
/// considered to be exposed, so long as this memory is disjoint from memory that will be used by
|
|
|
|
|
/// the abstract machine such as the stack, heap, and statics.
|
2022-10-16 05:03:52 +00:00
|
|
|
|
///
|
|
|
|
|
/// If there is no 'exposed' provenance that justifies the way this pointer will be used,
|
|
|
|
|
/// the program has undefined behavior. In particular, the aliasing rules still apply: pointers
|
|
|
|
|
/// and references that have been invalidated due to aliasing accesses cannot be used any more,
|
|
|
|
|
/// even if they have been exposed!
|
2022-10-26 14:14:20 +00:00
|
|
|
|
///
|
2022-10-16 05:03:52 +00:00
|
|
|
|
/// Note that there is no algorithm that decides which provenance will be used. You can think of this
|
|
|
|
|
/// as "guessing" the right provenance, and the guess will be "maximally in your favor", in the sense
|
|
|
|
|
/// that if there is any way to avoid undefined behavior (while upholding all aliasing requirements),
|
|
|
|
|
/// then that is the guess that will be taken.
|
2022-04-03 17:37:03 +00:00
|
|
|
|
///
|
|
|
|
|
/// On platforms with multiple address spaces, it is your responsibility to ensure that the
|
|
|
|
|
/// address makes sense in the address space that this pointer will be used with.
|
|
|
|
|
///
|
2023-11-30 20:45:57 +00:00
|
|
|
|
/// Using this function means that code is *not* following [Strict
|
|
|
|
|
/// Provenance][../index.html#strict-provenance] rules. "Guessing" a
|
2022-04-03 17:37:03 +00:00
|
|
|
|
/// suitable provenance complicates specification and reasoning and may not be supported by
|
|
|
|
|
/// tools that help you to stay conformant with the Rust memory model, so it is recommended to
|
|
|
|
|
/// use [`with_addr`][pointer::with_addr] wherever possible.
|
|
|
|
|
///
|
|
|
|
|
/// On most platforms this will produce a value with the same bytes as the address. Platforms
|
|
|
|
|
/// which need to store additional information in a pointer may not support this operation,
|
|
|
|
|
/// since it is generally not possible to actually *compute* which provenance the returned
|
|
|
|
|
/// pointer has to pick up.
|
|
|
|
|
///
|
2023-11-30 20:45:57 +00:00
|
|
|
|
/// It is unclear whether this function can be given a satisfying unambiguous specification. This
|
|
|
|
|
/// API and its claimed semantics are part of [Exposed Provenance][../index.html#exposed-provenance].
|
2022-04-03 17:37:03 +00:00
|
|
|
|
#[must_use]
|
2022-12-07 16:11:17 +00:00
|
|
|
|
#[inline(always)]
|
2023-11-30 20:45:57 +00:00
|
|
|
|
#[unstable(feature = "exposed_provenance", issue = "95228")]
|
2022-08-13 16:55:43 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2023-11-30 20:45:57 +00:00
|
|
|
|
#[allow(fuzzy_provenance_casts)] // this *is* the explicit provenance API one should use instead
|
2022-04-03 17:37:03 +00:00
|
|
|
|
pub fn from_exposed_addr<T>(addr: usize) -> *const T
|
|
|
|
|
where
|
|
|
|
|
T: Sized,
|
|
|
|
|
{
|
|
|
|
|
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
|
|
|
|
|
addr as *const T
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Convert an address back to a mutable pointer, picking up a previously 'exposed' provenance.
|
|
|
|
|
///
|
2023-11-30 20:45:57 +00:00
|
|
|
|
/// This is a more rigorously specified alternative to `addr as *mut T`. The provenance of the
|
|
|
|
|
/// returned pointer is that of *any* pointer that was previously passed to
|
|
|
|
|
/// [`expose_addr`][pointer::expose_addr] or a `ptr as usize` cast. If there is no previously
|
|
|
|
|
/// 'exposed' provenance that justifies the way this pointer will be used, the program has undefined
|
|
|
|
|
/// behavior. Note that there is no algorithm that decides which provenance will be used. You can
|
|
|
|
|
/// think of this as "guessing" the right provenance, and the guess will be "maximally in your
|
|
|
|
|
/// favor", in the sense that if there is any way to avoid undefined behavior, then that is the
|
|
|
|
|
/// guess that will be taken.
|
2022-04-03 17:37:03 +00:00
|
|
|
|
///
|
|
|
|
|
/// On platforms with multiple address spaces, it is your responsibility to ensure that the
|
|
|
|
|
/// address makes sense in the address space that this pointer will be used with.
|
|
|
|
|
///
|
2023-11-30 20:45:57 +00:00
|
|
|
|
/// Using this function means that code is *not* following [Strict
|
|
|
|
|
/// Provenance][../index.html#strict-provenance] rules. "Guessing" a
|
2022-04-03 17:37:03 +00:00
|
|
|
|
/// suitable provenance complicates specification and reasoning and may not be supported by
|
|
|
|
|
/// tools that help you to stay conformant with the Rust memory model, so it is recommended to
|
|
|
|
|
/// use [`with_addr`][pointer::with_addr] wherever possible.
|
|
|
|
|
///
|
|
|
|
|
/// On most platforms this will produce a value with the same bytes as the address. Platforms
|
|
|
|
|
/// which need to store additional information in a pointer may not support this operation,
|
|
|
|
|
/// since it is generally not possible to actually *compute* which provenance the returned
|
|
|
|
|
/// pointer has to pick up.
|
|
|
|
|
///
|
2023-11-30 20:45:57 +00:00
|
|
|
|
/// It is unclear whether this function can be given a satisfying unambiguous specification. This
|
|
|
|
|
/// API and its claimed semantics are part of [Exposed Provenance][../index.html#exposed-provenance].
|
2022-04-03 17:37:03 +00:00
|
|
|
|
#[must_use]
|
2022-12-07 16:11:17 +00:00
|
|
|
|
#[inline(always)]
|
2023-11-30 20:45:57 +00:00
|
|
|
|
#[unstable(feature = "exposed_provenance", issue = "95228")]
|
2022-08-13 16:55:43 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2023-11-30 20:45:57 +00:00
|
|
|
|
#[allow(fuzzy_provenance_casts)] // this *is* the explicit provenance API one should use instead
|
2022-04-03 17:37:03 +00:00
|
|
|
|
pub fn from_exposed_addr_mut<T>(addr: usize) -> *mut T
|
|
|
|
|
where
|
|
|
|
|
T: Sized,
|
|
|
|
|
{
|
|
|
|
|
// FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
|
|
|
|
|
addr as *mut T
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-27 12:02:34 +00:00
|
|
|
|
/// Convert a reference to a raw pointer.
|
2022-02-14 19:05:45 +00:00
|
|
|
|
///
|
2022-11-27 12:02:34 +00:00
|
|
|
|
/// This is equivalent to `r as *const T`, but is a bit safer since it will never silently change
|
|
|
|
|
/// type or mutability, in particular if the code is refactored.
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
#[must_use]
|
2023-12-21 14:39:15 +00:00
|
|
|
|
#[stable(feature = "ptr_from_ref", since = "1.76.0")]
|
|
|
|
|
#[rustc_const_stable(feature = "ptr_from_ref", since = "1.76.0")]
|
2023-10-04 02:27:25 +00:00
|
|
|
|
#[rustc_never_returns_null_ptr]
|
2023-05-17 12:54:56 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_from_ref"]
|
2023-03-09 21:36:20 +00:00
|
|
|
|
pub const fn from_ref<T: ?Sized>(r: &T) -> *const T {
|
2022-11-27 12:02:34 +00:00
|
|
|
|
r
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-24 09:47:31 +00:00
|
|
|
|
/// Convert a mutable reference to a raw pointer.
|
2022-02-14 19:05:45 +00:00
|
|
|
|
///
|
2022-11-27 12:02:34 +00:00
|
|
|
|
/// This is equivalent to `r as *mut T`, but is a bit safer since it will never silently change
|
|
|
|
|
/// type or mutability, in particular if the code is refactored.
|
2022-02-14 19:05:45 +00:00
|
|
|
|
#[inline(always)]
|
|
|
|
|
#[must_use]
|
2023-12-21 14:39:15 +00:00
|
|
|
|
#[stable(feature = "ptr_from_ref", since = "1.76.0")]
|
|
|
|
|
#[rustc_const_stable(feature = "ptr_from_ref", since = "1.76.0")]
|
2023-11-11 11:33:10 +00:00
|
|
|
|
#[rustc_allow_const_fn_unstable(const_mut_refs)]
|
2023-10-04 02:27:25 +00:00
|
|
|
|
#[rustc_never_returns_null_ptr]
|
2023-03-09 21:36:20 +00:00
|
|
|
|
pub const fn from_mut<T: ?Sized>(r: &mut T) -> *mut T {
|
2022-11-27 12:02:34 +00:00
|
|
|
|
r
|
2022-02-14 19:05:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-11-05 08:32:47 +00:00
|
|
|
|
/// Forms a raw slice from a pointer and a length.
|
2019-06-19 07:21:44 +00:00
|
|
|
|
///
|
|
|
|
|
/// The `len` argument is the number of **elements**, not the number of bytes.
|
|
|
|
|
///
|
2019-11-05 08:32:47 +00:00
|
|
|
|
/// This function is safe, but actually using the return value is unsafe.
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
|
2019-11-05 08:32:47 +00:00
|
|
|
|
///
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
|
2019-11-05 08:32:47 +00:00
|
|
|
|
///
|
2019-06-19 07:21:44 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// // create a slice pointer when starting out with a pointer to the first element
|
2020-01-14 21:45:11 +00:00
|
|
|
|
/// let x = [5, 6, 7];
|
2020-04-23 20:22:27 +00:00
|
|
|
|
/// let raw_pointer = x.as_ptr();
|
|
|
|
|
/// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
|
2019-06-19 07:21:44 +00:00
|
|
|
|
/// assert_eq!(unsafe { &*slice }[2], 7);
|
|
|
|
|
/// ```
|
|
|
|
|
#[inline]
|
2020-01-14 21:45:11 +00:00
|
|
|
|
#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
|
2022-05-29 16:01:26 +00:00
|
|
|
|
#[rustc_const_stable(feature = "const_slice_from_raw_parts", since = "1.64.0")]
|
|
|
|
|
#[rustc_allow_const_fn_unstable(ptr_metadata)]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_slice_from_raw_parts"]
|
2019-12-20 20:42:03 +00:00
|
|
|
|
pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
|
2021-01-18 16:18:13 +00:00
|
|
|
|
from_raw_parts(data.cast(), len)
|
2019-06-19 07:21:44 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-11-05 08:32:47 +00:00
|
|
|
|
/// Performs the same functionality as [`slice_from_raw_parts`], except that a
|
2019-11-05 20:50:55 +00:00
|
|
|
|
/// raw mutable slice is returned, as opposed to a raw immutable slice.
|
2019-06-19 07:21:44 +00:00
|
|
|
|
///
|
2019-11-05 08:32:47 +00:00
|
|
|
|
/// See the documentation of [`slice_from_raw_parts`] for more details.
|
2019-06-19 07:21:44 +00:00
|
|
|
|
///
|
2019-11-05 08:32:47 +00:00
|
|
|
|
/// This function is safe, but actually using the return value is unsafe.
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
|
2019-11-05 08:32:47 +00:00
|
|
|
|
///
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
|
2020-04-23 20:32:20 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let x = &mut [5, 6, 7];
|
|
|
|
|
/// let raw_pointer = x.as_mut_ptr();
|
|
|
|
|
/// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// (*slice)[2] = 99; // assign a value at an index in the slice
|
|
|
|
|
/// };
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(unsafe { &*slice }[2], 99);
|
|
|
|
|
/// ```
|
2019-06-19 07:21:44 +00:00
|
|
|
|
#[inline]
|
2020-01-14 21:45:11 +00:00
|
|
|
|
#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
|
2022-05-29 16:01:26 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_slice_from_raw_parts_mut", issue = "67456")]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_slice_from_raw_parts_mut"]
|
2019-12-20 20:42:03 +00:00
|
|
|
|
pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
|
2021-01-18 16:18:13 +00:00
|
|
|
|
from_raw_parts_mut(data.cast(), len)
|
2019-06-19 07:21:44 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-12-09 01:12:35 +00:00
|
|
|
|
/// Swaps the values at two mutable locations of the same type, without
|
2017-12-03 23:02:17 +00:00
|
|
|
|
/// deinitializing either.
|
|
|
|
|
///
|
2022-06-03 21:10:12 +00:00
|
|
|
|
/// But for the following exceptions, this function is semantically
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// equivalent to [`mem::swap`]:
|
|
|
|
|
///
|
|
|
|
|
/// * It operates on raw pointers instead of references. When references are
|
|
|
|
|
/// available, [`mem::swap`] should be preferred.
|
|
|
|
|
///
|
|
|
|
|
/// * The two pointed-to values may overlap. If the values do overlap, then the
|
|
|
|
|
/// overlapping region of memory from `x` will be used. This is demonstrated
|
2018-09-18 19:14:31 +00:00
|
|
|
|
/// in the second example below.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2022-06-03 21:10:12 +00:00
|
|
|
|
/// * The operation is "untyped" in the sense that data may be uninitialized or otherwise violate
|
|
|
|
|
/// the requirements of `T`. The initialization state is preserved exactly.
|
|
|
|
|
///
|
2014-12-09 01:12:35 +00:00
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2023-09-05 15:20:31 +00:00
|
|
|
|
/// * Both `x` and `y` must be [valid] for both reads and writes. They must remain valid even when the
|
2023-08-21 11:54:03 +00:00
|
|
|
|
/// other pointer is written. (This means if the memory ranges overlap, the two pointers must not
|
|
|
|
|
/// be subject to aliasing restrictions relative to each other.)
|
2017-01-07 18:41:16 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// * Both `x` and `y` must be properly aligned.
|
2017-01-07 18:41:16 +00:00
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointers must be non-null and properly aligned.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2017-12-03 23:02:17 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Swapping two non-overlapping regions:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let mut array = [0, 1, 2, 3];
|
|
|
|
|
///
|
2022-04-03 17:23:27 +00:00
|
|
|
|
/// let (x, y) = array.split_at_mut(2);
|
|
|
|
|
/// let x = x.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[0..2]`
|
|
|
|
|
/// let y = y.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[2..4]`
|
2017-12-03 23:02:17 +00:00
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// ptr::swap(x, y);
|
|
|
|
|
/// assert_eq!([2, 3, 0, 1], array);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// Swapping two overlapping regions:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
2021-05-19 10:33:10 +00:00
|
|
|
|
/// let mut array: [i32; 4] = [0, 1, 2, 3];
|
|
|
|
|
///
|
|
|
|
|
/// let array_ptr: *mut i32 = array.as_mut_ptr();
|
2017-12-03 23:02:17 +00:00
|
|
|
|
///
|
2021-05-19 10:33:10 +00:00
|
|
|
|
/// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
|
|
|
|
|
/// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
|
2017-12-03 23:02:17 +00:00
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// ptr::swap(x, y);
|
2018-09-18 19:14:31 +00:00
|
|
|
|
/// // The indices `1..3` of the slice overlap between `x` and `y`.
|
|
|
|
|
/// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
|
|
|
|
|
/// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
|
|
|
|
|
/// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
|
|
|
|
|
/// // This implementation is defined to make the latter choice.
|
2017-12-03 23:02:17 +00:00
|
|
|
|
/// assert_eq!([1, 0, 1, 2], array);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2013-05-31 14:21:29 +00:00
|
|
|
|
#[inline]
|
2015-01-24 05:48:20 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2021-03-13 19:33:27 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_swap", issue = "83163")]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_swap"]
|
2021-03-13 19:33:27 +00:00
|
|
|
|
pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
|
2018-10-12 06:59:38 +00:00
|
|
|
|
// Give ourselves some scratch space to work with.
|
|
|
|
|
// We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
|
2019-03-18 21:45:02 +00:00
|
|
|
|
let mut tmp = MaybeUninit::<T>::uninit();
|
2013-05-31 14:21:29 +00:00
|
|
|
|
|
|
|
|
|
// Perform the swap
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `x` and `y` are
|
|
|
|
|
// valid for writes and properly aligned. `tmp` cannot be
|
|
|
|
|
// overlapping either `x` or `y` because `tmp` was just allocated
|
|
|
|
|
// on the stack as a separate allocated object.
|
|
|
|
|
unsafe {
|
|
|
|
|
copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
|
|
|
|
|
copy(y, x, 1); // `x` and `y` may overlap
|
|
|
|
|
copy_nonoverlapping(tmp.as_ptr(), y, 1);
|
|
|
|
|
}
|
2013-05-31 14:21:29 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-05-29 00:41:19 +00:00
|
|
|
|
/// Swaps `count * size_of::<T>()` bytes between the two regions of memory
|
|
|
|
|
/// beginning at `x` and `y`. The two regions must *not* overlap.
|
2017-06-21 06:48:15 +00:00
|
|
|
|
///
|
2022-06-03 21:10:12 +00:00
|
|
|
|
/// The operation is "untyped" in the sense that data may be uninitialized or otherwise violate the
|
|
|
|
|
/// requirements of `T`. The initialization state is preserved exactly.
|
|
|
|
|
///
|
2017-06-21 06:48:15 +00:00
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-05-29 00:41:19 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2020-02-15 12:58:54 +00:00
|
|
|
|
/// * Both `x` and `y` must be [valid] for both reads and writes of `count *
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// size_of::<T>()` bytes.
|
2018-05-29 00:41:19 +00:00
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * Both `x` and `y` must be properly aligned.
|
2018-05-29 00:41:19 +00:00
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * The region of memory beginning at `x` with a size of `count *
|
|
|
|
|
/// size_of::<T>()` bytes must *not* overlap with the region of memory
|
|
|
|
|
/// beginning at `y` with the same size.
|
2018-05-29 00:41:19 +00:00
|
|
|
|
///
|
2018-08-30 14:26:48 +00:00
|
|
|
|
/// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// the pointers must be non-null and properly aligned.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2017-06-21 06:48:15 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let mut x = [1, 2, 3, 4];
|
|
|
|
|
/// let mut y = [7, 8, 9];
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(x, [7, 8, 3, 4]);
|
|
|
|
|
/// assert_eq!(y, [1, 2, 9]);
|
|
|
|
|
/// ```
|
|
|
|
|
#[inline]
|
2018-04-17 04:36:13 +00:00
|
|
|
|
#[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
|
2021-03-13 19:33:27 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_swap", issue = "83163")]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_swap_nonoverlapping"]
|
2021-03-13 19:33:27 +00:00
|
|
|
|
pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
|
2022-02-27 02:57:15 +00:00
|
|
|
|
#[allow(unused)]
|
2022-02-21 07:25:18 +00:00
|
|
|
|
macro_rules! attempt_swap_as_chunks {
|
|
|
|
|
($ChunkTy:ty) => {
|
|
|
|
|
if mem::align_of::<T>() >= mem::align_of::<$ChunkTy>()
|
|
|
|
|
&& mem::size_of::<T>() % mem::size_of::<$ChunkTy>() == 0
|
|
|
|
|
{
|
2022-06-03 21:06:29 +00:00
|
|
|
|
let x: *mut $ChunkTy = x.cast();
|
|
|
|
|
let y: *mut $ChunkTy = y.cast();
|
2022-02-21 07:25:18 +00:00
|
|
|
|
let count = count * (mem::size_of::<T>() / mem::size_of::<$ChunkTy>());
|
|
|
|
|
// SAFETY: these are the same bytes that the caller promised were
|
|
|
|
|
// ok, just typed as `MaybeUninit<ChunkTy>`s instead of as `T`s.
|
|
|
|
|
// The `if` condition above ensures that we're not violating
|
|
|
|
|
// alignment requirements, and that the division is exact so
|
|
|
|
|
// that we don't lose any bytes off the end.
|
2022-06-03 21:06:29 +00:00
|
|
|
|
return unsafe { swap_nonoverlapping_simple_untyped(x, y, count) };
|
2022-02-21 07:25:18 +00:00
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
2017-06-21 06:48:15 +00:00
|
|
|
|
|
2022-01-09 04:55:09 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `x` and `y` are
|
|
|
|
|
// valid for writes and properly aligned.
|
|
|
|
|
unsafe {
|
2022-10-14 03:01:58 +00:00
|
|
|
|
assert_unsafe_precondition!(
|
|
|
|
|
"ptr::swap_nonoverlapping requires that both pointer arguments are aligned and non-null \
|
|
|
|
|
and the specified memory ranges do not overlap",
|
|
|
|
|
[T](x: *mut T, y: *mut T, count: usize) =>
|
2022-01-09 04:55:09 +00:00
|
|
|
|
is_aligned_and_not_null(x)
|
|
|
|
|
&& is_aligned_and_not_null(y)
|
|
|
|
|
&& is_nonoverlapping(x, y, count)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-06 13:20:09 +00:00
|
|
|
|
// Split up the slice into small power-of-two-sized chunks that LLVM is able
|
|
|
|
|
// to vectorize (unless it's a special type with more-than-pointer alignment,
|
|
|
|
|
// because we don't want to pessimize things like slices of SIMD vectors.)
|
|
|
|
|
if mem::align_of::<T>() <= mem::size_of::<usize>()
|
|
|
|
|
&& (!mem::size_of::<T>().is_power_of_two()
|
|
|
|
|
|| mem::size_of::<T>() > mem::size_of::<usize>() * 2)
|
2021-03-11 14:33:34 +00:00
|
|
|
|
{
|
2022-11-06 13:20:09 +00:00
|
|
|
|
attempt_swap_as_chunks!(usize);
|
|
|
|
|
attempt_swap_as_chunks!(u8);
|
2021-03-11 12:39:37 +00:00
|
|
|
|
}
|
|
|
|
|
|
2022-02-21 07:25:18 +00:00
|
|
|
|
// SAFETY: Same preconditions as this function
|
2022-06-03 21:06:29 +00:00
|
|
|
|
unsafe { swap_nonoverlapping_simple_untyped(x, y, count) }
|
2018-07-04 09:48:30 +00:00
|
|
|
|
}
|
|
|
|
|
|
2022-02-21 07:25:18 +00:00
|
|
|
|
/// Same behaviour and safety conditions as [`swap_nonoverlapping`]
|
|
|
|
|
///
|
|
|
|
|
/// LLVM can vectorize this (at least it can for the power-of-two-sized types
|
|
|
|
|
/// `swap_nonoverlapping` tries to use) so no need to manually SIMD it.
|
2017-06-21 06:48:15 +00:00
|
|
|
|
#[inline]
|
2021-03-13 19:33:27 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_swap", issue = "83163")]
|
2022-06-03 21:06:29 +00:00
|
|
|
|
const unsafe fn swap_nonoverlapping_simple_untyped<T>(x: *mut T, y: *mut T, count: usize) {
|
|
|
|
|
let x = x.cast::<MaybeUninit<T>>();
|
|
|
|
|
let y = y.cast::<MaybeUninit<T>>();
|
2017-06-21 06:48:15 +00:00
|
|
|
|
let mut i = 0;
|
2022-02-21 07:25:18 +00:00
|
|
|
|
while i < count {
|
2022-06-03 21:06:29 +00:00
|
|
|
|
// SAFETY: By precondition, `i` is in-bounds because it's below `n`
|
|
|
|
|
let x = unsafe { &mut *x.add(i) };
|
|
|
|
|
// SAFETY: By precondition, `i` is in-bounds because it's below `n`
|
|
|
|
|
// and it's distinct from `x` since the ranges are non-overlapping
|
|
|
|
|
let y = unsafe { &mut *y.add(i) };
|
2022-06-03 21:10:12 +00:00
|
|
|
|
mem::swap_simple::<MaybeUninit<T>>(x, y);
|
2020-06-30 17:10:22 +00:00
|
|
|
|
|
2022-02-21 07:25:18 +00:00
|
|
|
|
i += 1;
|
2017-06-21 06:48:15 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-30 14:26:48 +00:00
|
|
|
|
/// Moves `src` into the pointed `dst`, returning the previous `dst` value.
|
2018-05-28 12:36:14 +00:00
|
|
|
|
///
|
|
|
|
|
/// Neither value is dropped.
|
2014-12-09 01:12:35 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// This function is semantically equivalent to [`mem::replace`] except that it
|
|
|
|
|
/// operates on raw pointers instead of references. When references are
|
|
|
|
|
/// available, [`mem::replace`] should be preferred.
|
|
|
|
|
///
|
2014-12-09 01:12:35 +00:00
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2020-01-31 14:18:27 +00:00
|
|
|
|
/// * `dst` must be [valid] for both reads and writes.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2018-08-30 14:26:48 +00:00
|
|
|
|
/// * `dst` must be properly aligned.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2020-01-31 14:22:51 +00:00
|
|
|
|
/// * `dst` must point to a properly initialized value of type `T`.
|
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let mut rust = vec!['b', 'u', 's', 't'];
|
|
|
|
|
///
|
|
|
|
|
/// // `mem::replace` would have the same effect without requiring the unsafe
|
|
|
|
|
/// // block.
|
|
|
|
|
/// let b = unsafe {
|
|
|
|
|
/// ptr::replace(&mut rust[0], 'r')
|
|
|
|
|
/// };
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(b, 'b');
|
|
|
|
|
/// assert_eq!(rust, &['r', 'u', 's', 't']);
|
|
|
|
|
/// ```
|
2013-06-18 21:45:18 +00:00
|
|
|
|
#[inline]
|
2015-01-24 05:48:20 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2021-06-14 15:29:22 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_replace", issue = "83164")]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_replace"]
|
2021-06-14 15:29:22 +00:00
|
|
|
|
pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `dst` is valid to be
|
|
|
|
|
// cast to a mutable reference (valid for writes, aligned, initialized),
|
|
|
|
|
// and cannot overlap `src` since `dst` must point to a distinct
|
|
|
|
|
// allocated object.
|
|
|
|
|
unsafe {
|
2022-10-14 03:01:58 +00:00
|
|
|
|
assert_unsafe_precondition!(
|
|
|
|
|
"ptr::replace requires that the pointer argument is aligned and non-null",
|
|
|
|
|
[T](dst: *mut T) => is_aligned_and_not_null(dst)
|
|
|
|
|
);
|
2020-06-30 17:10:22 +00:00
|
|
|
|
mem::swap(&mut *dst, &mut src); // cannot overlap
|
|
|
|
|
}
|
2013-05-31 14:21:29 +00:00
|
|
|
|
src
|
|
|
|
|
}
|
|
|
|
|
|
2015-02-06 00:57:28 +00:00
|
|
|
|
/// Reads the value from `src` without moving it. This leaves the
|
2014-12-09 01:12:35 +00:00
|
|
|
|
/// memory in `src` unchanged.
|
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * `src` must be [valid] for reads.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
|
|
|
|
|
/// case.
|
2016-04-14 16:42:00 +00:00
|
|
|
|
///
|
2020-01-31 14:22:51 +00:00
|
|
|
|
/// * `src` must point to a properly initialized value of type `T`.
|
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// let x = 12;
|
|
|
|
|
/// let y = &x as *const i32;
|
|
|
|
|
///
|
2016-08-21 20:49:09 +00:00
|
|
|
|
/// unsafe {
|
|
|
|
|
/// assert_eq!(std::ptr::read(y), 12);
|
|
|
|
|
/// }
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// ```
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// Manually implement [`mem::swap`]:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// fn swap<T>(a: &mut T, b: &mut T) {
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// // Create a bitwise copy of the value at `a` in `tmp`.
|
|
|
|
|
/// let tmp = ptr::read(a);
|
|
|
|
|
///
|
|
|
|
|
/// // Exiting at this point (either by explicitly returning or by
|
|
|
|
|
/// // calling a function which panics) would cause the value in `tmp` to
|
|
|
|
|
/// // be dropped while the same value is still referenced by `a`. This
|
|
|
|
|
/// // could trigger undefined behavior if `T` is not `Copy`.
|
|
|
|
|
///
|
|
|
|
|
/// // Create a bitwise copy of the value at `b` in `a`.
|
|
|
|
|
/// // This is safe because mutable references cannot alias.
|
|
|
|
|
/// ptr::copy_nonoverlapping(b, a, 1);
|
|
|
|
|
///
|
|
|
|
|
/// // As above, exiting here could trigger undefined behavior because
|
|
|
|
|
/// // the same value is referenced by `a` and `b`.
|
|
|
|
|
///
|
|
|
|
|
/// // Move `tmp` into `b`.
|
|
|
|
|
/// ptr::write(b, tmp);
|
2018-09-17 13:14:19 +00:00
|
|
|
|
///
|
|
|
|
|
/// // `tmp` has been moved (`write` takes ownership of its second argument),
|
|
|
|
|
/// // so nothing is dropped implicitly here.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let mut foo = "foo".to_owned();
|
|
|
|
|
/// let mut bar = "bar".to_owned();
|
|
|
|
|
///
|
|
|
|
|
/// swap(&mut foo, &mut bar);
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(foo, "bar");
|
|
|
|
|
/// assert_eq!(bar, "foo");
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
2018-09-17 13:21:20 +00:00
|
|
|
|
/// ## Ownership of the Returned Value
|
|
|
|
|
///
|
|
|
|
|
/// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
|
|
|
|
|
/// If `T` is not [`Copy`], using both the returned value and the value at
|
2019-02-09 21:23:30 +00:00
|
|
|
|
/// `*src` can violate memory safety. Note that assigning to `*src` counts as a
|
2018-09-17 13:21:20 +00:00
|
|
|
|
/// use because it will attempt to drop the value at `*src`.
|
|
|
|
|
///
|
2020-09-09 02:24:57 +00:00
|
|
|
|
/// [`write()`] can be used to overwrite data without causing it to be dropped.
|
2018-09-17 13:21:20 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let mut s = String::from("foo");
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// // `s2` now points to the same underlying memory as `s`.
|
|
|
|
|
/// let mut s2: String = ptr::read(&s);
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(s2, "foo");
|
|
|
|
|
///
|
|
|
|
|
/// // Assigning to `s2` causes its original value to be dropped. Beyond
|
|
|
|
|
/// // this point, `s` must no longer be used, as the underlying memory has
|
|
|
|
|
/// // been freed.
|
|
|
|
|
/// s2 = String::default();
|
|
|
|
|
/// assert_eq!(s2, "");
|
|
|
|
|
///
|
|
|
|
|
/// // Assigning to `s` would cause the old value to be dropped again,
|
|
|
|
|
/// // resulting in undefined behavior.
|
|
|
|
|
/// // s = String::from("bar"); // ERROR
|
|
|
|
|
///
|
|
|
|
|
/// // `ptr::write` can be used to overwrite a value without dropping it.
|
|
|
|
|
/// ptr::write(&mut s, String::from("bar"));
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(s, "bar");
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2017-07-20 18:14:13 +00:00
|
|
|
|
#[inline]
|
2015-01-24 05:48:20 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2023-05-29 14:33:37 +00:00
|
|
|
|
#[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
|
2023-05-05 12:50:59 +00:00
|
|
|
|
#[rustc_allow_const_fn_unstable(const_mut_refs, const_maybe_uninit_as_mut_ptr)]
|
2022-07-20 20:42:20 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_read"]
|
2020-12-26 01:25:08 +00:00
|
|
|
|
pub const unsafe fn read<T>(src: *const T) -> T {
|
2023-03-12 22:52:34 +00:00
|
|
|
|
// It would be semantically correct to implement this via `copy_nonoverlapping`
|
2023-03-15 05:24:28 +00:00
|
|
|
|
// and `MaybeUninit`, as was done before PR #109035. Calling `assume_init`
|
|
|
|
|
// provides enough information to know that this is a typed operation.
|
2023-03-12 22:52:34 +00:00
|
|
|
|
|
2023-03-15 05:24:28 +00:00
|
|
|
|
// However, as of March 2023 the compiler was not capable of taking advantage
|
|
|
|
|
// of that information. Thus the implementation here switched to an intrinsic,
|
|
|
|
|
// which lowers to `_0 = *src` in MIR, to address a few issues:
|
2023-03-12 22:52:34 +00:00
|
|
|
|
//
|
|
|
|
|
// - Using `MaybeUninit::assume_init` after a `copy_nonoverlapping` was not
|
|
|
|
|
// turning the untyped copy into a typed load. As such, the generated
|
|
|
|
|
// `load` in LLVM didn't get various metadata, such as `!range` (#73258),
|
|
|
|
|
// `!nonnull`, and `!noundef`, resulting in poorer optimization.
|
|
|
|
|
// - Going through the extra local resulted in multiple extra copies, even
|
|
|
|
|
// in optimized MIR. (Ignoring StorageLive/Dead, the intrinsic is one
|
|
|
|
|
// MIR statement, while the previous implementation was eight.) LLVM
|
|
|
|
|
// could sometimes optimize them away, but because `read` is at the core
|
|
|
|
|
// of so many things, not having them in the first place improves what we
|
|
|
|
|
// hand off to the backend. For example, `mem::replace::<Big>` previously
|
|
|
|
|
// emitted 4 `alloca` and 6 `memcpy`s, but is now 1 `alloc` and 3 `memcpy`s.
|
|
|
|
|
// - In general, this approach keeps us from getting any more bugs (like
|
|
|
|
|
// #106369) that boil down to "`read(p)` is worse than `*p`", as this
|
|
|
|
|
// makes them look identical to the backend (or other MIR consumers).
|
|
|
|
|
//
|
|
|
|
|
// Future enhancements to MIR optimizations might well allow this to return
|
|
|
|
|
// to the previous implementation, rather than using an intrinsic.
|
2021-08-06 17:33:02 +00:00
|
|
|
|
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `src` is valid for reads.
|
|
|
|
|
unsafe {
|
2022-10-14 03:01:58 +00:00
|
|
|
|
assert_unsafe_precondition!(
|
|
|
|
|
"ptr::read requires that the pointer argument is aligned and non-null",
|
|
|
|
|
[T](src: *const T) => is_aligned_and_not_null(src)
|
|
|
|
|
);
|
2023-04-21 13:33:04 +00:00
|
|
|
|
crate::intrinsics::read_via_copy(src)
|
2020-06-30 17:10:22 +00:00
|
|
|
|
}
|
2013-06-20 19:13:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-12-12 02:51:22 +00:00
|
|
|
|
/// Reads the value from `src` without moving it. This leaves the
|
|
|
|
|
/// memory in `src` unchanged.
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Unlike [`read`], `read_unaligned` works with unaligned pointers.
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * `src` must be [valid] for reads.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2020-01-31 14:22:51 +00:00
|
|
|
|
/// * `src` must point to a properly initialized value of type `T`.
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
|
2019-02-09 21:23:30 +00:00
|
|
|
|
/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// value and the value at `*src` can [violate memory safety][read-ownership].
|
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// [read-ownership]: read#ownership-of-the-returned-value
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// ## On `packed` structs
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// Attempting to create a raw pointer to an `unaligned` struct field with
|
|
|
|
|
/// an expression such as `&packed.unaligned as *const FieldType` creates an
|
|
|
|
|
/// intermediate unaligned reference before converting that to a raw pointer.
|
|
|
|
|
/// That this reference is temporary and immediately cast is inconsequential
|
|
|
|
|
/// as the compiler always expects references to be properly aligned.
|
|
|
|
|
/// As a result, using `&packed.unaligned as *const FieldType` causes immediate
|
|
|
|
|
/// *undefined behavior* in your program.
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// Instead you must use the [`ptr::addr_of!`](addr_of) macro to
|
|
|
|
|
/// create the pointer. You may use that returned pointer together with this
|
|
|
|
|
/// function.
|
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// An example of what not to do and how this relates to `read_unaligned` is:
|
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// ```
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// #[repr(packed, C)]
|
|
|
|
|
/// struct Packed {
|
|
|
|
|
/// _padding: u8,
|
|
|
|
|
/// unaligned: u32,
|
2016-12-12 02:51:22 +00:00
|
|
|
|
/// }
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// let packed = Packed {
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// _padding: 0x00,
|
|
|
|
|
/// unaligned: 0x01020304,
|
|
|
|
|
/// };
|
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// // Take the address of a 32-bit integer which is not aligned.
|
|
|
|
|
/// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
|
|
|
|
|
/// let unaligned = std::ptr::addr_of!(packed.unaligned);
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// let v = unsafe { std::ptr::read_unaligned(unaligned) };
|
|
|
|
|
/// assert_eq!(v, 0x01020304);
|
2016-12-12 02:51:22 +00:00
|
|
|
|
/// ```
|
2019-07-03 02:05:05 +00:00
|
|
|
|
///
|
2019-07-04 07:54:37 +00:00
|
|
|
|
/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
|
2019-07-08 14:03:29 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
2021-08-22 16:15:49 +00:00
|
|
|
|
/// Read a usize value from a byte buffer:
|
2019-07-08 14:03:29 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::mem;
|
|
|
|
|
///
|
|
|
|
|
/// fn read_usize(x: &[u8]) -> usize {
|
|
|
|
|
/// assert!(x.len() >= mem::size_of::<usize>());
|
|
|
|
|
///
|
|
|
|
|
/// let ptr = x.as_ptr() as *const usize;
|
|
|
|
|
///
|
|
|
|
|
/// unsafe { ptr.read_unaligned() }
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-07-20 18:14:13 +00:00
|
|
|
|
#[inline]
|
2017-03-15 03:51:29 +00:00
|
|
|
|
#[stable(feature = "ptr_unaligned", since = "1.17.0")]
|
2023-05-29 14:33:37 +00:00
|
|
|
|
#[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
|
2023-05-05 12:50:59 +00:00
|
|
|
|
#[rustc_allow_const_fn_unstable(const_mut_refs, const_maybe_uninit_as_mut_ptr)]
|
2022-07-20 20:42:20 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_read_unaligned"]
|
2020-12-26 01:25:08 +00:00
|
|
|
|
pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
|
2019-03-18 21:45:02 +00:00
|
|
|
|
let mut tmp = MaybeUninit::<T>::uninit();
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `src` is valid for reads.
|
|
|
|
|
// `src` cannot overlap `tmp` because `tmp` was just allocated on
|
|
|
|
|
// the stack as a separate allocated object.
|
|
|
|
|
//
|
|
|
|
|
// Also, since we just wrote a valid value into `tmp`, it is guaranteed
|
|
|
|
|
// to be properly initialized.
|
|
|
|
|
unsafe {
|
|
|
|
|
copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
|
|
|
|
|
tmp.assume_init()
|
|
|
|
|
}
|
2016-12-12 02:51:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
2014-12-19 16:57:12 +00:00
|
|
|
|
/// Overwrites a memory location with the given value without reading or
|
|
|
|
|
/// dropping the old value.
|
2014-05-30 00:40:18 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// `write` does not drop the contents of `dst`. This is safe, but it could leak
|
2018-08-30 15:07:24 +00:00
|
|
|
|
/// allocations or resources, so care should be taken not to overwrite an object
|
2015-10-11 11:40:47 +00:00
|
|
|
|
/// that should be dropped.
|
2014-12-09 01:12:35 +00:00
|
|
|
|
///
|
2017-03-09 12:45:52 +00:00
|
|
|
|
/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
|
|
|
|
|
/// location pointed to by `dst`.
|
2017-03-07 22:39:49 +00:00
|
|
|
|
///
|
2015-01-07 01:53:18 +00:00
|
|
|
|
/// This is appropriate for initializing uninitialized memory, or overwriting
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// memory that has previously been [`read`] from.
|
2016-04-14 16:42:00 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
2016-04-14 16:42:00 +00:00
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * `dst` must be [valid] for writes.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
|
|
|
|
|
/// case.
|
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// let mut x = 0;
|
|
|
|
|
/// let y = &mut x as *mut i32;
|
|
|
|
|
/// let z = 12;
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// std::ptr::write(y, z);
|
2016-08-21 20:49:09 +00:00
|
|
|
|
/// assert_eq!(std::ptr::read(y), 12);
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// Manually implement [`mem::swap`]:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// fn swap<T>(a: &mut T, b: &mut T) {
|
|
|
|
|
/// unsafe {
|
2018-09-17 13:14:19 +00:00
|
|
|
|
/// // Create a bitwise copy of the value at `a` in `tmp`.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// let tmp = ptr::read(a);
|
2018-09-17 13:14:19 +00:00
|
|
|
|
///
|
|
|
|
|
/// // Exiting at this point (either by explicitly returning or by
|
|
|
|
|
/// // calling a function which panics) would cause the value in `tmp` to
|
|
|
|
|
/// // be dropped while the same value is still referenced by `a`. This
|
|
|
|
|
/// // could trigger undefined behavior if `T` is not `Copy`.
|
|
|
|
|
///
|
|
|
|
|
/// // Create a bitwise copy of the value at `b` in `a`.
|
|
|
|
|
/// // This is safe because mutable references cannot alias.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// ptr::copy_nonoverlapping(b, a, 1);
|
2018-09-17 13:14:19 +00:00
|
|
|
|
///
|
|
|
|
|
/// // As above, exiting here could trigger undefined behavior because
|
|
|
|
|
/// // the same value is referenced by `a` and `b`.
|
|
|
|
|
///
|
|
|
|
|
/// // Move `tmp` into `b`.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// ptr::write(b, tmp);
|
2018-09-17 13:14:19 +00:00
|
|
|
|
///
|
|
|
|
|
/// // `tmp` has been moved (`write` takes ownership of its second argument),
|
|
|
|
|
/// // so nothing is dropped implicitly here.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let mut foo = "foo".to_owned();
|
|
|
|
|
/// let mut bar = "bar".to_owned();
|
|
|
|
|
///
|
|
|
|
|
/// swap(&mut foo, &mut bar);
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(foo, "bar");
|
|
|
|
|
/// assert_eq!(bar, "foo");
|
|
|
|
|
/// ```
|
2014-05-30 00:40:18 +00:00
|
|
|
|
#[inline]
|
2015-01-24 05:48:20 +00:00
|
|
|
|
#[stable(feature = "rust1", since = "1.0.0")]
|
2021-06-14 17:58:34 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
|
2023-08-22 13:41:07 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_write"]
|
2022-07-20 20:42:20 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2021-06-14 15:29:22 +00:00
|
|
|
|
pub const unsafe fn write<T>(dst: *mut T, src: T) {
|
2023-04-30 06:32:40 +00:00
|
|
|
|
// Semantically, it would be fine for this to be implemented as a
|
|
|
|
|
// `copy_nonoverlapping` and appropriate drop suppression of `src`.
|
|
|
|
|
|
|
|
|
|
// However, implementing via that currently produces more MIR than is ideal.
|
|
|
|
|
// Using an intrinsic keeps it down to just the simple `*dst = move src` in
|
|
|
|
|
// MIR (11 statements shorter, at the time of writing), and also allows
|
|
|
|
|
// `src` to stay an SSA value in codegen_ssa, rather than a memory one.
|
2021-06-04 19:22:52 +00:00
|
|
|
|
|
2020-12-22 12:05:31 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `dst` is valid for writes.
|
|
|
|
|
// `dst` cannot overlap `src` because the caller has mutable access
|
|
|
|
|
// to `dst` while `src` is owned by this function.
|
|
|
|
|
unsafe {
|
2022-10-14 03:01:58 +00:00
|
|
|
|
assert_unsafe_precondition!(
|
|
|
|
|
"ptr::write requires that the pointer argument is aligned and non-null",
|
|
|
|
|
[T](dst: *mut T) => is_aligned_and_not_null(dst)
|
|
|
|
|
);
|
2023-04-30 06:32:40 +00:00
|
|
|
|
intrinsics::write_via_move(dst, src)
|
2020-06-06 09:56:58 +00:00
|
|
|
|
}
|
2014-05-30 00:40:18 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-12-12 02:51:22 +00:00
|
|
|
|
/// Overwrites a memory location with the given value without reading or
|
|
|
|
|
/// dropping the old value.
|
|
|
|
|
///
|
2020-09-09 02:24:57 +00:00
|
|
|
|
/// Unlike [`write()`], the pointer may be unaligned.
|
2018-05-17 17:19:41 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
|
2018-08-30 15:07:24 +00:00
|
|
|
|
/// could leak allocations or resources, so care should be taken not to overwrite
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// an object that should be dropped.
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2017-03-09 12:45:52 +00:00
|
|
|
|
/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
|
|
|
|
|
/// location pointed to by `dst`.
|
|
|
|
|
///
|
2016-12-12 02:51:22 +00:00
|
|
|
|
/// This is appropriate for initializing uninitialized memory, or overwriting
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// memory that has previously been read with [`read_unaligned`].
|
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * `dst` must be [valid] for writes.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// ## On `packed` structs
|
2016-12-12 02:51:22 +00:00
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// Attempting to create a raw pointer to an `unaligned` struct field with
|
|
|
|
|
/// an expression such as `&packed.unaligned as *const FieldType` creates an
|
|
|
|
|
/// intermediate unaligned reference before converting that to a raw pointer.
|
|
|
|
|
/// That this reference is temporary and immediately cast is inconsequential
|
|
|
|
|
/// as the compiler always expects references to be properly aligned.
|
|
|
|
|
/// As a result, using `&packed.unaligned as *const FieldType` causes immediate
|
|
|
|
|
/// *undefined behavior* in your program.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// Instead you must use the [`ptr::addr_of_mut!`](addr_of_mut)
|
|
|
|
|
/// macro to create the pointer. You may use that returned pointer together with
|
|
|
|
|
/// this function.
|
|
|
|
|
///
|
|
|
|
|
/// An example of how to do it and how this relates to `write_unaligned` is:
|
2019-07-03 02:05:05 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// ```
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// #[repr(packed, C)]
|
|
|
|
|
/// struct Packed {
|
|
|
|
|
/// _padding: u8,
|
|
|
|
|
/// unaligned: u32,
|
|
|
|
|
/// }
|
|
|
|
|
///
|
2019-07-03 02:05:05 +00:00
|
|
|
|
/// let mut packed: Packed = unsafe { std::mem::zeroed() };
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// // Take the address of a 32-bit integer which is not aligned.
|
|
|
|
|
/// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
|
|
|
|
|
/// let unaligned = std::ptr::addr_of_mut!(packed.unaligned);
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// unsafe { std::ptr::write_unaligned(unaligned, 42) };
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
|
2018-05-17 17:19:41 +00:00
|
|
|
|
/// ```
|
2019-07-03 02:05:05 +00:00
|
|
|
|
///
|
2021-03-27 10:44:39 +00:00
|
|
|
|
/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
|
|
|
|
|
/// (as can be seen in the `assert_eq!` above).
|
2019-07-08 14:03:29 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
2021-08-22 16:15:49 +00:00
|
|
|
|
/// Write a usize value to a byte buffer:
|
2019-07-08 14:03:29 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::mem;
|
|
|
|
|
///
|
|
|
|
|
/// fn write_usize(x: &mut [u8], val: usize) {
|
|
|
|
|
/// assert!(x.len() >= mem::size_of::<usize>());
|
|
|
|
|
///
|
|
|
|
|
/// let ptr = x.as_mut_ptr() as *mut usize;
|
|
|
|
|
///
|
|
|
|
|
/// unsafe { ptr.write_unaligned(val) }
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-12-12 02:51:22 +00:00
|
|
|
|
#[inline]
|
2017-03-15 03:51:29 +00:00
|
|
|
|
#[stable(feature = "ptr_unaligned", since = "1.17.0")]
|
2021-06-14 17:58:34 +00:00
|
|
|
|
#[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
|
2023-08-22 13:41:07 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_write_unaligned"]
|
2022-07-20 20:42:20 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2021-01-18 21:59:56 +00:00
|
|
|
|
pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must guarantee that `dst` is valid for writes.
|
|
|
|
|
// `dst` cannot overlap `src` because the caller has mutable access
|
|
|
|
|
// to `dst` while `src` is owned by this function.
|
|
|
|
|
unsafe {
|
|
|
|
|
copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
|
2021-01-18 21:59:56 +00:00
|
|
|
|
// We are calling the intrinsic directly to avoid function calls in the generated code.
|
|
|
|
|
intrinsics::forget(src);
|
2020-06-30 17:10:22 +00:00
|
|
|
|
}
|
2016-12-12 02:51:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-02-18 20:01:11 +00:00
|
|
|
|
/// Performs a volatile read of the value from `src` without moving it. This
|
|
|
|
|
/// leaves the memory in `src` unchanged.
|
|
|
|
|
///
|
|
|
|
|
/// Volatile operations are intended to act on I/O memory, and are guaranteed
|
|
|
|
|
/// to not be elided or reordered by the compiler across other volatile
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// operations.
|
2016-02-18 20:01:11 +00:00
|
|
|
|
///
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// # Notes
|
|
|
|
|
///
|
|
|
|
|
/// Rust does not currently have a rigorously and formally defined memory model,
|
|
|
|
|
/// so the precise semantics of what "volatile" means here is subject to change
|
|
|
|
|
/// over time. That being said, the semantics will almost always end up pretty
|
|
|
|
|
/// similar to [C11's definition of volatile][c11].
|
|
|
|
|
///
|
2017-08-13 09:28:04 +00:00
|
|
|
|
/// The compiler shouldn't change the relative order or number of volatile
|
|
|
|
|
/// memory operations. However, volatile memory operations on zero-sized types
|
2019-02-09 22:16:58 +00:00
|
|
|
|
/// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
|
2017-08-13 09:28:04 +00:00
|
|
|
|
/// and may be ignored.
|
2017-08-12 08:43:59 +00:00
|
|
|
|
///
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
|
2016-02-18 20:01:11 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * `src` must be [valid] for reads.
|
2018-04-06 07:34:45 +00:00
|
|
|
|
///
|
|
|
|
|
/// * `src` must be properly aligned.
|
|
|
|
|
///
|
2020-01-31 14:22:51 +00:00
|
|
|
|
/// * `src` must point to a properly initialized value of type `T`.
|
|
|
|
|
///
|
2019-05-18 16:03:12 +00:00
|
|
|
|
/// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
|
2019-02-09 21:23:30 +00:00
|
|
|
|
/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// value and the value at `*src` can [violate memory safety][read-ownership].
|
|
|
|
|
/// However, storing non-[`Copy`] types in volatile memory is almost certainly
|
|
|
|
|
/// incorrect.
|
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2020-09-08 21:36:36 +00:00
|
|
|
|
/// [read-ownership]: read#ownership-of-the-returned-value
|
2016-04-14 16:42:00 +00:00
|
|
|
|
///
|
2018-08-03 10:15:00 +00:00
|
|
|
|
/// Just like in C, whether an operation is volatile has no bearing whatsoever
|
|
|
|
|
/// on questions involving concurrent access from multiple threads. Volatile
|
|
|
|
|
/// accesses behave exactly like non-atomic accesses in that regard. In particular,
|
|
|
|
|
/// a race between a `read_volatile` and any write operation to the same location
|
|
|
|
|
/// is undefined behavior.
|
|
|
|
|
///
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// let x = 12;
|
|
|
|
|
/// let y = &x as *const i32;
|
|
|
|
|
///
|
2016-08-21 20:49:09 +00:00
|
|
|
|
/// unsafe {
|
|
|
|
|
/// assert_eq!(std::ptr::read_volatile(y), 12);
|
|
|
|
|
/// }
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// ```
|
2016-02-18 20:01:11 +00:00
|
|
|
|
#[inline]
|
2016-04-07 17:42:53 +00:00
|
|
|
|
#[stable(feature = "volatile", since = "1.9.0")]
|
2022-07-20 20:42:20 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_read_volatile"]
|
2016-02-18 20:01:11 +00:00
|
|
|
|
pub unsafe fn read_volatile<T>(src: *const T) -> T {
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must uphold the safety contract for `volatile_load`.
|
2022-01-09 04:55:09 +00:00
|
|
|
|
unsafe {
|
2022-10-14 03:01:58 +00:00
|
|
|
|
assert_unsafe_precondition!(
|
|
|
|
|
"ptr::read_volatile requires that the pointer argument is aligned and non-null",
|
|
|
|
|
[T](src: *const T) => is_aligned_and_not_null(src)
|
|
|
|
|
);
|
2022-01-09 04:55:09 +00:00
|
|
|
|
intrinsics::volatile_load(src)
|
|
|
|
|
}
|
2016-02-18 20:01:11 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Performs a volatile write of a memory location with the given value without
|
|
|
|
|
/// reading or dropping the old value.
|
|
|
|
|
///
|
|
|
|
|
/// Volatile operations are intended to act on I/O memory, and are guaranteed
|
|
|
|
|
/// to not be elided or reordered by the compiler across other volatile
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// operations.
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// `write_volatile` does not drop the contents of `dst`. This is safe, but it
|
2018-08-30 15:07:24 +00:00
|
|
|
|
/// could leak allocations or resources, so care should be taken not to overwrite
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// an object that should be dropped.
|
|
|
|
|
///
|
|
|
|
|
/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
|
|
|
|
|
/// location pointed to by `dst`.
|
|
|
|
|
///
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// # Notes
|
2016-02-18 20:01:11 +00:00
|
|
|
|
///
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// Rust does not currently have a rigorously and formally defined memory model,
|
|
|
|
|
/// so the precise semantics of what "volatile" means here is subject to change
|
|
|
|
|
/// over time. That being said, the semantics will almost always end up pretty
|
|
|
|
|
/// similar to [C11's definition of volatile][c11].
|
|
|
|
|
///
|
2017-08-13 09:28:04 +00:00
|
|
|
|
/// The compiler shouldn't change the relative order or number of volatile
|
|
|
|
|
/// memory operations. However, volatile memory operations on zero-sized types
|
2019-02-09 22:16:58 +00:00
|
|
|
|
/// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
|
2017-08-13 09:28:04 +00:00
|
|
|
|
/// and may be ignored.
|
2017-08-12 08:43:59 +00:00
|
|
|
|
///
|
2016-04-07 17:42:53 +00:00
|
|
|
|
/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
|
2016-02-18 20:01:11 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Safety
|
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// Behavior is undefined if any of the following conditions are violated:
|
2016-02-18 20:01:11 +00:00
|
|
|
|
///
|
2018-06-17 09:45:38 +00:00
|
|
|
|
/// * `dst` must be [valid] for writes.
|
2016-02-18 20:01:11 +00:00
|
|
|
|
///
|
2018-04-06 07:34:45 +00:00
|
|
|
|
/// * `dst` must be properly aligned.
|
|
|
|
|
///
|
2021-05-02 21:55:22 +00:00
|
|
|
|
/// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
|
2018-08-29 12:34:59 +00:00
|
|
|
|
///
|
2020-09-09 20:42:57 +00:00
|
|
|
|
/// [valid]: self#safety
|
2016-04-14 16:42:00 +00:00
|
|
|
|
///
|
2018-08-03 10:15:00 +00:00
|
|
|
|
/// Just like in C, whether an operation is volatile has no bearing whatsoever
|
|
|
|
|
/// on questions involving concurrent access from multiple threads. Volatile
|
|
|
|
|
/// accesses behave exactly like non-atomic accesses in that regard. In particular,
|
2020-09-09 02:24:57 +00:00
|
|
|
|
/// a race between a `write_volatile` and any other operation (reading or writing)
|
2018-08-03 10:15:00 +00:00
|
|
|
|
/// on the same location is undefined behavior.
|
|
|
|
|
///
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// Basic usage:
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// let mut x = 0;
|
|
|
|
|
/// let y = &mut x as *mut i32;
|
|
|
|
|
/// let z = 12;
|
|
|
|
|
///
|
|
|
|
|
/// unsafe {
|
|
|
|
|
/// std::ptr::write_volatile(y, z);
|
2016-08-21 20:49:09 +00:00
|
|
|
|
/// assert_eq!(std::ptr::read_volatile(y), 12);
|
2016-04-14 16:42:00 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-02-18 20:01:11 +00:00
|
|
|
|
#[inline]
|
2016-04-07 17:42:53 +00:00
|
|
|
|
#[stable(feature = "volatile", since = "1.9.0")]
|
2023-08-22 13:41:07 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_write_volatile"]
|
2022-07-20 20:42:20 +00:00
|
|
|
|
#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
|
2016-02-18 20:01:11 +00:00
|
|
|
|
pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
|
2020-06-30 17:10:22 +00:00
|
|
|
|
// SAFETY: the caller must uphold the safety contract for `volatile_store`.
|
|
|
|
|
unsafe {
|
2022-10-14 03:01:58 +00:00
|
|
|
|
assert_unsafe_precondition!(
|
|
|
|
|
"ptr::write_volatile requires that the pointer argument is aligned and non-null",
|
|
|
|
|
[T](dst: *mut T) => is_aligned_and_not_null(dst)
|
|
|
|
|
);
|
2020-06-30 17:10:22 +00:00
|
|
|
|
intrinsics::volatile_store(dst, src);
|
|
|
|
|
}
|
2016-02-18 20:01:11 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// Align pointer `p`.
|
|
|
|
|
///
|
2022-10-07 20:23:34 +00:00
|
|
|
|
/// Calculate offset (in terms of elements of `size_of::<T>()` stride) that has to be applied
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// to pointer `p` so that pointer `p` would get aligned to `a`.
|
|
|
|
|
///
|
2022-10-07 20:23:34 +00:00
|
|
|
|
/// # Safety
|
|
|
|
|
/// `a` must be a power of two.
|
|
|
|
|
///
|
|
|
|
|
/// # Notes
|
|
|
|
|
/// This implementation has been carefully tailored to not panic. It is UB for this to panic.
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
|
|
|
|
|
/// constants.
|
|
|
|
|
///
|
|
|
|
|
/// If we ever decide to make it possible to call the intrinsic with `a` that is not a
|
|
|
|
|
/// power-of-two, it will probably be more prudent to just change to a naive implementation rather
|
2018-08-19 13:30:23 +00:00
|
|
|
|
/// than trying to adapt this to accommodate that change.
|
2018-04-18 15:38:12 +00:00
|
|
|
|
///
|
|
|
|
|
/// Any questions go to @nagisa.
|
2019-12-07 04:18:12 +00:00
|
|
|
|
#[lang = "align_offset"]
|
2022-10-07 20:23:34 +00:00
|
|
|
|
pub(crate) const unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
|
2020-08-16 13:59:43 +00:00
|
|
|
|
// FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
|
|
|
|
|
// 1, where the method versions of these operations are not inlined.
|
Optimise align_offset for stride=1 further
`stride == 1` case can be computed more efficiently through `-p (mod
a)`. That, then translates to a nice and short sequence of LLVM
instructions:
%address = ptrtoint i8* %p to i64
%negptr = sub i64 0, %address
%offset = and i64 %negptr, %a_minus_one
And produces pretty much ideal code-gen when this function is used in
isolation.
Typical use of this function will, however, involve use of
the result to offset a pointer, i.e.
%aligned = getelementptr inbounds i8, i8* %p, i64 %offset
This still looks very good, but LLVM does not really translate that to
what would be considered ideal machine code (on any target). For example
that's the codegen we obtain for an unknown alignment:
; x86_64
dec rsi
mov rax, rdi
neg rax
and rax, rsi
add rax, rdi
In particular negating a pointer is not something that’s going to be
optimised for in the design of CISC architectures like x86_64. They
are much better at offsetting pointers. And so we’d love to utilize this
ability and produce code that's more like this:
; x86_64
lea rax, [rsi + rdi - 1]
neg rsi
and rax, rsi
To achieve this we need to give LLVM an opportunity to apply its
various peep-hole optimisations that it does during DAG selection. In
particular, the `and` instruction appears to be a major inhibitor here.
We cannot, sadly, get rid of this load-bearing operation, but we can
reorder operations such that LLVM has more to work with around this
instruction.
One such ordering is proposed in #75579 and results in LLVM IR that
looks broadly like this:
; using add enables `lea` and similar CISCisms
%offset_ptr = add i64 %address, %a_minus_one
%mask = sub i64 0, %a
%masked = and i64 %offset_ptr, %mask
; can be folded with `gepi` that may follow
%offset = sub i64 %masked, %address
…and generates the intended x86_64 machine code. One might also wonder
how the increased amount of code would impact a RISC target. Turns out
not much:
; aarch64 previous ; aarch64 new
sub x8, x1, #1 add x8, x1, x0
neg x9, x0 sub x8, x8, #1
and x8, x9, x8 neg x9, x1
add x0, x0, x8 and x0, x8, x9
(and similarly for ppc, sparc, mips, riscv, etc)
The only target that seems to do worse is… wasm32.
Onto actual measurements – the best way to evaluate snippets like these
is to use llvm-mca. Much like Aarch64 assembly would allow to suspect,
there isn’t any performance difference to be found. Both snippets
execute in same number of cycles for the CPUs I tried. On x86_64,
we get throughput improvement of >50%, however!
2020-08-20 00:38:00 +00:00
|
|
|
|
use intrinsics::{
|
2023-05-03 00:23:54 +00:00
|
|
|
|
assume, cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl,
|
|
|
|
|
unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
|
Optimise align_offset for stride=1 further
`stride == 1` case can be computed more efficiently through `-p (mod
a)`. That, then translates to a nice and short sequence of LLVM
instructions:
%address = ptrtoint i8* %p to i64
%negptr = sub i64 0, %address
%offset = and i64 %negptr, %a_minus_one
And produces pretty much ideal code-gen when this function is used in
isolation.
Typical use of this function will, however, involve use of
the result to offset a pointer, i.e.
%aligned = getelementptr inbounds i8, i8* %p, i64 %offset
This still looks very good, but LLVM does not really translate that to
what would be considered ideal machine code (on any target). For example
that's the codegen we obtain for an unknown alignment:
; x86_64
dec rsi
mov rax, rdi
neg rax
and rax, rsi
add rax, rdi
In particular negating a pointer is not something that’s going to be
optimised for in the design of CISC architectures like x86_64. They
are much better at offsetting pointers. And so we’d love to utilize this
ability and produce code that's more like this:
; x86_64
lea rax, [rsi + rdi - 1]
neg rsi
and rax, rsi
To achieve this we need to give LLVM an opportunity to apply its
various peep-hole optimisations that it does during DAG selection. In
particular, the `and` instruction appears to be a major inhibitor here.
We cannot, sadly, get rid of this load-bearing operation, but we can
reorder operations such that LLVM has more to work with around this
instruction.
One such ordering is proposed in #75579 and results in LLVM IR that
looks broadly like this:
; using add enables `lea` and similar CISCisms
%offset_ptr = add i64 %address, %a_minus_one
%mask = sub i64 0, %a
%masked = and i64 %offset_ptr, %mask
; can be folded with `gepi` that may follow
%offset = sub i64 %masked, %address
…and generates the intended x86_64 machine code. One might also wonder
how the increased amount of code would impact a RISC target. Turns out
not much:
; aarch64 previous ; aarch64 new
sub x8, x1, #1 add x8, x1, x0
neg x9, x0 sub x8, x8, #1
and x8, x9, x8 neg x9, x1
add x0, x0, x8 and x0, x8, x9
(and similarly for ppc, sparc, mips, riscv, etc)
The only target that seems to do worse is… wasm32.
Onto actual measurements – the best way to evaluate snippets like these
is to use llvm-mca. Much like Aarch64 assembly would allow to suspect,
there isn’t any performance difference to be found. Both snippets
execute in same number of cycles for the CPUs I tried. On x86_64,
we get throughput improvement of >50%, however!
2020-08-20 00:38:00 +00:00
|
|
|
|
};
|
2020-08-16 13:59:43 +00:00
|
|
|
|
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// Calculate multiplicative modular inverse of `x` modulo `m`.
|
|
|
|
|
///
|
2020-08-16 14:10:54 +00:00
|
|
|
|
/// This implementation is tailored for `align_offset` and has following preconditions:
|
2018-04-18 15:38:12 +00:00
|
|
|
|
///
|
|
|
|
|
/// * `m` is a power-of-two;
|
|
|
|
|
/// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
|
|
|
|
|
///
|
|
|
|
|
/// Implementation of this function shall not panic. Ever.
|
2018-05-03 21:49:22 +00:00
|
|
|
|
#[inline]
|
2022-10-07 20:23:34 +00:00
|
|
|
|
const unsafe fn mod_inv(x: usize, m: usize) -> usize {
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// Multiplicative modular inverse table modulo 2⁴ = 16.
|
|
|
|
|
///
|
2018-11-27 02:59:49 +00:00
|
|
|
|
/// Note, that this table does not contain values where inverse does not exist (i.e., for
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
|
2018-09-24 15:01:46 +00:00
|
|
|
|
const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
|
2018-04-18 15:38:12 +00:00
|
|
|
|
/// Modulo for which the `INV_TABLE_MOD_16` is intended.
|
|
|
|
|
const INV_TABLE_MOD: usize = 16;
|
|
|
|
|
|
2020-08-16 13:59:43 +00:00
|
|
|
|
// SAFETY: `m` is required to be a power-of-two, hence non-zero.
|
|
|
|
|
let m_minus_one = unsafe { unchecked_sub(m, 1) };
|
2022-10-22 00:03:48 +00:00
|
|
|
|
let mut inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
|
|
|
|
|
let mut mod_gate = INV_TABLE_MOD;
|
|
|
|
|
// We iterate "up" using the following formula:
|
|
|
|
|
//
|
|
|
|
|
// $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
|
|
|
|
|
//
|
|
|
|
|
// This application needs to be applied at least until `2²ⁿ ≥ m`, at which point we can
|
|
|
|
|
// finally reduce the computation to our desired `m` by taking `inverse mod m`.
|
|
|
|
|
//
|
|
|
|
|
// This computation is `O(log log m)`, which is to say, that on 64-bit machines this loop
|
|
|
|
|
// will always finish in at most 4 iterations.
|
|
|
|
|
loop {
|
|
|
|
|
// y = y * (2 - xy) mod n
|
2018-04-18 15:38:12 +00:00
|
|
|
|
//
|
2022-10-22 00:03:48 +00:00
|
|
|
|
// Note, that we use wrapping operations here intentionally – the original formula
|
|
|
|
|
// uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
|
|
|
|
|
// usize::MAX` instead, because we take the result `mod n` at the end
|
|
|
|
|
// anyway.
|
|
|
|
|
if mod_gate >= m {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
|
|
|
|
|
let (new_gate, overflow) = mul_with_overflow(mod_gate, mod_gate);
|
|
|
|
|
if overflow {
|
|
|
|
|
break;
|
2018-04-18 15:38:12 +00:00
|
|
|
|
}
|
2022-10-22 00:03:48 +00:00
|
|
|
|
mod_gate = new_gate;
|
2018-04-18 15:38:12 +00:00
|
|
|
|
}
|
2022-10-22 00:03:48 +00:00
|
|
|
|
inverse & m_minus_one
|
2018-04-18 15:38:12 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-04-15 02:23:21 +00:00
|
|
|
|
let stride = mem::size_of::<T>();
|
2022-10-07 20:23:34 +00:00
|
|
|
|
|
2022-11-16 14:08:35 +00:00
|
|
|
|
// SAFETY: This is just an inlined `p.addr()` (which is not
|
|
|
|
|
// a `const fn` so we cannot call it).
|
|
|
|
|
// During const eval, we hook this function to ensure that the pointer never
|
|
|
|
|
// has provenance, making this sound.
|
2022-11-16 10:41:18 +00:00
|
|
|
|
let addr: usize = unsafe { mem::transmute(p) };
|
|
|
|
|
|
2020-08-16 14:10:54 +00:00
|
|
|
|
// SAFETY: `a` is a power-of-two, therefore non-zero.
|
2020-08-16 13:59:43 +00:00
|
|
|
|
let a_minus_one = unsafe { unchecked_sub(a, 1) };
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
|
|
|
|
|
if stride == 0 {
|
|
|
|
|
// SPECIAL_CASE: handle 0-sized types. No matter how many times we step, the address will
|
|
|
|
|
// stay the same, so no offset will be able to align the pointer unless it is already
|
|
|
|
|
// aligned. This branch _will_ be optimized out as `stride` is known at compile-time.
|
|
|
|
|
let p_mod_a = addr & a_minus_one;
|
|
|
|
|
return if p_mod_a == 0 { 0 } else { usize::MAX };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SAFETY: `stride == 0` case has been handled by the special case above.
|
|
|
|
|
let a_mod_stride = unsafe { unchecked_rem(a, stride) };
|
|
|
|
|
if a_mod_stride == 0 {
|
|
|
|
|
// SPECIAL_CASE: In cases where the `a` is divisible by `stride`, byte offset to align a
|
|
|
|
|
// pointer can be computed more simply through `-p (mod a)`. In the off-chance the byte
|
|
|
|
|
// offset is not a multiple of `stride`, the input pointer was misaligned and no pointer
|
|
|
|
|
// offset will be able to produce a `p` aligned to the specified `a`.
|
Optimise align_offset for stride=1 further
`stride == 1` case can be computed more efficiently through `-p (mod
a)`. That, then translates to a nice and short sequence of LLVM
instructions:
%address = ptrtoint i8* %p to i64
%negptr = sub i64 0, %address
%offset = and i64 %negptr, %a_minus_one
And produces pretty much ideal code-gen when this function is used in
isolation.
Typical use of this function will, however, involve use of
the result to offset a pointer, i.e.
%aligned = getelementptr inbounds i8, i8* %p, i64 %offset
This still looks very good, but LLVM does not really translate that to
what would be considered ideal machine code (on any target). For example
that's the codegen we obtain for an unknown alignment:
; x86_64
dec rsi
mov rax, rdi
neg rax
and rax, rsi
add rax, rdi
In particular negating a pointer is not something that’s going to be
optimised for in the design of CISC architectures like x86_64. They
are much better at offsetting pointers. And so we’d love to utilize this
ability and produce code that's more like this:
; x86_64
lea rax, [rsi + rdi - 1]
neg rsi
and rax, rsi
To achieve this we need to give LLVM an opportunity to apply its
various peep-hole optimisations that it does during DAG selection. In
particular, the `and` instruction appears to be a major inhibitor here.
We cannot, sadly, get rid of this load-bearing operation, but we can
reorder operations such that LLVM has more to work with around this
instruction.
One such ordering is proposed in #75579 and results in LLVM IR that
looks broadly like this:
; using add enables `lea` and similar CISCisms
%offset_ptr = add i64 %address, %a_minus_one
%mask = sub i64 0, %a
%masked = and i64 %offset_ptr, %mask
; can be folded with `gepi` that may follow
%offset = sub i64 %masked, %address
…and generates the intended x86_64 machine code. One might also wonder
how the increased amount of code would impact a RISC target. Turns out
not much:
; aarch64 previous ; aarch64 new
sub x8, x1, #1 add x8, x1, x0
neg x9, x0 sub x8, x8, #1
and x8, x9, x8 neg x9, x1
add x0, x0, x8 and x0, x8, x9
(and similarly for ppc, sparc, mips, riscv, etc)
The only target that seems to do worse is… wasm32.
Onto actual measurements – the best way to evaluate snippets like these
is to use llvm-mca. Much like Aarch64 assembly would allow to suspect,
there isn’t any performance difference to be found. Both snippets
execute in same number of cycles for the CPUs I tried. On x86_64,
we get throughput improvement of >50%, however!
2020-08-20 00:38:00 +00:00
|
|
|
|
//
|
2023-01-14 15:33:11 +00:00
|
|
|
|
// The naive `-p (mod a)` equation inhibits LLVM's ability to select instructions
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
// like `lea`. We compute `(round_up_to_next_alignment(p, a) - p)` instead. This
|
|
|
|
|
// redistributes operations around the load-bearing, but pessimizing `and` instruction
|
|
|
|
|
// sufficiently for LLVM to be able to utilize the various optimizations it knows about.
|
Optimise align_offset for stride=1 further
`stride == 1` case can be computed more efficiently through `-p (mod
a)`. That, then translates to a nice and short sequence of LLVM
instructions:
%address = ptrtoint i8* %p to i64
%negptr = sub i64 0, %address
%offset = and i64 %negptr, %a_minus_one
And produces pretty much ideal code-gen when this function is used in
isolation.
Typical use of this function will, however, involve use of
the result to offset a pointer, i.e.
%aligned = getelementptr inbounds i8, i8* %p, i64 %offset
This still looks very good, but LLVM does not really translate that to
what would be considered ideal machine code (on any target). For example
that's the codegen we obtain for an unknown alignment:
; x86_64
dec rsi
mov rax, rdi
neg rax
and rax, rsi
add rax, rdi
In particular negating a pointer is not something that’s going to be
optimised for in the design of CISC architectures like x86_64. They
are much better at offsetting pointers. And so we’d love to utilize this
ability and produce code that's more like this:
; x86_64
lea rax, [rsi + rdi - 1]
neg rsi
and rax, rsi
To achieve this we need to give LLVM an opportunity to apply its
various peep-hole optimisations that it does during DAG selection. In
particular, the `and` instruction appears to be a major inhibitor here.
We cannot, sadly, get rid of this load-bearing operation, but we can
reorder operations such that LLVM has more to work with around this
instruction.
One such ordering is proposed in #75579 and results in LLVM IR that
looks broadly like this:
; using add enables `lea` and similar CISCisms
%offset_ptr = add i64 %address, %a_minus_one
%mask = sub i64 0, %a
%masked = and i64 %offset_ptr, %mask
; can be folded with `gepi` that may follow
%offset = sub i64 %masked, %address
…and generates the intended x86_64 machine code. One might also wonder
how the increased amount of code would impact a RISC target. Turns out
not much:
; aarch64 previous ; aarch64 new
sub x8, x1, #1 add x8, x1, x0
neg x9, x0 sub x8, x8, #1
and x8, x9, x8 neg x9, x1
add x0, x0, x8 and x0, x8, x9
(and similarly for ppc, sparc, mips, riscv, etc)
The only target that seems to do worse is… wasm32.
Onto actual measurements – the best way to evaluate snippets like these
is to use llvm-mca. Much like Aarch64 assembly would allow to suspect,
there isn’t any performance difference to be found. Both snippets
execute in same number of cycles for the CPUs I tried. On x86_64,
we get throughput improvement of >50%, however!
2020-08-20 00:38:00 +00:00
|
|
|
|
//
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
// LLVM handles the branch here particularly nicely. If this branch needs to be evaluated
|
|
|
|
|
// at runtime, it will produce a mask `if addr_mod_stride == 0 { 0 } else { usize::MAX }`
|
|
|
|
|
// in a branch-free way and then bitwise-OR it with whatever result the `-p mod a`
|
|
|
|
|
// computation produces.
|
|
|
|
|
|
2023-05-03 00:23:54 +00:00
|
|
|
|
let aligned_address = wrapping_add(addr, a_minus_one) & wrapping_sub(0, a);
|
|
|
|
|
let byte_offset = wrapping_sub(aligned_address, addr);
|
|
|
|
|
// FIXME: Remove the assume after <https://github.com/llvm/llvm-project/issues/62502>
|
|
|
|
|
// SAFETY: Masking by `-a` can only affect the low bits, and thus cannot have reduced
|
|
|
|
|
// the value by more than `a-1`, so even though the intermediate values might have
|
|
|
|
|
// wrapped, the byte_offset is always in `[0, a)`.
|
|
|
|
|
unsafe { assume(byte_offset < a) };
|
|
|
|
|
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
// SAFETY: `stride == 0` case has been handled by the special case above.
|
|
|
|
|
let addr_mod_stride = unsafe { unchecked_rem(addr, stride) };
|
2018-04-18 15:38:12 +00:00
|
|
|
|
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
return if addr_mod_stride == 0 {
|
|
|
|
|
// SAFETY: `stride` is non-zero. This is guaranteed to divide exactly as well, because
|
|
|
|
|
// addr has been verified to be aligned to the original type’s alignment requirements.
|
|
|
|
|
unsafe { exact_div(byte_offset, stride) }
|
|
|
|
|
} else {
|
|
|
|
|
usize::MAX
|
|
|
|
|
};
|
2018-05-03 21:49:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
// GENERAL_CASE: From here on we’re handling the very general case where `addr` may be
|
|
|
|
|
// misaligned, there isn’t an obvious relationship between `stride` and `a` that we can take an
|
|
|
|
|
// advantage of, etc. This case produces machine code that isn’t particularly high quality,
|
|
|
|
|
// compared to the special cases above. The code produced here is still within the realm of
|
|
|
|
|
// miracles, given the situations this case has to deal with.
|
|
|
|
|
|
2020-08-16 13:59:43 +00:00
|
|
|
|
// SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
|
2023-04-16 07:20:15 +00:00
|
|
|
|
// FIXME(const-hack) replace with min
|
|
|
|
|
let gcdpow = unsafe {
|
|
|
|
|
let x = cttz_nonzero(stride);
|
|
|
|
|
let y = cttz_nonzero(a);
|
|
|
|
|
if x < y { x } else { y }
|
|
|
|
|
};
|
2021-08-22 16:15:49 +00:00
|
|
|
|
// SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize.
|
2020-08-16 13:59:43 +00:00
|
|
|
|
let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
|
|
|
|
|
// SAFETY: gcd is always greater or equal to 1.
|
2022-03-22 05:27:28 +00:00
|
|
|
|
if addr & unsafe { unchecked_sub(gcd, 1) } == 0 {
|
2018-09-24 15:01:46 +00:00
|
|
|
|
// This branch solves for the following linear congruence equation:
|
2018-04-18 15:38:12 +00:00
|
|
|
|
//
|
2020-01-28 21:14:04 +00:00
|
|
|
|
// ` p + so = 0 mod a `
|
2018-04-18 15:38:12 +00:00
|
|
|
|
//
|
2020-01-28 21:14:04 +00:00
|
|
|
|
// `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
|
2018-09-24 15:01:46 +00:00
|
|
|
|
// requested alignment.
|
2018-04-18 15:38:12 +00:00
|
|
|
|
//
|
2020-08-16 13:59:43 +00:00
|
|
|
|
// With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
|
|
|
|
|
// `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
|
2018-04-18 15:38:12 +00:00
|
|
|
|
//
|
2020-01-28 21:14:04 +00:00
|
|
|
|
// ` p' + s'o = 0 mod a' `
|
|
|
|
|
// ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
|
2018-04-18 15:38:12 +00:00
|
|
|
|
//
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
// The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the
|
|
|
|
|
// second term is "how does incrementing `p` by `s` bytes change the relative alignment of
|
|
|
|
|
// `p`" (again divided by `g`). Division by `g` is necessary to make the inverse well
|
|
|
|
|
// formed if `a` and `s` are not co-prime.
|
2020-01-28 21:14:04 +00:00
|
|
|
|
//
|
|
|
|
|
// Furthermore, the result produced by this solution is not "minimal", so it is necessary
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
// to take the result `o mod lcm(s, a)`. This `lcm(s, a)` is the same as `a'`.
|
2020-08-16 13:59:43 +00:00
|
|
|
|
|
|
|
|
|
// SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
|
|
|
|
|
// `a`.
|
|
|
|
|
let a2 = unsafe { unchecked_shr(a, gcdpow) };
|
|
|
|
|
// SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
|
|
|
|
|
// in `a` (of which it has exactly one).
|
|
|
|
|
let a2minus1 = unsafe { unchecked_sub(a2, 1) };
|
|
|
|
|
// SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
|
|
|
|
|
// `a`.
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
let s2 = unsafe { unchecked_shr(stride & a_minus_one, gcdpow) };
|
2020-08-16 13:59:43 +00:00
|
|
|
|
// SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
|
|
|
|
|
// `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
|
|
|
|
|
// always be strictly greater than `(p % a) >> gcdpow`.
|
Add a special case for align_offset /w stride != 1
This generalizes the previous `stride == 1` special case to apply to any
situation where the requested alignment is divisible by the stride. This
in turn allows the test case from #98809 produce ideal assembly, along
the lines of:
leaq 15(%rdi), %rax
andq $-16, %rax
This also produces pretty high quality code for situations where the
alignment of the input pointer isn’t known:
pub unsafe fn ptr_u32(slice: *const u32) -> *const u32 {
slice.offset(slice.align_offset(16) as isize)
}
// =>
movl %edi, %eax
andl $3, %eax
leaq 15(%rdi), %rcx
andq $-16, %rcx
subq %rdi, %rcx
shrq $2, %rcx
negq %rax
sbbq %rax, %rax
orq %rcx, %rax
leaq (%rdi,%rax,4), %rax
Here LLVM is smart enough to replace the `usize::MAX` special case with
a branch-less bitwise-OR approach, where the mask is constructed using
the neg and sbb instructions. This appears to work across various
architectures I’ve tried.
This change ends up introducing more branches and code in situations
where there is less knowledge of the arguments. For example when the
requested alignment is entirely unknown. This use-case was never really
a focus of this function, so I’m not particularly worried, especially
since llvm-mca is saying that the new code is still appreciably faster,
despite all the new branching.
Fixes #98809.
Sadly, this does not help with #72356.
2022-07-03 21:23:31 +00:00
|
|
|
|
let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(addr & a_minus_one, gcdpow)) };
|
2020-08-16 13:59:43 +00:00
|
|
|
|
// SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
|
|
|
|
|
// because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
|
|
|
|
|
return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
|
2018-04-18 15:38:12 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Cannot be aligned at all.
|
2020-06-02 07:59:11 +00:00
|
|
|
|
usize::MAX
|
2018-04-18 15:38:12 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-02-09 22:16:58 +00:00
|
|
|
|
/// Compares raw pointers for equality.
|
2016-09-15 09:19:19 +00:00
|
|
|
|
///
|
|
|
|
|
/// This is the same as using the `==` operator, but less generic:
|
|
|
|
|
/// the arguments have to be `*const T` raw pointers,
|
|
|
|
|
/// not anything that implements `PartialEq`.
|
|
|
|
|
///
|
|
|
|
|
/// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
|
|
|
|
|
/// by their address rather than comparing the values they point to
|
|
|
|
|
/// (which is what the `PartialEq for &T` implementation does).
|
|
|
|
|
///
|
2022-10-26 12:20:31 +00:00
|
|
|
|
/// When comparing wide pointers, both the address and the metadata are tested for equality.
|
2022-12-08 21:36:57 +00:00
|
|
|
|
/// However, note that comparing trait object pointers (`*const dyn Trait`) is unreliable: pointers
|
2022-10-26 09:15:14 +00:00
|
|
|
|
/// to values of the same underlying type can compare inequal (because vtables are duplicated in
|
|
|
|
|
/// multiple codegen units), and pointers to values of *different* underlying type can compare equal
|
|
|
|
|
/// (since identical vtables can be deduplicated within a codegen unit).
|
|
|
|
|
///
|
2016-09-15 09:19:19 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let five = 5;
|
|
|
|
|
/// let other_five = 5;
|
|
|
|
|
/// let five_ref = &five;
|
|
|
|
|
/// let same_five_ref = &five;
|
|
|
|
|
/// let other_five_ref = &other_five;
|
|
|
|
|
///
|
|
|
|
|
/// assert!(five_ref == same_five_ref);
|
|
|
|
|
/// assert!(ptr::eq(five_ref, same_five_ref));
|
2019-03-25 20:38:12 +00:00
|
|
|
|
///
|
|
|
|
|
/// assert!(five_ref == other_five_ref);
|
2016-09-15 09:19:19 +00:00
|
|
|
|
/// assert!(!ptr::eq(five_ref, other_five_ref));
|
|
|
|
|
/// ```
|
2019-03-25 21:19:47 +00:00
|
|
|
|
///
|
|
|
|
|
/// Slices are also compared by their length (fat pointers):
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// let a = [1, 2, 3];
|
|
|
|
|
/// assert!(std::ptr::eq(&a[..3], &a[..3]));
|
|
|
|
|
/// assert!(!std::ptr::eq(&a[..2], &a[..3]));
|
|
|
|
|
/// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
|
|
|
|
|
/// ```
|
2017-03-15 14:58:27 +00:00
|
|
|
|
#[stable(feature = "ptr_eq", since = "1.17.0")]
|
2022-12-07 16:11:17 +00:00
|
|
|
|
#[inline(always)]
|
2023-10-02 15:10:51 +00:00
|
|
|
|
#[must_use = "pointer comparison produces a value"]
|
2023-09-27 03:56:38 +00:00
|
|
|
|
#[rustc_diagnostic_item = "ptr_eq"]
|
2023-12-22 10:14:11 +00:00
|
|
|
|
#[allow(ambiguous_wide_pointer_comparisons)] // it's actually clear here
|
2016-09-15 09:19:19 +00:00
|
|
|
|
pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
|
|
|
|
|
a == b
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-02 01:56:38 +00:00
|
|
|
|
/// Compares the *addresses* of the two pointers for equality,
|
|
|
|
|
/// ignoring any metadata in fat pointers.
|
|
|
|
|
///
|
|
|
|
|
/// If the arguments are thin pointers of the same type,
|
|
|
|
|
/// then this is the same as [`eq`].
|
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
2023-11-16 10:35:59 +00:00
|
|
|
|
/// use std::ptr;
|
2023-10-02 01:56:38 +00:00
|
|
|
|
///
|
|
|
|
|
/// let whole: &[i32; 3] = &[1, 2, 3];
|
|
|
|
|
/// let first: &i32 = &whole[0];
|
2023-11-16 10:35:59 +00:00
|
|
|
|
///
|
|
|
|
|
/// assert!(ptr::addr_eq(whole, first));
|
|
|
|
|
/// assert!(!ptr::eq::<dyn std::fmt::Debug>(whole, first));
|
2023-10-02 01:56:38 +00:00
|
|
|
|
/// ```
|
2023-12-21 14:39:15 +00:00
|
|
|
|
#[stable(feature = "ptr_addr_eq", since = "1.76.0")]
|
2023-10-02 01:56:38 +00:00
|
|
|
|
#[inline(always)]
|
2023-10-02 15:10:51 +00:00
|
|
|
|
#[must_use = "pointer comparison produces a value"]
|
2023-10-02 01:56:38 +00:00
|
|
|
|
pub fn addr_eq<T: ?Sized, U: ?Sized>(p: *const T, q: *const U) -> bool {
|
|
|
|
|
(p as *const ()) == (q as *const ())
|
|
|
|
|
}
|
|
|
|
|
|
2018-12-07 16:33:32 +00:00
|
|
|
|
/// Hash a raw pointer.
|
|
|
|
|
///
|
2018-12-07 16:34:53 +00:00
|
|
|
|
/// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
|
2018-12-07 16:33:32 +00:00
|
|
|
|
/// by its address rather than the value it points to
|
|
|
|
|
/// (which is what the `Hash for &T` implementation does).
|
2018-11-26 18:36:03 +00:00
|
|
|
|
///
|
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
2023-10-13 06:44:19 +00:00
|
|
|
|
/// use std::hash::{DefaultHasher, Hash, Hasher};
|
2018-11-26 18:36:03 +00:00
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// let five = 5;
|
|
|
|
|
/// let five_ref = &five;
|
|
|
|
|
///
|
|
|
|
|
/// let mut hasher = DefaultHasher::new();
|
2018-11-26 21:31:12 +00:00
|
|
|
|
/// ptr::hash(five_ref, &mut hasher);
|
2018-11-27 16:46:24 +00:00
|
|
|
|
/// let actual = hasher.finish();
|
|
|
|
|
///
|
|
|
|
|
/// let mut hasher = DefaultHasher::new();
|
2018-11-27 20:09:18 +00:00
|
|
|
|
/// (five_ref as *const i32).hash(&mut hasher);
|
2018-11-27 16:46:24 +00:00
|
|
|
|
/// let expected = hasher.finish();
|
|
|
|
|
///
|
|
|
|
|
/// assert_eq!(actual, expected);
|
2018-11-26 18:36:03 +00:00
|
|
|
|
/// ```
|
2019-04-01 13:36:07 +00:00
|
|
|
|
#[stable(feature = "ptr_hash", since = "1.35.0")]
|
2018-12-12 17:41:03 +00:00
|
|
|
|
pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
|
2019-04-15 02:23:21 +00:00
|
|
|
|
use crate::hash::Hash;
|
2018-12-04 08:06:26 +00:00
|
|
|
|
hashee.hash(into);
|
2018-11-26 18:36:03 +00:00
|
|
|
|
}
|
|
|
|
|
|
2023-04-21 13:33:04 +00:00
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> PartialEq for F {
|
|
|
|
|
#[inline]
|
|
|
|
|
fn eq(&self, other: &Self) -> bool {
|
|
|
|
|
self.addr() == other.addr()
|
2023-03-06 16:48:22 +00:00
|
|
|
|
}
|
2015-09-13 15:11:10 +00:00
|
|
|
|
}
|
2023-04-21 13:33:04 +00:00
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> Eq for F {}
|
2015-09-13 15:11:10 +00:00
|
|
|
|
|
2023-04-21 13:33:04 +00:00
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> PartialOrd for F {
|
|
|
|
|
#[inline]
|
|
|
|
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
|
|
|
|
self.addr().partial_cmp(&other.addr())
|
2023-03-06 16:48:22 +00:00
|
|
|
|
}
|
2023-04-21 13:33:04 +00:00
|
|
|
|
}
|
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> Ord for F {
|
|
|
|
|
#[inline]
|
|
|
|
|
fn cmp(&self, other: &Self) -> Ordering {
|
|
|
|
|
self.addr().cmp(&other.addr())
|
2023-03-06 16:48:22 +00:00
|
|
|
|
}
|
2023-04-21 13:33:04 +00:00
|
|
|
|
}
|
2023-03-06 16:48:22 +00:00
|
|
|
|
|
2023-04-21 13:33:04 +00:00
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> hash::Hash for F {
|
|
|
|
|
fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
|
|
|
|
|
state.write_usize(self.addr() as _)
|
2023-03-06 16:48:22 +00:00
|
|
|
|
}
|
2023-04-21 13:33:04 +00:00
|
|
|
|
}
|
2023-03-06 16:48:22 +00:00
|
|
|
|
|
2023-04-21 13:33:04 +00:00
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> fmt::Pointer for F {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
|
fmt::pointer_fmt_inner(self.addr() as _, f)
|
2023-03-06 16:48:22 +00:00
|
|
|
|
}
|
2023-04-21 13:33:04 +00:00
|
|
|
|
}
|
2020-06-12 16:17:30 +00:00
|
|
|
|
|
2023-04-21 13:33:04 +00:00
|
|
|
|
#[stable(feature = "fnptr_impls", since = "1.4.0")]
|
|
|
|
|
impl<F: FnPtr> fmt::Debug for F {
|
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
|
fmt::pointer_fmt_inner(self.addr() as _, f)
|
2023-03-06 16:48:22 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2023-04-21 13:33:04 +00:00
|
|
|
|
|
2020-06-12 16:17:30 +00:00
|
|
|
|
/// Create a `const` raw pointer to a place, without creating an intermediate reference.
|
|
|
|
|
///
|
|
|
|
|
/// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
|
|
|
|
|
/// and points to initialized data. For cases where those requirements do not hold,
|
|
|
|
|
/// raw pointers should be used instead. However, `&expr as *const _` creates a reference
|
|
|
|
|
/// before casting it to a raw pointer, and that reference is subject to the same rules
|
|
|
|
|
/// as all other references. This macro can create a raw pointer *without* creating
|
|
|
|
|
/// a reference first.
|
|
|
|
|
///
|
2023-11-04 09:55:18 +00:00
|
|
|
|
/// The `expr` in `addr_of!(expr)` is evaluated as a place expression, but never loads
|
|
|
|
|
/// from the place or requires the place to be dereferenceable. This means that
|
2023-11-10 06:34:28 +00:00
|
|
|
|
/// `addr_of!(*ptr)` is defined behavior even if `ptr` is null, dangling, or misaligned.
|
2023-11-04 09:55:18 +00:00
|
|
|
|
/// Note however that `addr_of!((*ptr).field)` still requires the projection to
|
|
|
|
|
/// `field` to be in-bounds, using the same rules as [`offset`].
|
|
|
|
|
///
|
|
|
|
|
/// Note that `Deref`/`Index` coercions (and their mutable counterparts) are applied inside
|
|
|
|
|
/// `addr_of!` like everywhere else, in which case a reference is created to call `Deref::deref` or
|
|
|
|
|
/// `Index::index`, respectively. The statements above only apply when no such coercions are
|
|
|
|
|
/// applied.
|
|
|
|
|
///
|
|
|
|
|
/// [`offset`]: pointer::offset
|
2021-04-03 17:26:54 +00:00
|
|
|
|
///
|
2020-06-12 16:17:30 +00:00
|
|
|
|
/// # Example
|
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// #[repr(packed)]
|
|
|
|
|
/// struct Packed {
|
|
|
|
|
/// f1: u8,
|
|
|
|
|
/// f2: u16,
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let packed = Packed { f1: 1, f2: 2 };
|
|
|
|
|
/// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
|
2021-01-10 18:35:42 +00:00
|
|
|
|
/// let raw_f2 = ptr::addr_of!(packed.f2);
|
2020-06-12 16:17:30 +00:00
|
|
|
|
/// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
|
|
|
|
|
/// ```
|
2021-04-03 17:25:11 +00:00
|
|
|
|
///
|
2023-04-11 04:49:38 +00:00
|
|
|
|
/// See [`addr_of_mut`] for how to create a pointer to uninitialized data.
|
2021-04-03 17:25:11 +00:00
|
|
|
|
/// Doing that with `addr_of` would not make much sense since one could only
|
|
|
|
|
/// read the data, and that would be Undefined Behavior.
|
2021-01-10 18:35:42 +00:00
|
|
|
|
#[stable(feature = "raw_ref_macros", since = "1.51.0")]
|
2020-06-12 16:17:30 +00:00
|
|
|
|
#[rustc_macro_transparency = "semitransparent"]
|
|
|
|
|
#[allow_internal_unstable(raw_ref_op)]
|
2021-01-10 18:35:42 +00:00
|
|
|
|
pub macro addr_of($place:expr) {
|
|
|
|
|
&raw const $place
|
2020-06-12 16:17:30 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Create a `mut` raw pointer to a place, without creating an intermediate reference.
|
|
|
|
|
///
|
|
|
|
|
/// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
|
|
|
|
|
/// and points to initialized data. For cases where those requirements do not hold,
|
|
|
|
|
/// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
|
|
|
|
|
/// before casting it to a raw pointer, and that reference is subject to the same rules
|
|
|
|
|
/// as all other references. This macro can create a raw pointer *without* creating
|
|
|
|
|
/// a reference first.
|
|
|
|
|
///
|
2023-11-04 09:55:18 +00:00
|
|
|
|
/// The `expr` in `addr_of_mut!(expr)` is evaluated as a place expression, but never loads
|
|
|
|
|
/// from the place or requires the place to be dereferenceable. This means that
|
2023-11-10 06:34:28 +00:00
|
|
|
|
/// `addr_of_mut!(*ptr)` is defined behavior even if `ptr` is null, dangling, or misaligned.
|
2023-11-04 09:55:18 +00:00
|
|
|
|
/// Note however that `addr_of_mut!((*ptr).field)` still requires the projection to
|
|
|
|
|
/// `field` to be in-bounds, using the same rules as [`offset`].
|
|
|
|
|
///
|
|
|
|
|
/// Note that `Deref`/`Index` coercions (and their mutable counterparts) are applied inside
|
|
|
|
|
/// `addr_of_mut!` like everywhere else, in which case a reference is created to call `Deref::deref`
|
|
|
|
|
/// or `Index::index`, respectively. The statements above only apply when no such coercions are
|
|
|
|
|
/// applied.
|
|
|
|
|
///
|
|
|
|
|
/// [`offset`]: pointer::offset
|
2021-04-03 17:26:54 +00:00
|
|
|
|
///
|
2021-04-03 17:25:11 +00:00
|
|
|
|
/// # Examples
|
|
|
|
|
///
|
|
|
|
|
/// **Creating a pointer to unaligned data:**
|
2020-06-12 16:17:30 +00:00
|
|
|
|
///
|
|
|
|
|
/// ```
|
|
|
|
|
/// use std::ptr;
|
|
|
|
|
///
|
|
|
|
|
/// #[repr(packed)]
|
|
|
|
|
/// struct Packed {
|
|
|
|
|
/// f1: u8,
|
|
|
|
|
/// f2: u16,
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let mut packed = Packed { f1: 1, f2: 2 };
|
|
|
|
|
/// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
|
2021-01-10 18:35:42 +00:00
|
|
|
|
/// let raw_f2 = ptr::addr_of_mut!(packed.f2);
|
2020-06-12 16:17:30 +00:00
|
|
|
|
/// unsafe { raw_f2.write_unaligned(42); }
|
|
|
|
|
/// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
|
|
|
|
|
/// ```
|
2021-04-03 17:25:11 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Creating a pointer to uninitialized data:**
|
|
|
|
|
///
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// use std::{ptr, mem::MaybeUninit};
|
|
|
|
|
///
|
|
|
|
|
/// struct Demo {
|
|
|
|
|
/// field: bool,
|
|
|
|
|
/// }
|
|
|
|
|
///
|
|
|
|
|
/// let mut uninit = MaybeUninit::<Demo>::uninit();
|
|
|
|
|
/// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
|
|
|
|
|
/// // and thus be Undefined Behavior!
|
|
|
|
|
/// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
|
|
|
|
|
/// unsafe { f1_ptr.write(true); }
|
|
|
|
|
/// let init = unsafe { uninit.assume_init() };
|
|
|
|
|
/// ```
|
2021-01-10 18:35:42 +00:00
|
|
|
|
#[stable(feature = "raw_ref_macros", since = "1.51.0")]
|
2020-06-12 16:17:30 +00:00
|
|
|
|
#[rustc_macro_transparency = "semitransparent"]
|
|
|
|
|
#[allow_internal_unstable(raw_ref_op)]
|
2021-01-10 18:35:42 +00:00
|
|
|
|
pub macro addr_of_mut($place:expr) {
|
|
|
|
|
&raw mut $place
|
2020-06-12 16:17:30 +00:00
|
|
|
|
}
|