core/ptr/mod.rs
1//! Manually manage memory through raw pointers.
2//!
3//! *[See also the pointer primitive types](pointer).*
4//!
5//! # Safety
6//!
7//! Many functions in this module take raw pointers as arguments and read from or write to them. For
8//! this to be safe, these pointers must be *valid* for the given access. Whether a pointer is valid
9//! depends on the operation it is used for (read or write), and the extent of the memory that is
10//! accessed (i.e., how many bytes are read/written) -- it makes no sense to ask "is this pointer
11//! valid"; one has to ask "is this pointer valid for a given access". Most functions use `*mut T`
12//! and `*const T` to access only a single value, in which case the documentation omits the size and
13//! implicitly assumes it to be `size_of::<T>()` bytes.
14//!
15//! The precise rules for validity are not determined yet. The guarantees that are
16//! provided at this point are very minimal:
17//!
18//! * A [null] pointer is *never* valid for reads/writes.
19//! * For memory accesses of [size zero][zst], *every* non-null pointer is valid for reads/writes.
20//! The following points are only concerned with non-zero-sized accesses.
21//! * For a pointer to be valid for reads/writes, it is necessary, but not always sufficient, that
22//! the pointer be *dereferenceable*. The [provenance] of the pointer is used to determine which
23//! [allocation] it is derived from; a pointer is dereferenceable if the memory range of the given
24//! size starting at the pointer is entirely contained within the bounds of that allocation. Note
25//! that in Rust, every (stack-allocated) variable is considered a separate allocation.
26//! * All accesses performed by functions in this module are *non-atomic* in the sense
27//! of [atomic operations] used to synchronize between threads. This means it is
28//! undefined behavior to perform two concurrent accesses to the same location from different
29//! threads unless both accesses only read from memory.
30//! * The result of casting a reference to a pointer is valid for reads/writes for as long as the
31//! underlying allocation is live and no reference (just raw pointers) is used to
32//! access the same memory. That is, reference and pointer accesses cannot be
33//! interleaved.
34//!
35//! These axioms, along with careful use of [`offset`] for pointer arithmetic,
36//! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
37//! will be provided eventually, as the [aliasing] rules are being determined. For more
38//! information, see the [book] as well as the section in the reference devoted
39//! to [undefined behavior][ub].
40//!
41//! Note that some operations such as [`read`] and [`write`][`write()`] do allow null pointers if
42//! the total size of the access is zero. However, other operations internally convert pointers into
43//! references. Therefore, the general notion of "valid for reads/writes" excludes null pointers,
44//! and the specific operations that permit null pointers mention that as an exception. Furthermore,
45//! [`read_volatile`] and [`write_volatile`] can be used in even more situations; see their
46//! documentation for details.
47//!
48//! We say that a pointer is "dangling" if it is not valid for any non-zero-sized accesses. This
49//! means out-of-bounds pointers, pointers to freed memory, null pointers, and pointers created with
50//! [`NonNull::dangling`] are all dangling.
51//!
52//! ## Alignment
53//!
54//! Valid raw pointers as defined above are not necessarily properly aligned (where
55//! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
56//! aligned to `align_of::<T>()`). However, most functions require their
57//! arguments to be properly aligned, and will explicitly state
58//! this requirement in their documentation. Notable exceptions to this are
59//! [`read_unaligned`] and [`write_unaligned`].
60//!
61//! When a function requires proper alignment, it does so even if the access
62//! has size 0, i.e., even if memory is not actually touched. Consider using
63//! [`NonNull::dangling`] in such cases.
64//!
65//! ## Pointer to reference conversion
66//!
67//! When converting a pointer to a reference (e.g. via `&*ptr` or `&mut *ptr`),
68//! there are several rules that must be followed:
69//!
70//! * The pointer must be properly aligned.
71//!
72//! * It must be non-null.
73//!
74//! * It must be "dereferenceable" in the sense defined above.
75//!
76//! * The pointer must point to a [valid value] of type `T`.
77//!
78//! * You must enforce Rust's aliasing rules. The exact aliasing rules are not decided yet, so we
79//! only give a rough overview here. The rules also depend on whether a mutable or a shared
80//! reference is being created.
81//! * When creating a mutable reference, then while this reference exists, the memory it points to
82//! must not get accessed (read or written) through any other pointer or reference not derived
83//! from this reference.
84//! * When creating a shared reference, then while this reference exists, the memory it points to
85//! must not get mutated (except inside `UnsafeCell`).
86//!
87//! If a pointer follows all of these rules, it is said to be
88//! *convertible to a (mutable or shared) reference*.
89// ^ we use this term instead of saying that the produced reference must
90// be valid, as the validity of a reference is easily confused for the
91// validity of the thing it refers to, and while the two concepts are
92// closely related, they are not identical.
93//!
94//! These rules apply even if the result is unused!
95//! (The part about being initialized is not yet fully decided, but until
96//! it is, the only safe approach is to ensure that they are indeed initialized.)
97//!
98//! An example of the implications of the above rules is that an expression such
99//! as `unsafe { &*(0 as *const u8) }` is Immediate Undefined Behavior.
100//!
101//! [valid value]: ../../reference/behavior-considered-undefined.html#invalid-values
102//!
103//! ## Allocation
104//!
105//! <a id="allocated-object"></a> <!-- keep old URLs working -->
106//!
107//! An *allocation* is a subset of program memory which is addressable
108//! from Rust, and within which pointer arithmetic is possible. Examples of
109//! allocations include heap allocations, stack-allocated variables,
110//! statics, and consts. The safety preconditions of some Rust operations -
111//! such as `offset` and field projections (`expr.field`) - are defined in
112//! terms of the allocations on which they operate.
113//!
114//! An allocation has a base address, a size, and a set of memory
115//! addresses. It is possible for an allocation to have zero size, but
116//! such an allocation will still have a base address. The base address
117//! of an allocation is not necessarily unique. While it is currently the
118//! case that an allocation always has a set of memory addresses which is
119//! fully contiguous (i.e., has no "holes"), there is no guarantee that this
120//! will not change in the future.
121//!
122//! An allocation can be either mutable (the common case) or *read-only*.
123//! Read-only allocations are implicitly introduced by the compiler for `static` items without
124//! interior mutability and for `const` items. Writing or creating a mutable reference to a
125//! read-only allocation is undefined behavior, and most atomic operations are not supported
126//! for read-only allocations either (see [here][atomic-ro] for exceptions).
127//! Additionally, some target-specific intrinsics are not supported on read-only
128//! allocations even if their memory write is masked off, such as [`_mm_maskmoveu_si128`].
129//!
130//! [atomic-ro]: crate::sync::atomic#atomic-accesses-to-read-only-memory
131//! [`_mm_maskmoveu_si128`]: ../../core/arch/x86/fn._mm_maskmoveu_si128.html
132//!
133//! Allocations must behave like "normal" memory: in particular, reads must not have
134//! side-effects, and writes must become visible to other threads using the usual synchronization
135//! primitives.
136//! Allocations must support all atomic operations that are available for the target (as
137//! determined by the `target_has_atomic*` set of cfg flags).
138//! Read-only allocations only have to support the operations [permitted there][atomic-ro].
139//! The precise instructions used for atomic operations are generally not guaranteed, so portable
140//! software should place all Rust allocations in memory regions that support all atomic
141//! instructions.
142//!
143//! For any allocation with `base` address, `size`, and a set of
144//! `addresses`, the following are guaranteed:
145//! - For all addresses `a` in `addresses`, `a` is in the range `base .. (base +
146//! size)` (note that this requires `a < base + size`, not `a <= base + size`)
147//! - `base` is not equal to [`null()`] (i.e., the address with the numerical
148//! value 0)
149//! - `base + size <= usize::MAX`
150//! - `size <= isize::MAX`
151//!
152//! As a consequence of these guarantees, given any address `a` within the set
153//! of addresses of an allocation:
154//! - It is guaranteed that `a - base` does not overflow `isize`
155//! - It is guaranteed that `a - base` is non-negative
156//! - It is guaranteed that, given `o = a - base` (i.e., the offset of `a` within
157//! the allocation), `base + o` will not wrap around the address space (in
158//! other words, will not overflow `usize`)
159//!
160//! Allocations typically have a fixed size that cannot change. However, allocations created by
161//! directly invoking page table operations of the operating system, e.g. via `mmap`, are allowed to
162//! grow by adding more pages to them at the end. Adding more pages before the beginning, or
163//! unmapping parts of an allocation (i.e., shrinking it or punching holes into it), is currently
164//! not supported. Allocations created via "compiler-recognized" operations, such as `std::alloc`
165//! methods or `libc::malloc`, can never change their size, even if they use `mmap` under the hood.
166//!
167//! [`null()`]: null
168//!
169//! # Provenance
170//!
171//! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial
172//! to say that a Use After Free is clearly Undefined Behavior, even if you "get lucky"
173//! and the freed memory gets reallocated before your read/write (in fact this is the
174//! worst-case scenario, UAFs would be much less concerning if this didn't happen!).
175//! As another example, consider that [`wrapping_offset`] is documented to "remember"
176//! the allocation that the original pointer points to, even if it is offset far
177//! outside the memory range occupied by that allocation.
178//! To rationalize claims like this, pointers need to somehow be *more* than just their addresses:
179//! they must have **provenance**.
180//!
181//! A pointer value in Rust semantically contains the following information:
182//!
183//! * The **address** it points to, which can be represented by a `usize`.
184//! * The **provenance** it has, defining the memory it has permission to access. Provenance can be
185//! absent, in which case the pointer does not have permission to access any memory.
186//!
187//! The exact structure of provenance is not yet specified, but the permission defined by a
188//! pointer's provenance have a *spatial* component, a *temporal* component, and a *mutability*
189//! component:
190//!
191//! * Spatial: The set of memory addresses that the pointer is allowed to access.
192//! * Temporal: The timespan during which the pointer is allowed to access those memory addresses.
193//! * Mutability: Whether the pointer may only access the memory for reads, or also access it for
194//! writes. Note that this can interact with the other components, e.g. a pointer might permit
195//! mutation only for a subset of addresses, or only for a subset of its maximal timespan.
196//!
197//! When an [allocation] is created, it has a unique Original Pointer. For alloc
198//! APIs this is literally the pointer the call returns, and for local variables and statics,
199//! this is the name of the variable/static. (This is mildly overloading the term "pointer"
200//! for the sake of brevity/exposition.)
201//!
202//! The Original Pointer for an allocation has provenance that constrains the *spatial*
203//! permissions of this pointer to the memory range of the allocation, and the *temporal*
204//! permissions to the lifetime of the allocation. Provenance is implicitly inherited by all
205//! pointers transitively derived from the Original Pointer through operations like [`offset`],
206//! borrowing, and pointer casts. Some operations may *shrink* the permissions of the derived
207//! provenance, limiting how much memory it can access or how long it's valid for (i.e. borrowing a
208//! subfield and subslicing can shrink the spatial component of provenance, and all borrowing can
209//! shrink the temporal component of provenance). However, no operation can ever *grow* the
210//! permissions of the derived provenance: even if you "know" there is a larger allocation, you
211//! can't derive a pointer with a larger provenance. Similarly, you cannot "recombine" two
212//! contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`).
213//!
214//! A reference to a place always has provenance over at least the memory that place occupies.
215//! A reference to a slice always has provenance over at least the range that slice describes.
216//! Whether and when exactly the provenance of a reference gets "shrunk" to *exactly* fit
217//! the memory it points to is not yet determined.
218//!
219//! A *shared* reference only ever has provenance that permits reading from memory,
220//! and never permits writes, except inside [`UnsafeCell`].
221//!
222//! Provenance can affect whether a program has undefined behavior:
223//!
224//! * It is undefined behavior to access memory through a pointer that does not have provenance over
225//! that memory. Note that a pointer "at the end" of its provenance is not actually outside its
226//! provenance, it just has 0 bytes it can load/store. Zero-sized accesses do not require any
227//! provenance since they access an empty range of memory.
228//!
229//! * It is undefined behavior to [`offset`] a pointer across a memory range that is not contained
230//! in the allocation it is derived from, or to [`offset_from`] two pointers not derived
231//! from the same allocation. Provenance is used to say what exactly "derived from" even
232//! means: the lineage of a pointer is traced back to the Original Pointer it descends from, and
233//! that identifies the relevant allocation. In particular, it's always UB to offset a
234//! pointer derived from something that is now deallocated, except if the offset is 0.
235//!
236//! But it *is* still sound to:
237//!
238//! * Create a pointer without provenance from just an address (see [`without_provenance`]). Such a
239//! pointer cannot be used for memory accesses (except for zero-sized accesses). This can still be
240//! useful for sentinel values like `null` *or* to represent a tagged pointer that will never be
241//! dereferenceable. In general, it is always sound for an integer to pretend to be a pointer "for
242//! fun" as long as you don't use operations on it which require it to be valid (non-zero-sized
243//! offset, read, write, etc).
244//!
245//! * Forge an allocation of size zero at any sufficiently aligned non-null address.
246//! i.e. the usual "ZSTs are fake, do what you want" rules apply.
247//!
248//! * [`wrapping_offset`] a pointer outside its provenance. This includes pointers
249//! which have "no" provenance. In particular, this makes it sound to do pointer tagging tricks.
250//!
251//! * Compare arbitrary pointers by address. Pointer comparison ignores provenance and addresses
252//! *are* just integers, so there is always a coherent answer, even if the pointers are dangling
253//! or from different provenances. Note that if you get "lucky" and notice that a pointer at the
254//! end of one allocation is the "same" address as the start of another allocation,
255//! anything you do with that fact is *probably* going to be gibberish. The scope of that
256//! gibberish is kept under control by the fact that the two pointers *still* aren't allowed to
257//! access the other's allocation (bytes), because they still have different provenance.
258//!
259//! Note that the full definition of provenance in Rust is not decided yet, as this interacts
260//! with the as-yet undecided [aliasing] rules.
261//!
262//! ## Pointers Vs Integers
263//!
264//! From this discussion, it becomes very clear that a `usize` *cannot* accurately represent a pointer,
265//! and converting from a pointer to a `usize` is generally an operation which *only* extracts the
266//! address. Converting this address back into pointer requires somehow answering the question:
267//! which provenance should the resulting pointer have?
268//!
269//! Rust provides two ways of dealing with this situation: *Strict Provenance* and *Exposed Provenance*.
270//!
271//! Note that a pointer *can* represent a `usize` (via [`without_provenance`]), so the right type to
272//! use in situations where a value is "sometimes a pointer and sometimes a bare `usize`" is a
273//! pointer type.
274//!
275//! ## Strict Provenance
276//!
277//! "Strict Provenance" refers to a set of APIs designed to make working with provenance more
278//! explicit. They are intended as substitutes for casting a pointer to an integer and back.
279//!
280//! Entirely avoiding integer-to-pointer casts successfully side-steps the inherent ambiguity of
281//! that operation. This benefits compiler optimizations, and it is pretty much a requirement for
282//! using tools like [Miri] and architectures like [CHERI] that aim to detect and diagnose pointer
283//! misuse.
284//!
285//! The key insight to making programming without integer-to-pointer casts *at all* viable is the
286//! [`with_addr`] method:
287//!
288//! ```text
289//! /// Creates a new pointer with the given address and the provenance of `self`.
290//! ///
291//! /// This is similar to a `addr as *const T` cast,
292//! /// but copies the provenance of `self` to the new pointer.
293//! /// This avoids the inherent ambiguity of the unary cast.
294//! ///
295//! /// This is equivalent to using `wrapping_offset` to offset `self` to the given address,
296//! /// and therefore has all the same capabilities and restrictions.
297//! pub fn with_addr(self, addr: usize) -> Self;
298//! ```
299//!
300//! So you're still able to drop down to the address representation and do whatever
301//! clever bit tricks you want *as long as* you're able to keep around a pointer
302//! into the allocation you care about that can "reconstitute" the provenance.
303//! Usually this is very easy, because you only are taking a pointer, messing with the address,
304//! and then immediately converting back to a pointer. To make this use case more ergonomic,
305//! we provide the [`map_addr`] method.
306//!
307//! To help make it clear that code is "following" Strict Provenance semantics, we also provide an
308//! [`addr`] method which promises that the returned address is not part of a
309//! pointer-integer-pointer roundtrip. In the future we may provide a lint for pointer<->integer
310//! casts to help you audit if your code conforms to strict provenance.
311//!
312//! ### Using Strict Provenance
313//!
314//! Most code needs no changes to conform to strict provenance, as the only really concerning
315//! operation is casts from `usize` to a pointer. For code which *does* cast a `usize` to a pointer,
316//! the scope of the change depends on exactly what you're doing.
317//!
318//! In general, you just need to make sure that if you want to convert a `usize` address to a
319//! pointer and then use that pointer to read/write memory, you need to keep around a pointer
320//! that has sufficient provenance to perform that read/write itself. In this way all of your
321//! casts from an address to a pointer are essentially just applying offsets/indexing.
322//!
323//! This is generally trivial to do for simple cases like tagged pointers *as long as you
324//! represent the tagged pointer as an actual pointer and not a `usize`*. For instance:
325//!
326//! ```
327//! // A flag we want to pack into our pointer
328//! static HAS_DATA: usize = 0x1;
329//! static FLAG_MASK: usize = !HAS_DATA;
330//!
331//! // Our value, which must have enough alignment to have spare least-significant-bits.
332//! let my_precious_data: u32 = 17;
333//! assert!(align_of::<u32>() > 1);
334//!
335//! // Create a tagged pointer
336//! let ptr = &my_precious_data as *const u32;
337//! let tagged = ptr.map_addr(|addr| addr | HAS_DATA);
338//!
339//! // Check the flag:
340//! if tagged.addr() & HAS_DATA != 0 {
341//! // Untag and read the pointer
342//! let data = unsafe { *tagged.map_addr(|addr| addr & FLAG_MASK) };
343//! assert_eq!(data, 17);
344//! } else {
345//! unreachable!()
346//! }
347//! ```
348//!
349//! (Yes, if you've been using [`AtomicUsize`] for pointers in concurrent datastructures, you should
350//! be using [`AtomicPtr`] instead. If that messes up the way you atomically manipulate pointers,
351//! we would like to know why, and what needs to be done to fix it.)
352//!
353//! Situations where a valid pointer *must* be created from just an address, such as baremetal code
354//! accessing a memory-mapped interface at a fixed address, cannot currently be handled with strict
355//! provenance APIs and should use [exposed provenance](#exposed-provenance).
356//!
357//! ## Exposed Provenance
358//!
359//! As discussed above, integer-to-pointer casts are not possible with Strict Provenance APIs.
360//! This is by design: the goal of Strict Provenance is to provide a clear specification that we are
361//! confident can be formalized unambiguously and can be subject to precise formal reasoning.
362//! Integer-to-pointer casts do not (currently) have such a clear specification.
363//!
364//! However, there exist situations where integer-to-pointer casts cannot be avoided, or
365//! where avoiding them would require major refactoring. Legacy platform APIs also regularly assume
366//! that `usize` can capture all the information that makes up a pointer.
367//! Bare-metal platforms can also require the synthesis of a pointer "out of thin air" without
368//! anywhere to obtain proper provenance from.
369//!
370//! Rust's model for dealing with integer-to-pointer casts is called *Exposed Provenance*. However,
371//! the semantics of Exposed Provenance are on much less solid footing than Strict Provenance, and
372//! at this point it is not yet clear whether a satisfying unambiguous semantics can be defined for
373//! Exposed Provenance. (If that sounds bad, be reassured that other popular languages that provide
374//! integer-to-pointer casts are not faring any better.) Furthermore, Exposed Provenance will not
375//! work (well) with tools like [Miri] and [CHERI].
376//!
377//! Exposed Provenance is provided by the [`expose_provenance`] and [`with_exposed_provenance`] methods,
378//! which are equivalent to `as` casts between pointers and integers.
379//! - [`expose_provenance`] is a lot like [`addr`], but additionally adds the provenance of the
380//! pointer to a global list of 'exposed' provenances. (This list is purely conceptual, it exists
381//! for the purpose of specifying Rust but is not materialized in actual executions, except in
382//! tools like [Miri].)
383//! Memory which is outside the control of the Rust abstract machine (MMIO registers, for example)
384//! is always considered to be exposed, so long as this memory is disjoint from memory that will
385//! be used by the abstract machine such as the stack, heap, and statics.
386//! - [`with_exposed_provenance`] can be used to construct a pointer with one of these previously
387//! 'exposed' provenances. [`with_exposed_provenance`] takes only `addr: usize` as arguments, so
388//! unlike in [`with_addr`] there is no indication of what the correct provenance for the returned
389//! pointer is -- and that is exactly what makes integer-to-pointer casts so tricky to rigorously
390//! specify! The compiler will do its best to pick the right provenance for you, but currently we
391//! cannot provide any guarantees about which provenance the resulting pointer will have. Only one
392//! thing is clear: if there is *no* previously 'exposed' provenance that justifies the way the
393//! returned pointer will be used, the program has undefined behavior.
394//!
395//! If at all possible, we encourage code to be ported to [Strict Provenance] APIs, thus avoiding
396//! the need for Exposed Provenance. Maximizing the amount of such code is a major win for avoiding
397//! specification complexity and to facilitate adoption of tools like [CHERI] and [Miri] that can be
398//! a big help in increasing the confidence in (unsafe) Rust code. However, we acknowledge that this
399//! is not always possible, and offer Exposed Provenance as a way to explicit "opt out" of the
400//! well-defined semantics of Strict Provenance, and "opt in" to the unclear semantics of
401//! integer-to-pointer casts.
402//!
403//! [aliasing]: ../../nomicon/aliasing.html
404//! [allocation]: #allocation
405//! [provenance]: #provenance
406//! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
407//! [ub]: ../../reference/behavior-considered-undefined.html
408//! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
409//! [atomic operations]: crate::sync::atomic
410//! [`offset`]: pointer::offset
411//! [`offset_from`]: pointer::offset_from
412//! [`wrapping_offset`]: pointer::wrapping_offset
413//! [`with_addr`]: pointer::with_addr
414//! [`map_addr`]: pointer::map_addr
415//! [`addr`]: pointer::addr
416//! [`AtomicUsize`]: crate::sync::atomic::AtomicUsize
417//! [`AtomicPtr`]: crate::sync::atomic::AtomicPtr
418//! [`expose_provenance`]: pointer::expose_provenance
419//! [`with_exposed_provenance`]: with_exposed_provenance
420//! [Miri]: https://github.com/rust-lang/miri
421//! [CHERI]: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
422//! [Strict Provenance]: #strict-provenance
423//! [`UnsafeCell`]: core::cell::UnsafeCell
424
425#![stable(feature = "rust1", since = "1.0.0")]
426// There are many unsafe functions taking pointers that don't dereference them.
427#![allow(clippy::not_unsafe_ptr_arg_deref)]
428
429use crate::cmp::Ordering;
430use crate::intrinsics::const_eval_select;
431use crate::marker::{Destruct, PointeeSized};
432use crate::mem::{self, MaybeUninit, SizedTypeProperties};
433use crate::num::NonZero;
434use crate::ops::FnPtr;
435use crate::{fmt, hash, intrinsics, ub_checks};
436
437#[unstable(feature = "ptr_alignment_type", issue = "102070")]
438#[deprecated(since = "1.96.0", note = "moved from `ptr` to `mem`")]
439/// Deprecated re-export of [mem::Alignment].
440pub type Alignment = mem::Alignment;
441
442mod metadata;
443#[unstable(feature = "ptr_metadata", issue = "81513")]
444pub use metadata::{DynMetadata, Pointee, Thin, from_raw_parts, from_raw_parts_mut, metadata};
445
446mod non_null;
447#[stable(feature = "nonnull", since = "1.25.0")]
448pub use non_null::NonNull;
449
450mod unique;
451#[unstable(feature = "ptr_internals", issue = "none")]
452pub use unique::Unique;
453
454mod const_ptr;
455mod mut_ptr;
456
457// Some functions are defined here because they accidentally got made
458// available in this module on stable. See <https://github.com/rust-lang/rust/issues/15702>.
459// (`transmute` also falls into this category, but it cannot be wrapped due to the
460// check that `T` and `U` have the same size.)
461
462/// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
463/// and destination must *not* overlap.
464///
465/// For regions of memory which might overlap, use [`copy`] instead.
466///
467/// `copy_nonoverlapping` is semantically equivalent to C's [`memcpy`], but
468/// with the source and destination arguments swapped,
469/// and `count` counting the number of `T`s instead of bytes.
470///
471/// The copy is "untyped" in the sense that data may be uninitialized or otherwise violate the
472/// requirements of `T`. The initialization state is preserved exactly.
473///
474/// [`memcpy`]: https://en.cppreference.com/w/c/string/byte/memcpy
475///
476/// # Safety
477///
478/// Behavior is undefined if any of the following conditions are violated:
479///
480/// * `src` must be [valid] for reads of `count * size_of::<T>()` bytes or that number must be 0.
481///
482/// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes or that number must be 0.
483///
484/// * Both `src` and `dst` must be properly aligned.
485///
486/// * The region of memory beginning at `src` with a size of `count *
487/// size_of::<T>()` bytes must *not* overlap with the region of memory
488/// beginning at `dst` with the same size.
489///
490/// Like [`read`], `copy_nonoverlapping` creates a bitwise copy of `T`, regardless of
491/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using *both* the values
492/// in the region beginning at `*src` and the region beginning at `*dst` can
493/// [violate memory safety][read-ownership].
494///
495/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
496/// `0`, the pointers must be properly aligned.
497///
498/// [`read`]: crate::ptr::read
499/// [read-ownership]: crate::ptr::read#ownership-of-the-returned-value
500/// [valid]: crate::ptr#safety
501///
502/// # Examples
503///
504/// Manually implement [`Vec::append`]:
505///
506/// ```
507/// use std::ptr;
508///
509/// /// Moves all the elements of `src` into `dst`, leaving `src` empty.
510/// fn append<T>(dst: &mut Vec<T>, src: &mut Vec<T>) {
511/// let src_len = src.len();
512/// let dst_len = dst.len();
513///
514/// // Ensure that `dst` has enough capacity to hold all of `src`.
515/// dst.reserve(src_len);
516///
517/// unsafe {
518/// // The call to add is always safe because `Vec` will never
519/// // allocate more than `isize::MAX` bytes.
520/// let dst_ptr = dst.as_mut_ptr().add(dst_len);
521/// let src_ptr = src.as_ptr();
522///
523/// // Truncate `src` without dropping its contents. We do this first,
524/// // to avoid problems in case something further down panics.
525/// src.set_len(0);
526///
527/// // The two regions cannot overlap because mutable references do
528/// // not alias, and two different vectors cannot own the same
529/// // memory.
530/// ptr::copy_nonoverlapping(src_ptr, dst_ptr, src_len);
531///
532/// // Notify `dst` that it now holds the contents of `src`.
533/// dst.set_len(dst_len + src_len);
534/// }
535/// }
536///
537/// let mut a = vec!['r'];
538/// let mut b = vec!['u', 's', 't'];
539///
540/// append(&mut a, &mut b);
541///
542/// assert_eq!(a, &['r', 'u', 's', 't']);
543/// assert!(b.is_empty());
544/// ```
545///
546/// [`Vec::append`]: ../../std/vec/struct.Vec.html#method.append
547#[doc(alias = "memcpy")]
548#[stable(feature = "rust1", since = "1.0.0")]
549#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
550#[inline(always)]
551#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
552#[rustc_diagnostic_item = "ptr_copy_nonoverlapping"]
553#[ferrocene::prevalidated]
554pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize) {
555 ub_checks::assert_unsafe_precondition!(
556 check_language_ub,
557 "ptr::copy_nonoverlapping requires that both pointer arguments are aligned and non-null \
558 and the specified memory ranges do not overlap",
559 (
560 src: *const () = src as *const (),
561 dst: *mut () = dst as *mut (),
562 size: usize = size_of::<T>(),
563 align: usize = align_of::<T>(),
564 count: usize = count,
565 ) => {
566 let zero_size = count == 0 || size == 0;
567 ub_checks::maybe_is_aligned_and_not_null(src, align, zero_size)
568 && ub_checks::maybe_is_aligned_and_not_null(dst, align, zero_size)
569 && ub_checks::maybe_is_nonoverlapping(src, dst, size, count)
570 }
571 );
572
573 // SAFETY: the safety contract for `copy_nonoverlapping` must be
574 // upheld by the caller.
575 unsafe { crate::intrinsics::copy_nonoverlapping(src, dst, count) }
576}
577
578/// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
579/// and destination may overlap.
580///
581/// If the source and destination will *never* overlap,
582/// [`copy_nonoverlapping`] can be used instead.
583///
584/// `copy` is semantically equivalent to C's [`memmove`], but
585/// with the source and destination arguments swapped,
586/// and `count` counting the number of `T`s instead of bytes.
587/// Copying takes place as if the bytes were copied from `src`
588/// to a temporary array and then copied from the array to `dst`.
589///
590/// The copy is "untyped" in the sense that data may be uninitialized or otherwise violate the
591/// requirements of `T`. The initialization state is preserved exactly.
592///
593/// [`memmove`]: https://en.cppreference.com/w/c/string/byte/memmove
594///
595/// # Safety
596///
597/// Behavior is undefined if any of the following conditions are violated:
598///
599/// * `src` must be [valid] for reads of `count * size_of::<T>()` bytes or that number must be 0.
600///
601/// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes or that number must be 0,
602/// and `dst` must remain valid even when `src` is read for `count * size_of::<T>()` bytes. (This
603/// means if the memory ranges overlap, the `dst` pointer must not be invalidated by `src` reads.)
604///
605/// * Both `src` and `dst` must be properly aligned.
606///
607/// Like [`read`], `copy` creates a bitwise copy of `T`, regardless of
608/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the values
609/// in the region beginning at `*src` and the region beginning at `*dst` can
610/// [violate memory safety][read-ownership].
611///
612/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
613/// `0`, the pointers must be properly aligned.
614///
615/// [`read`]: crate::ptr::read
616/// [read-ownership]: crate::ptr::read#ownership-of-the-returned-value
617/// [valid]: crate::ptr#safety
618///
619/// # Examples
620///
621/// Efficiently create a Rust vector from an unsafe buffer:
622///
623/// ```
624/// use std::ptr;
625///
626/// /// # Safety
627/// ///
628/// /// * `ptr` must be correctly aligned for its type and non-zero.
629/// /// * `ptr` must be valid for reads of `elts` contiguous elements of type `T`.
630/// /// * Those elements must not be used after calling this function unless `T: Copy`.
631/// # #[allow(dead_code)]
632/// unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
633/// let mut dst = Vec::with_capacity(elts);
634///
635/// // SAFETY: Our precondition ensures the source is aligned and valid,
636/// // and `Vec::with_capacity` ensures that we have usable space to write them.
637/// unsafe { ptr::copy(ptr, dst.as_mut_ptr(), elts); }
638///
639/// // SAFETY: We created it with this much capacity earlier,
640/// // and the previous `copy` has initialized these elements.
641/// unsafe { dst.set_len(elts); }
642/// dst
643/// }
644/// ```
645#[doc(alias = "memmove")]
646#[stable(feature = "rust1", since = "1.0.0")]
647#[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.83.0")]
648#[inline(always)]
649#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
650#[rustc_diagnostic_item = "ptr_copy"]
651#[ferrocene::prevalidated]
652pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize) {
653 // SAFETY: the safety contract for `copy` must be upheld by the caller.
654 unsafe {
655 ub_checks::assert_unsafe_precondition!(
656 check_language_ub,
657 "ptr::copy requires that both pointer arguments are aligned and non-null",
658 (
659 src: *const () = src as *const (),
660 dst: *mut () = dst as *mut (),
661 align: usize = align_of::<T>(),
662 zero_size: bool = T::IS_ZST || count == 0,
663 ) =>
664 ub_checks::maybe_is_aligned_and_not_null(src, align, zero_size)
665 && ub_checks::maybe_is_aligned_and_not_null(dst, align, zero_size)
666 );
667 crate::intrinsics::copy(src, dst, count)
668 }
669}
670
671/// Sets `count * size_of::<T>()` bytes of memory starting at `dst` to
672/// `val`.
673///
674/// `write_bytes` is similar to C's [`memset`], but sets `count *
675/// size_of::<T>()` bytes to `val`.
676///
677/// [`memset`]: https://en.cppreference.com/w/c/string/byte/memset
678///
679/// # Safety
680///
681/// Behavior is undefined if any of the following conditions are violated:
682///
683/// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes.
684///
685/// * `dst` must be properly aligned.
686///
687/// Note that even if the effectively copied size (`count * size_of::<T>()`) is
688/// `0`, the pointer must be properly aligned.
689///
690/// Additionally, note that changing `*dst` in this way can easily lead to undefined behavior (UB)
691/// later if the written bytes are not a valid representation of some `T`. For instance, the
692/// following is an **incorrect** use of this function:
693///
694/// ```rust,no_run
695/// unsafe {
696/// let mut value: u8 = 0;
697/// let ptr: *mut bool = &mut value as *mut u8 as *mut bool;
698/// let _bool = ptr.read(); // This is fine, `ptr` points to a valid `bool`.
699/// ptr.write_bytes(42u8, 1); // This function itself does not cause UB...
700/// let _bool = ptr.read(); // ...but it makes this operation UB! ⚠️
701/// }
702/// ```
703///
704/// [valid]: crate::ptr#safety
705///
706/// # Examples
707///
708/// Basic usage:
709///
710/// ```
711/// use std::ptr;
712///
713/// let mut vec = vec![0u32; 4];
714/// unsafe {
715/// let vec_ptr = vec.as_mut_ptr();
716/// ptr::write_bytes(vec_ptr, 0xfe, 2);
717/// }
718/// assert_eq!(vec, [0xfefefefe, 0xfefefefe, 0, 0]);
719/// ```
720#[doc(alias = "memset")]
721#[stable(feature = "rust1", since = "1.0.0")]
722#[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
723#[inline(always)]
724#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
725#[rustc_diagnostic_item = "ptr_write_bytes"]
726#[ferrocene::prevalidated]
727pub const unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize) {
728 // SAFETY: the safety contract for `write_bytes` must be upheld by the caller.
729 unsafe {
730 ub_checks::assert_unsafe_precondition!(
731 check_language_ub,
732 "ptr::write_bytes requires that the destination pointer is aligned and non-null",
733 (
734 addr: *const () = dst as *const (),
735 align: usize = align_of::<T>(),
736 zero_size: bool = T::IS_ZST || count == 0,
737 ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, zero_size)
738 );
739 crate::intrinsics::write_bytes(dst, val, count)
740 }
741}
742
743/// Executes the destructor (if any) of the pointed-to value.
744///
745/// This is almost the same as calling [`ptr::read`] and discarding
746/// the result, but has the following advantages:
747// FIXME: say something more useful than "almost the same"?
748// There are open questions here: `read` requires the value to be fully valid, e.g. if `T` is a
749// `bool` it must be 0 or 1, if it is a reference then it must be dereferenceable. `drop_in_place`
750// only requires that `*to_drop` be "valid for dropping" and we have not defined what that means. In
751// Miri it currently (May 2024) requires nothing at all for types without drop glue.
752///
753/// * It is *required* to use `drop_in_place` to drop unsized types like
754/// trait objects, because they can't be read out onto the stack and
755/// dropped normally.
756///
757/// * It is friendlier to the optimizer to do this over [`ptr::read`] when
758/// dropping manually allocated memory (e.g., in the implementations of
759/// `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
760/// sound to elide the copy.
761///
762/// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
763/// (pinned data must not be moved before it is dropped).
764///
765/// Unaligned values cannot be dropped in place, they must be copied to an aligned
766/// location first using [`ptr::read_unaligned`]. For packed structs, this move is
767/// done automatically by the compiler. This means the fields of packed structs
768/// are not dropped in-place.
769///
770/// [`ptr::read`]: self::read
771/// [`ptr::read_unaligned`]: self::read_unaligned
772/// [pinned]: crate::pin
773///
774/// # Safety
775///
776/// Behavior is undefined if any of the following conditions are violated:
777///
778/// * `to_drop` must be [valid] for both reads and writes.
779///
780/// * `to_drop` must be properly aligned, even if `T` has size 0.
781///
782/// * `to_drop` must be nonnull, even if `T` has size 0.
783///
784/// * The value `to_drop` points to must be valid for dropping, which may mean
785/// it must uphold additional invariants. These invariants depend on the type
786/// of the value being dropped. For instance, when dropping a Box, the box's
787/// pointer to the heap must be valid.
788///
789/// * While `drop_in_place` is executing, the only way to access parts of
790/// `to_drop` is through the `&mut self` references supplied to the
791/// `Drop::drop` methods that `drop_in_place` invokes.
792///
793/// Additionally, if `T` is not [`Copy`], using the pointed-to value after
794/// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
795/// foo` counts as a use because it will cause the value to be dropped
796/// again. [`write()`] can be used to overwrite data without causing it to be
797/// dropped.
798///
799/// [valid]: self#safety
800///
801/// # Examples
802///
803/// Manually remove the last item from a vector:
804///
805/// ```
806/// use std::ptr;
807/// use std::rc::Rc;
808///
809/// let last = Rc::new(1);
810/// let weak = Rc::downgrade(&last);
811///
812/// let mut v = vec![Rc::new(0), last];
813///
814/// unsafe {
815/// // Get a raw pointer to the last element in `v`.
816/// let ptr = &mut v[1] as *mut _;
817/// // Shorten `v` to prevent the last item from being dropped. We do that first,
818/// // to prevent issues if the `drop_in_place` below panics.
819/// v.set_len(1);
820/// // Without a call `drop_in_place`, the last item would never be dropped,
821/// // and the memory it manages would be leaked.
822/// ptr::drop_in_place(ptr);
823/// }
824///
825/// assert_eq!(v, &[0.into()]);
826///
827/// // Ensure that the last item was dropped.
828/// assert!(weak.upgrade().is_none());
829/// ```
830#[ferrocene::prevalidated]
831#[inline(always)]
832#[stable(feature = "drop_in_place", since = "1.8.0")]
833#[rustc_diagnostic_item = "ptr_drop_in_place"]
834#[rustc_const_unstable(feature = "const_drop_in_place", issue = "109342")]
835pub const unsafe fn drop_in_place<T: PointeeSized>(to_drop: *mut T)
836where
837 T: [const] Destruct,
838{
839 // Due to historic reasons, `drop_in_place` takes a pointer rather than a reference,
840 // which results in worse codegen since we don't apply noalias/dereferenceable llvm
841 // attributes to pointer arguments. To workaround this without breaking public
842 // interface, `drop_in_place` calls the lang item, rather than being one directly.
843
844 // SAFETY:
845 // - compiler glue has the same safety requirements as this function
846 // - the pointer must be valid as per the safety requirement of this function
847 unsafe { drop_glue(&mut *to_drop) }
848}
849
850/// Helper function for `drop_in_place`. The compiler replaces this by the actual drop glue.
851#[ferrocene::prevalidated]
852#[lang = "drop_glue"]
853pub(crate) const unsafe fn drop_glue<T: PointeeSized>(_: &mut T)
854where
855 T: [const] Destruct,
856{
857 // Code here does not matter - this is replaced by the
858 // real drop glue by the compiler.
859}
860
861/// Creates a null raw pointer.
862///
863/// This function is equivalent to zero-initializing the pointer:
864/// `MaybeUninit::<*const T>::zeroed().assume_init()`.
865/// The resulting pointer has the address 0.
866///
867/// # Examples
868///
869/// ```
870/// use std::ptr;
871///
872/// let p: *const i32 = ptr::null();
873/// assert!(p.is_null());
874/// assert_eq!(p as usize, 0); // this pointer has the address 0
875/// ```
876#[inline(always)]
877#[must_use]
878#[stable(feature = "rust1", since = "1.0.0")]
879#[rustc_promotable]
880#[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
881#[rustc_diagnostic_item = "ptr_null"]
882#[ferrocene::prevalidated]
883pub const fn null<T: PointeeSized + Thin>() -> *const T {
884 from_raw_parts(without_provenance::<()>(0), ())
885}
886
887/// Creates a null mutable raw pointer.
888///
889/// This function is equivalent to zero-initializing the pointer:
890/// `MaybeUninit::<*mut T>::zeroed().assume_init()`.
891/// The resulting pointer has the address 0.
892///
893/// # Examples
894///
895/// ```
896/// use std::ptr;
897///
898/// let p: *mut i32 = ptr::null_mut();
899/// assert!(p.is_null());
900/// assert_eq!(p as usize, 0); // this pointer has the address 0
901/// ```
902#[inline(always)]
903#[must_use]
904#[stable(feature = "rust1", since = "1.0.0")]
905#[rustc_promotable]
906#[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
907#[rustc_diagnostic_item = "ptr_null_mut"]
908#[ferrocene::prevalidated]
909pub const fn null_mut<T: PointeeSized + Thin>() -> *mut T {
910 from_raw_parts_mut(without_provenance_mut::<()>(0), ())
911}
912
913/// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
914///
915/// This is equivalent to `ptr::null().with_addr(addr)`.
916///
917/// Without provenance, this pointer is not associated with any actual allocation. Such a
918/// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but
919/// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are
920/// little more than a `usize` address in disguise.
921///
922/// This is different from `addr as *const T`, which creates a pointer that picks up a previously
923/// exposed provenance. See [`with_exposed_provenance`] for more details on that operation.
924///
925/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
926#[inline(always)]
927#[must_use]
928#[stable(feature = "strict_provenance", since = "1.84.0")]
929#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
930#[rustc_diagnostic_item = "ptr_without_provenance"]
931#[ferrocene::prevalidated]
932pub const fn without_provenance<T>(addr: usize) -> *const T {
933 without_provenance_mut(addr)
934}
935
936/// Creates a new pointer that is dangling, but non-null and well-aligned.
937///
938/// This is useful for initializing types which lazily allocate, like
939/// `Vec::new` does.
940///
941/// Note that the address of the returned pointer may potentially
942/// be that of a valid pointer, which means this must not be used
943/// as a "not yet initialized" sentinel value.
944/// Types that lazily allocate must track initialization by some other means.
945#[inline(always)]
946#[must_use]
947#[stable(feature = "strict_provenance", since = "1.84.0")]
948#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
949pub const fn dangling<T>() -> *const T {
950 dangling_mut()
951}
952
953/// Creates a pointer with the given address and no [provenance][crate::ptr#provenance].
954///
955/// This is equivalent to `ptr::null_mut().with_addr(addr)`.
956///
957/// Without provenance, this pointer is not associated with any actual allocation. Such a
958/// no-provenance pointer may be used for zero-sized memory accesses (if suitably aligned), but
959/// non-zero-sized memory accesses with a no-provenance pointer are UB. No-provenance pointers are
960/// little more than a `usize` address in disguise.
961///
962/// This is different from `addr as *mut T`, which creates a pointer that picks up a previously
963/// exposed provenance. See [`with_exposed_provenance_mut`] for more details on that operation.
964///
965/// This is a [Strict Provenance][crate::ptr#strict-provenance] API.
966#[inline(always)]
967#[must_use]
968#[stable(feature = "strict_provenance", since = "1.84.0")]
969#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
970#[rustc_diagnostic_item = "ptr_without_provenance_mut"]
971#[allow(integer_to_ptr_transmutes)] // Expected semantics here.
972#[ferrocene::prevalidated]
973pub const fn without_provenance_mut<T>(addr: usize) -> *mut T {
974 // An int-to-pointer transmute currently has exactly the intended semantics: it creates a
975 // pointer without provenance. Note that this is *not* a stable guarantee about transmute
976 // semantics, it relies on sysroot crates having special status.
977 // SAFETY: every valid integer is also a valid pointer (as long as you don't dereference that
978 // pointer).
979 unsafe { mem::transmute(addr) }
980}
981
982/// Creates a new pointer that is dangling, but non-null and well-aligned.
983///
984/// This is useful for initializing types which lazily allocate, like
985/// `Vec::new` does.
986///
987/// Note that the address of the returned pointer may potentially
988/// be that of a valid pointer, which means this must not be used
989/// as a "not yet initialized" sentinel value.
990/// Types that lazily allocate must track initialization by some other means.
991#[inline(always)]
992#[must_use]
993#[stable(feature = "strict_provenance", since = "1.84.0")]
994#[rustc_const_stable(feature = "strict_provenance", since = "1.84.0")]
995pub const fn dangling_mut<T>() -> *mut T {
996 NonNull::dangling().as_ptr()
997}
998
999/// Converts an address back to a pointer, picking up some previously 'exposed'
1000/// [provenance][crate::ptr#provenance].
1001///
1002/// This is fully equivalent to `addr as *const T`. The provenance of the returned pointer is that
1003/// of *some* pointer that was previously exposed by passing it to
1004/// [`expose_provenance`][pointer::expose_provenance], or a `ptr as usize` cast. In addition, memory
1005/// which is outside the control of the Rust abstract machine (MMIO registers, for example) is
1006/// always considered to be accessible with an exposed provenance, so long as this memory is disjoint
1007/// from memory that will be used by the abstract machine such as the stack, heap, and statics.
1008///
1009/// The exact provenance that gets picked is not specified. The compiler will do its best to pick
1010/// the "right" provenance for you (whatever that may be), but currently we cannot provide any
1011/// guarantees about which provenance the resulting pointer will have -- and therefore there
1012/// is no definite specification for which memory the resulting pointer may access.
1013///
1014/// If there is *no* previously 'exposed' provenance that justifies the way the returned pointer
1015/// will be used, the program has undefined behavior. In particular, the aliasing rules still apply:
1016/// pointers and references that have been invalidated due to aliasing accesses cannot be used
1017/// anymore, even if they have been exposed!
1018///
1019/// Due to its inherent ambiguity, this operation may not be supported by tools that help you to
1020/// stay conformant with the Rust memory model. It is recommended to use [Strict
1021/// Provenance][self#strict-provenance] APIs such as [`with_addr`][pointer::with_addr] wherever
1022/// possible.
1023///
1024/// On most platforms this will produce a value with the same bytes as the address. Platforms
1025/// which need to store additional information in a pointer may not support this operation,
1026/// since it is generally not possible to actually *compute* which provenance the returned
1027/// pointer has to pick up.
1028///
1029/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
1030#[must_use]
1031#[inline(always)]
1032#[stable(feature = "exposed_provenance", since = "1.84.0")]
1033#[rustc_const_stable(feature = "const_exposed_provenance", since = "1.91.0")]
1034#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1035#[allow(implicit_provenance_casts)] // this *is* the explicit provenance API one should use instead
1036pub const fn with_exposed_provenance<T>(addr: usize) -> *const T {
1037 addr as *const T
1038}
1039
1040/// Converts an address back to a mutable pointer, picking up some previously 'exposed'
1041/// [provenance][crate::ptr#provenance].
1042///
1043/// This is fully equivalent to `addr as *mut T`. The provenance of the returned pointer is that
1044/// of *some* pointer that was previously exposed by passing it to
1045/// [`expose_provenance`][pointer::expose_provenance], or a `ptr as usize` cast. In addition, memory
1046/// which is outside the control of the Rust abstract machine (MMIO registers, for example) is
1047/// always considered to be accessible with an exposed provenance, so long as this memory is disjoint
1048/// from memory that will be used by the abstract machine such as the stack, heap, and statics.
1049///
1050/// The exact provenance that gets picked is not specified. The compiler will do its best to pick
1051/// the "right" provenance for you (whatever that may be), but currently we cannot provide any
1052/// guarantees about which provenance the resulting pointer will have -- and therefore there
1053/// is no definite specification for which memory the resulting pointer may access.
1054///
1055/// If there is *no* previously 'exposed' provenance that justifies the way the returned pointer
1056/// will be used, the program has undefined behavior. In particular, the aliasing rules still apply:
1057/// pointers and references that have been invalidated due to aliasing accesses cannot be used
1058/// anymore, even if they have been exposed!
1059///
1060/// Due to its inherent ambiguity, this operation may not be supported by tools that help you to
1061/// stay conformant with the Rust memory model. It is recommended to use [Strict
1062/// Provenance][self#strict-provenance] APIs such as [`with_addr`][pointer::with_addr] wherever
1063/// possible.
1064///
1065/// On most platforms this will produce a value with the same bytes as the address. Platforms
1066/// which need to store additional information in a pointer may not support this operation,
1067/// since it is generally not possible to actually *compute* which provenance the returned
1068/// pointer has to pick up.
1069///
1070/// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API.
1071#[must_use]
1072#[inline(always)]
1073#[stable(feature = "exposed_provenance", since = "1.84.0")]
1074#[rustc_const_stable(feature = "const_exposed_provenance", since = "1.91.0")]
1075#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1076#[allow(implicit_provenance_casts)] // this *is* the explicit provenance API one should use instead
1077pub const fn with_exposed_provenance_mut<T>(addr: usize) -> *mut T {
1078 addr as *mut T
1079}
1080
1081/// Converts a reference to a raw pointer.
1082///
1083/// For `r: &T`, `from_ref(r)` is equivalent to `r as *const T` (except for the caveat noted below),
1084/// but is a bit safer since it will never silently change type or mutability, in particular if the
1085/// code is refactored.
1086///
1087/// The caller must ensure that the pointee outlives the pointer this function returns, or else it
1088/// will end up dangling.
1089///
1090/// The caller must also ensure that the memory the pointer (non-transitively) points to is never
1091/// written to (except inside an `UnsafeCell`) using this pointer or any pointer derived from it. If
1092/// you need to mutate the pointee, use [`from_mut`]. Specifically, to turn a mutable reference `m:
1093/// &mut T` into `*const T`, prefer `from_mut(m).cast_const()` to obtain a pointer that can later be
1094/// used for mutation.
1095///
1096/// ## Interaction with lifetime extension
1097///
1098/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in
1099/// tail expressions. This code is valid, albeit in a non-obvious way:
1100/// ```rust
1101/// # type T = i32;
1102/// # fn foo() -> T { 42 }
1103/// // The temporary holding the return value of `foo` has its lifetime extended,
1104/// // because the surrounding expression involves no function call.
1105/// let p = &foo() as *const T;
1106/// unsafe { p.read() };
1107/// ```
1108/// Naively replacing the cast with `from_ref` is not valid:
1109/// ```rust,no_run
1110/// # use std::ptr;
1111/// # type T = i32;
1112/// # fn foo() -> T { 42 }
1113/// // The temporary holding the return value of `foo` does *not* have its lifetime extended,
1114/// // because the surrounding expression involves a function call.
1115/// let p = ptr::from_ref(&foo());
1116/// unsafe { p.read() }; // UB! Reading from a dangling pointer ⚠️
1117/// ```
1118/// The recommended way to write this code is to avoid relying on lifetime extension
1119/// when raw pointers are involved:
1120/// ```rust
1121/// # use std::ptr;
1122/// # type T = i32;
1123/// # fn foo() -> T { 42 }
1124/// let x = foo();
1125/// let p = ptr::from_ref(&x);
1126/// unsafe { p.read() };
1127/// ```
1128#[inline(always)]
1129#[must_use]
1130#[stable(feature = "ptr_from_ref", since = "1.76.0")]
1131#[rustc_const_stable(feature = "ptr_from_ref", since = "1.76.0")]
1132#[rustc_never_returns_null_ptr]
1133#[rustc_diagnostic_item = "ptr_from_ref"]
1134#[ferrocene::prevalidated]
1135pub const fn from_ref<T: PointeeSized>(r: &T) -> *const T {
1136 r
1137}
1138
1139/// Converts a mutable reference to a raw pointer.
1140///
1141/// For `r: &mut T`, `from_mut(r)` is equivalent to `r as *mut T` (except for the caveat noted
1142/// below), but is a bit safer since it will never silently change type or mutability, in particular
1143/// if the code is refactored.
1144///
1145/// The caller must ensure that the pointee outlives the pointer this function returns, or else it
1146/// will end up dangling.
1147///
1148/// ## Interaction with lifetime extension
1149///
1150/// Note that this has subtle interactions with the rules for lifetime extension of temporaries in
1151/// tail expressions. This code is valid, albeit in a non-obvious way:
1152/// ```rust
1153/// # type T = i32;
1154/// # fn foo() -> T { 42 }
1155/// // The temporary holding the return value of `foo` has its lifetime extended,
1156/// // because the surrounding expression involves no function call.
1157/// let p = &mut foo() as *mut T;
1158/// unsafe { p.write(T::default()) };
1159/// ```
1160/// Naively replacing the cast with `from_mut` is not valid:
1161/// ```rust,no_run
1162/// # use std::ptr;
1163/// # type T = i32;
1164/// # fn foo() -> T { 42 }
1165/// // The temporary holding the return value of `foo` does *not* have its lifetime extended,
1166/// // because the surrounding expression involves a function call.
1167/// let p = ptr::from_mut(&mut foo());
1168/// unsafe { p.write(T::default()) }; // UB! Writing to a dangling pointer ⚠️
1169/// ```
1170/// The recommended way to write this code is to avoid relying on lifetime extension
1171/// when raw pointers are involved:
1172/// ```rust
1173/// # use std::ptr;
1174/// # type T = i32;
1175/// # fn foo() -> T { 42 }
1176/// let mut x = foo();
1177/// let p = ptr::from_mut(&mut x);
1178/// unsafe { p.write(T::default()) };
1179/// ```
1180#[inline(always)]
1181#[must_use]
1182#[stable(feature = "ptr_from_ref", since = "1.76.0")]
1183#[rustc_const_stable(feature = "ptr_from_ref", since = "1.76.0")]
1184#[rustc_never_returns_null_ptr]
1185pub const fn from_mut<T: PointeeSized>(r: &mut T) -> *mut T {
1186 r
1187}
1188
1189/// Forms a raw slice from a pointer and a length.
1190///
1191/// The `len` argument is the number of **elements**, not the number of bytes.
1192///
1193/// This function is safe, but actually using the return value is unsafe.
1194/// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
1195///
1196/// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
1197///
1198/// # Examples
1199///
1200/// ```rust
1201/// use std::ptr;
1202///
1203/// // create a slice pointer when starting out with a pointer to the first element
1204/// let x = [5, 6, 7];
1205/// let raw_pointer = x.as_ptr();
1206/// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
1207/// assert_eq!(unsafe { &*slice }[2], 7);
1208/// ```
1209///
1210/// You must ensure that the pointer is valid and not null before dereferencing
1211/// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1212///
1213/// ```rust,should_panic
1214/// use std::ptr;
1215/// let danger: *const [u8] = ptr::slice_from_raw_parts(ptr::null(), 0);
1216/// unsafe {
1217/// danger.as_ref().expect("references must not be null");
1218/// }
1219/// ```
1220#[inline]
1221#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
1222#[rustc_const_stable(feature = "const_slice_from_raw_parts", since = "1.64.0")]
1223#[rustc_diagnostic_item = "ptr_slice_from_raw_parts"]
1224#[ferrocene::prevalidated]
1225pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
1226 from_raw_parts(data, len)
1227}
1228
1229/// Forms a raw mutable slice from a pointer and a length.
1230///
1231/// The `len` argument is the number of **elements**, not the number of bytes.
1232///
1233/// Performs the same functionality as [`slice_from_raw_parts`], except that a
1234/// raw mutable slice is returned, as opposed to a raw immutable slice.
1235///
1236/// This function is safe, but actually using the return value is unsafe.
1237/// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
1238///
1239/// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
1240///
1241/// # Examples
1242///
1243/// ```rust
1244/// use std::ptr;
1245///
1246/// let x = &mut [5, 6, 7];
1247/// let raw_pointer = x.as_mut_ptr();
1248/// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
1249///
1250/// unsafe {
1251/// (*slice)[2] = 99; // assign a value at an index in the slice
1252/// };
1253///
1254/// assert_eq!(unsafe { &*slice }[2], 99);
1255/// ```
1256///
1257/// You must ensure that the pointer is valid and not null before dereferencing
1258/// the raw slice. A slice reference must never have a null pointer, even if it's empty.
1259///
1260/// ```rust,should_panic
1261/// use std::ptr;
1262/// let danger: *mut [u8] = ptr::slice_from_raw_parts_mut(ptr::null_mut(), 0);
1263/// unsafe {
1264/// danger.as_mut().expect("references must not be null");
1265/// }
1266/// ```
1267#[inline]
1268#[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
1269#[rustc_const_stable(feature = "const_slice_from_raw_parts_mut", since = "1.83.0")]
1270#[rustc_diagnostic_item = "ptr_slice_from_raw_parts_mut"]
1271#[ferrocene::prevalidated]
1272pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
1273 from_raw_parts_mut(data, len)
1274}
1275
1276/// Swaps the values at two mutable locations of the same type, without
1277/// deinitializing either.
1278///
1279/// But for the following exceptions, this function is semantically
1280/// equivalent to [`mem::swap`]:
1281///
1282/// * It operates on raw pointers instead of references. When references are
1283/// available, [`mem::swap`] should be preferred.
1284///
1285/// * The two pointed-to values may overlap. If the values do overlap, then the
1286/// overlapping region of memory from `x` will be used. This is demonstrated
1287/// in the second example below.
1288///
1289/// * The operation is "untyped" in the sense that data may be uninitialized or otherwise violate
1290/// the requirements of `T`. The initialization state is preserved exactly.
1291///
1292/// # Safety
1293///
1294/// Behavior is undefined if any of the following conditions are violated:
1295///
1296/// * Both `x` and `y` must be [valid] for both reads and writes. They must remain valid even when the
1297/// other pointer is written. (This means if the memory ranges overlap, the two pointers must not
1298/// be subject to aliasing restrictions relative to each other.)
1299///
1300/// * Both `x` and `y` must be properly aligned.
1301///
1302/// Note that even if `T` has size `0`, the pointers must be properly aligned.
1303///
1304/// [valid]: self#safety
1305///
1306/// # Examples
1307///
1308/// Swapping two non-overlapping regions:
1309///
1310/// ```
1311/// use std::ptr;
1312///
1313/// let mut array = [0, 1, 2, 3];
1314///
1315/// let (x, y) = array.split_at_mut(2);
1316/// let x = x.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[0..2]`
1317/// let y = y.as_mut_ptr().cast::<[u32; 2]>(); // this is `array[2..4]`
1318///
1319/// unsafe {
1320/// ptr::swap(x, y);
1321/// assert_eq!([2, 3, 0, 1], array);
1322/// }
1323/// ```
1324///
1325/// Swapping two overlapping regions:
1326///
1327/// ```
1328/// use std::ptr;
1329///
1330/// let mut array: [i32; 4] = [0, 1, 2, 3];
1331///
1332/// let array_ptr: *mut i32 = array.as_mut_ptr();
1333///
1334/// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
1335/// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
1336///
1337/// unsafe {
1338/// ptr::swap(x, y);
1339/// // The indices `1..3` of the slice overlap between `x` and `y`.
1340/// // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
1341/// // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
1342/// // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
1343/// // This implementation is defined to make the latter choice.
1344/// assert_eq!([1, 0, 1, 2], array);
1345/// }
1346/// ```
1347#[inline(always)]
1348#[stable(feature = "rust1", since = "1.0.0")]
1349#[rustc_const_stable(feature = "const_swap", since = "1.85.0")]
1350#[rustc_diagnostic_item = "ptr_swap"]
1351#[ferrocene::prevalidated]
1352pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
1353 // Give ourselves some scratch space to work with.
1354 // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
1355 let mut tmp = MaybeUninit::<T>::uninit();
1356
1357 // Perform the swap
1358 // SAFETY: the caller must guarantee that `x` and `y` are
1359 // valid for writes and properly aligned. `tmp` cannot be
1360 // overlapping either `x` or `y` because `tmp` was just allocated
1361 // on the stack as a separate allocation.
1362 unsafe {
1363 copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
1364 copy(y, x, 1); // `x` and `y` may overlap
1365 copy_nonoverlapping(tmp.as_ptr(), y, 1);
1366 }
1367}
1368
1369/// Swaps `count * size_of::<T>()` bytes between the two regions of memory
1370/// beginning at `x` and `y`. The two regions must *not* overlap.
1371///
1372/// The operation is "untyped" in the sense that data may be uninitialized or otherwise violate the
1373/// requirements of `T`. The initialization state is preserved exactly.
1374///
1375/// # Safety
1376///
1377/// Behavior is undefined if any of the following conditions are violated:
1378///
1379/// * Both `x` and `y` must be [valid] for both reads and writes of `count *
1380/// size_of::<T>()` bytes.
1381///
1382/// * Both `x` and `y` must be properly aligned.
1383///
1384/// * The region of memory beginning at `x` with a size of `count *
1385/// size_of::<T>()` bytes must *not* overlap with the region of memory
1386/// beginning at `y` with the same size.
1387///
1388/// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
1389/// the pointers must be properly aligned.
1390///
1391/// [valid]: self#safety
1392///
1393/// # Examples
1394///
1395/// Basic usage:
1396///
1397/// ```
1398/// use std::ptr;
1399///
1400/// let mut x = [1, 2, 3, 4];
1401/// let mut y = [7, 8, 9];
1402///
1403/// unsafe {
1404/// ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
1405/// }
1406///
1407/// assert_eq!(x, [7, 8, 3, 4]);
1408/// assert_eq!(y, [1, 2, 9]);
1409/// ```
1410#[inline]
1411#[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
1412#[rustc_const_stable(feature = "const_swap_nonoverlapping", since = "1.88.0")]
1413#[rustc_diagnostic_item = "ptr_swap_nonoverlapping"]
1414#[rustc_allow_const_fn_unstable(const_eval_select)] // both implementations behave the same
1415#[track_caller]
1416#[ferrocene::prevalidated]
1417pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
1418 ub_checks::assert_unsafe_precondition!(
1419 check_library_ub,
1420 "ptr::swap_nonoverlapping requires that both pointer arguments are aligned and non-null \
1421 and the specified memory ranges do not overlap",
1422 (
1423 x: *mut () = x as *mut (),
1424 y: *mut () = y as *mut (),
1425 size: usize = size_of::<T>(),
1426 align: usize = align_of::<T>(),
1427 count: usize = count,
1428 ) => {
1429 let zero_size = size == 0 || count == 0;
1430 ub_checks::maybe_is_aligned_and_not_null(x, align, zero_size)
1431 && ub_checks::maybe_is_aligned_and_not_null(y, align, zero_size)
1432 && ub_checks::maybe_is_nonoverlapping(x, y, size, count)
1433 }
1434 );
1435
1436 const_eval_select!(
1437 @capture[T] { x: *mut T, y: *mut T, count: usize }:
1438 if const {
1439 // At compile-time we don't need all the special code below.
1440 // SAFETY: Same preconditions as this function
1441 unsafe { swap_nonoverlapping_const(x, y, count) }
1442 } else {
1443 // Going though a slice here helps codegen know the size fits in `isize`
1444 let slice = slice_from_raw_parts_mut(x, count);
1445 // SAFETY: This is all readable from the pointer, meaning it's one
1446 // allocation, and thus cannot be more than isize::MAX bytes.
1447 let bytes = unsafe { mem::size_of_val_raw::<[T]>(slice) };
1448 if let Some(bytes) = NonZero::new(bytes) {
1449 // SAFETY: These are the same ranges, just expressed in a different
1450 // type, so they're still non-overlapping.
1451 unsafe { swap_nonoverlapping_bytes(x.cast(), y.cast(), bytes) };
1452 }
1453 }
1454 )
1455}
1456
1457/// Same behavior and safety conditions as [`swap_nonoverlapping`]
1458#[ferrocene::annotation(
1459 "This function is only called inside `swap_nonoverlapping` as the `const` arm of a `const_eval_select!` so it cannot be covered"
1460)]
1461#[inline]
1462#[ferrocene::prevalidated]
1463const unsafe fn swap_nonoverlapping_const<T>(x: *mut T, y: *mut T, count: usize) {
1464 let mut i = 0;
1465 while i < count {
1466 // SAFETY: By precondition, `i` is in-bounds because it's below `n`
1467 let x = unsafe { x.add(i) };
1468 // SAFETY: By precondition, `i` is in-bounds because it's below `n`
1469 // and it's distinct from `x` since the ranges are non-overlapping
1470 let y = unsafe { y.add(i) };
1471
1472 // SAFETY: we're only ever given pointers that are valid to read/write,
1473 // including being aligned, and nothing here panics so it's drop-safe.
1474 unsafe {
1475 // Note that it's critical that these use `copy_nonoverlapping`,
1476 // rather than `read`/`write`, to avoid #134713 if T has padding.
1477 let mut temp = MaybeUninit::<T>::uninit();
1478 copy_nonoverlapping(x, temp.as_mut_ptr(), 1);
1479 copy_nonoverlapping(y, x, 1);
1480 copy_nonoverlapping(temp.as_ptr(), y, 1);
1481 }
1482
1483 i += 1;
1484 }
1485}
1486
1487// Don't let MIR inline this, because we really want it to keep its noalias metadata
1488#[rustc_no_mir_inline]
1489#[inline]
1490#[ferrocene::prevalidated]
1491fn swap_chunk<const N: usize>(x: &mut MaybeUninit<[u8; N]>, y: &mut MaybeUninit<[u8; N]>) {
1492 let a = *x;
1493 let b = *y;
1494 *x = b;
1495 *y = a;
1496}
1497
1498#[inline]
1499#[ferrocene::prevalidated]
1500unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, bytes: NonZero<usize>) {
1501 // Same as `swap_nonoverlapping::<[u8; N]>`.
1502 #[ferrocene::prevalidated]
1503 unsafe fn swap_nonoverlapping_chunks<const N: usize>(
1504 x: *mut MaybeUninit<[u8; N]>,
1505 y: *mut MaybeUninit<[u8; N]>,
1506 chunks: NonZero<usize>,
1507 ) {
1508 let chunks = chunks.get();
1509 for i in 0..chunks {
1510 // SAFETY: i is in [0, chunks) so the adds and dereferences are in-bounds.
1511 unsafe { swap_chunk(&mut *x.add(i), &mut *y.add(i)) };
1512 }
1513 }
1514
1515 // Same as `swap_nonoverlapping_bytes`, but accepts at most 1+2+4=7 bytes
1516 #[inline]
1517 #[ferrocene::prevalidated]
1518 unsafe fn swap_nonoverlapping_short(x: *mut u8, y: *mut u8, bytes: NonZero<usize>) {
1519 // Tail handling for auto-vectorized code sometimes has element-at-a-time behaviour,
1520 // see <https://github.com/rust-lang/rust/issues/134946>.
1521 // By swapping as different sizes, rather than as a loop over bytes,
1522 // we make sure not to end up with, say, seven byte-at-a-time copies.
1523
1524 let bytes = bytes.get();
1525 let mut i = 0;
1526 macro_rules! swap_prefix {
1527 ($($n:literal)+) => {$(
1528 if (bytes & $n) != 0 {
1529 // SAFETY: `i` can only have the same bits set as those in bytes,
1530 // so these `add`s are in-bounds of `bytes`. But the bit for
1531 // `$n` hasn't been set yet, so the `$n` bytes that `swap_chunk`
1532 // will read and write are within the usable range.
1533 unsafe { swap_chunk::<$n>(&mut*x.add(i).cast(), &mut*y.add(i).cast()) };
1534 i |= $n;
1535 }
1536 )+};
1537 }
1538 swap_prefix!(4 2 1);
1539 debug_assert_eq!(i, bytes);
1540 }
1541
1542 const CHUNK_SIZE: usize = size_of::<*const ()>();
1543 let bytes = bytes.get();
1544
1545 let chunks = bytes / CHUNK_SIZE;
1546 let tail = bytes % CHUNK_SIZE;
1547 if let Some(chunks) = NonZero::new(chunks) {
1548 // SAFETY: this is bytes/CHUNK_SIZE*CHUNK_SIZE bytes, which is <= bytes,
1549 // so it's within the range of our non-overlapping bytes.
1550 unsafe { swap_nonoverlapping_chunks::<CHUNK_SIZE>(x.cast(), y.cast(), chunks) };
1551 }
1552 if let Some(tail) = NonZero::new(tail) {
1553 const { assert!(CHUNK_SIZE <= 8) };
1554 let delta = chunks * CHUNK_SIZE;
1555 // SAFETY: the tail length is below CHUNK SIZE because of the remainder,
1556 // and CHUNK_SIZE is at most 8 by the const assert, so tail <= 7
1557 unsafe { swap_nonoverlapping_short(x.add(delta), y.add(delta), tail) };
1558 }
1559}
1560
1561/// Moves `src` into the pointed `dst`, returning the previous `dst` value.
1562///
1563/// Neither value is dropped.
1564///
1565/// This function is semantically equivalent to [`mem::replace`] except that it
1566/// operates on raw pointers instead of references. When references are
1567/// available, [`mem::replace`] should be preferred.
1568///
1569/// # Safety
1570///
1571/// Behavior is undefined if any of the following conditions are violated:
1572///
1573/// * `dst` must be [valid] for both reads and writes or `T` must be a ZST.
1574///
1575/// * `dst` must be properly aligned.
1576///
1577/// * `dst` must point to a properly initialized value of type `T`.
1578///
1579/// Note that even if `T` has size `0`, the pointer must be properly aligned.
1580///
1581/// [valid]: self#safety
1582///
1583/// # Examples
1584///
1585/// ```
1586/// use std::ptr;
1587///
1588/// let mut rust = vec!['b', 'u', 's', 't'];
1589///
1590/// // `mem::replace` would have the same effect without requiring the unsafe
1591/// // block.
1592/// let b = unsafe {
1593/// ptr::replace(&mut rust[0], 'r')
1594/// };
1595///
1596/// assert_eq!(b, 'b');
1597/// assert_eq!(rust, &['r', 'u', 's', 't']);
1598/// ```
1599#[inline(always)]
1600#[stable(feature = "rust1", since = "1.0.0")]
1601#[rustc_const_stable(feature = "const_replace", since = "1.83.0")]
1602#[rustc_diagnostic_item = "ptr_replace"]
1603#[track_caller]
1604#[ferrocene::prevalidated]
1605pub const unsafe fn replace<T>(dst: *mut T, src: T) -> T {
1606 // SAFETY: the caller must guarantee that `dst` is valid to be
1607 // cast to a mutable reference (valid for writes, aligned, initialized),
1608 // and cannot overlap `src` since `dst` must point to a distinct
1609 // allocation. We are excluding null (with a ZST check) before creating a reference.
1610 unsafe {
1611 ub_checks::assert_unsafe_precondition!(
1612 check_language_ub,
1613 "ptr::replace requires that the pointer argument is aligned and non-null",
1614 (
1615 addr: *const () = dst as *const (),
1616 align: usize = align_of::<T>(),
1617 is_zst: bool = T::IS_ZST,
1618 ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst)
1619 );
1620 if T::IS_ZST {
1621 // If `T` is a ZST, `dst` is allowed to be null. However, we also don't have to actually
1622 // do anything since there isn't actually any data to be copied anyway. All values of
1623 // type `T` are bit-identical, so we can just return `src` here.
1624 return src;
1625 }
1626 mem::replace(&mut *dst, src)
1627 }
1628}
1629
1630/// Reads the value from `src` without moving it. This leaves the
1631/// memory in `src` unchanged.
1632///
1633/// # Safety
1634///
1635/// Behavior is undefined if any of the following conditions are violated:
1636///
1637/// * `src` must be [valid] for reads or `T` must be a ZST.
1638///
1639/// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
1640/// case.
1641///
1642/// * `src` must point to a properly initialized value of type `T`.
1643///
1644/// Note that even if `T` has size `0`, the pointer must be properly aligned.
1645///
1646/// Care must be taken around [ownership of the returned value](#ownership-of-the-returned-value).
1647///
1648/// # Examples
1649///
1650/// Basic usage:
1651///
1652/// ```
1653/// let x = 12;
1654/// let y = &x as *const i32;
1655///
1656/// unsafe {
1657/// assert_eq!(std::ptr::read(y), 12);
1658/// }
1659/// ```
1660///
1661/// Manually implement [`mem::swap`]:
1662///
1663/// ```
1664/// use std::ptr;
1665///
1666/// fn swap<T>(a: &mut T, b: &mut T) {
1667/// unsafe {
1668/// // Create a bitwise copy of the value at `a` in `tmp`.
1669/// let tmp = ptr::read(a);
1670///
1671/// // Exiting at this point (either by explicitly returning or by
1672/// // calling a function which panics) would cause the value in `tmp` to
1673/// // be dropped while the same value is still referenced by `a`. This
1674/// // could trigger undefined behavior if `T` is not `Copy`.
1675///
1676/// // Create a bitwise copy of the value at `b` in `a`.
1677/// // This is safe because mutable references cannot alias.
1678/// ptr::copy_nonoverlapping(b, a, 1);
1679///
1680/// // As above, exiting here could trigger undefined behavior because
1681/// // the same value is referenced by `a` and `b`.
1682///
1683/// // Move `tmp` into `b`.
1684/// ptr::write(b, tmp);
1685///
1686/// // `tmp` has been moved (`write` takes ownership of its second argument),
1687/// // so nothing is dropped implicitly here.
1688/// }
1689/// }
1690///
1691/// let mut foo = "foo".to_owned();
1692/// let mut bar = "bar".to_owned();
1693///
1694/// swap(&mut foo, &mut bar);
1695///
1696/// assert_eq!(foo, "bar");
1697/// assert_eq!(bar, "foo");
1698/// ```
1699///
1700/// ## Ownership of the Returned Value
1701///
1702/// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
1703/// If `T` is not [`Copy`], using both the returned value and the value at
1704/// `*src` can violate memory safety. Note that assigning to `*src` counts as a
1705/// use because it will attempt to drop the value at `*src`.
1706///
1707/// [`write()`] can be used to overwrite data without causing it to be dropped.
1708///
1709/// ```
1710/// use std::ptr;
1711///
1712/// let mut s = String::from("foo");
1713/// unsafe {
1714/// // `s2` now points to the same underlying memory as `s`.
1715/// let mut s2: String = ptr::read(&s);
1716///
1717/// assert_eq!(s2, "foo");
1718///
1719/// // Assigning to `s2` causes its original value to be dropped. Beyond
1720/// // this point, `s` must no longer be used, as the underlying memory has
1721/// // been freed.
1722/// s2 = String::default();
1723/// assert_eq!(s2, "");
1724///
1725/// // Assigning to `s` would cause the old value to be dropped again,
1726/// // resulting in undefined behavior.
1727/// // s = String::from("bar"); // ERROR
1728///
1729/// // `ptr::write` can be used to overwrite a value without dropping it.
1730/// ptr::write(&mut s, String::from("bar"));
1731/// }
1732///
1733/// assert_eq!(s, "bar");
1734/// ```
1735///
1736/// [valid]: self#safety
1737#[inline(always)]
1738#[stable(feature = "rust1", since = "1.0.0")]
1739#[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1740#[track_caller]
1741#[rustc_diagnostic_item = "ptr_read"]
1742#[ferrocene::prevalidated]
1743pub const unsafe fn read<T>(src: *const T) -> T {
1744 // It would be semantically correct to implement this via `copy_nonoverlapping`
1745 // and `MaybeUninit`, as was done before PR #109035. Calling `assume_init`
1746 // provides enough information to know that this is a typed operation.
1747
1748 // However, as of March 2023 the compiler was not capable of taking advantage
1749 // of that information. Thus, the implementation here switched to an intrinsic,
1750 // which lowers to `_0 = *src` in MIR, to address a few issues:
1751 //
1752 // - Using `MaybeUninit::assume_init` after a `copy_nonoverlapping` was not
1753 // turning the untyped copy into a typed load. As such, the generated
1754 // `load` in LLVM didn't get various metadata, such as `!range` (#73258),
1755 // `!nonnull`, and `!noundef`, resulting in poorer optimization.
1756 // - Going through the extra local resulted in multiple extra copies, even
1757 // in optimized MIR. (Ignoring StorageLive/Dead, the intrinsic is one
1758 // MIR statement, while the previous implementation was eight.) LLVM
1759 // could sometimes optimize them away, but because `read` is at the core
1760 // of so many things, not having them in the first place improves what we
1761 // hand off to the backend. For example, `mem::replace::<Big>` previously
1762 // emitted 4 `alloca` and 6 `memcpy`s, but is now 1 `alloc` and 3 `memcpy`s.
1763 // - In general, this approach keeps us from getting any more bugs (like
1764 // #106369) that boil down to "`read(p)` is worse than `*p`", as this
1765 // makes them look identical to the backend (or other MIR consumers).
1766 //
1767 // Future enhancements to MIR optimizations might well allow this to return
1768 // to the previous implementation, rather than using an intrinsic.
1769
1770 // SAFETY: the caller must guarantee that `src` is valid for reads.
1771 unsafe {
1772 #[cfg(debug_assertions)] // Too expensive to always enable (for now?)
1773 ub_checks::assert_unsafe_precondition!(
1774 check_language_ub,
1775 "ptr::read requires that the pointer argument is aligned and non-null",
1776 (
1777 addr: *const () = src as *const (),
1778 align: usize = align_of::<T>(),
1779 is_zst: bool = T::IS_ZST,
1780 ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst)
1781 );
1782 crate::intrinsics::read_via_copy(src)
1783 }
1784}
1785
1786/// Reads the value from `src` without moving it. This leaves the
1787/// memory in `src` unchanged.
1788///
1789/// Unlike [`read`], `read_unaligned` works with unaligned pointers.
1790///
1791/// # Safety
1792///
1793/// Behavior is undefined if any of the following conditions are violated:
1794///
1795/// * `src` must be [valid] for reads.
1796///
1797/// * `src` must point to a properly initialized value of type `T`.
1798///
1799/// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
1800/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1801/// value and the value at `*src` can [violate memory safety][read-ownership].
1802///
1803/// [read-ownership]: read#ownership-of-the-returned-value
1804/// [valid]: self#safety
1805///
1806/// ## On `packed` structs
1807///
1808/// Attempting to create a raw pointer to an `unaligned` struct field with
1809/// an expression such as `&packed.unaligned as *const FieldType` creates an
1810/// intermediate unaligned reference before converting that to a raw pointer.
1811/// That this reference is temporary and immediately cast is inconsequential
1812/// as the compiler always expects references to be properly aligned.
1813/// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1814/// *undefined behavior* in your program.
1815///
1816/// Instead you must use the `&raw const` syntax to create the pointer.
1817/// You may use that constructed pointer together with this function.
1818///
1819/// An example of what not to do and how this relates to `read_unaligned` is:
1820///
1821/// ```
1822/// #[repr(packed, C)]
1823/// struct Packed {
1824/// _padding: u8,
1825/// unaligned: u32,
1826/// }
1827///
1828/// let packed = Packed {
1829/// _padding: 0x00,
1830/// unaligned: 0x01020304,
1831/// };
1832///
1833/// // Take the address of a 32-bit integer which is not aligned.
1834/// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
1835/// let unaligned = &raw const packed.unaligned;
1836///
1837/// let v = unsafe { std::ptr::read_unaligned(unaligned) };
1838/// assert_eq!(v, 0x01020304);
1839/// ```
1840///
1841/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
1842///
1843/// # Examples
1844///
1845/// Read a `usize` value from a byte buffer:
1846///
1847/// ```
1848/// fn read_usize(x: &[u8]) -> usize {
1849/// assert!(x.len() >= size_of::<usize>());
1850///
1851/// let ptr = x.as_ptr() as *const usize;
1852///
1853/// unsafe { ptr.read_unaligned() }
1854/// }
1855/// ```
1856#[inline(always)]
1857#[stable(feature = "ptr_unaligned", since = "1.17.0")]
1858#[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")]
1859#[track_caller]
1860#[rustc_diagnostic_item = "ptr_read_unaligned"]
1861#[ferrocene::prevalidated]
1862pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
1863 // Always true thanks to the repr, but to demonstrate
1864 const {
1865 assert!(mem::offset_of!(Unaligned::<T>, 0) == 0);
1866 assert!(size_of::<T>() == size_of::<Unaligned<T>>());
1867 }
1868
1869 let src = src.cast::<Unaligned<T>>();
1870 // SAFETY: the caller must guarantee that `src` is valid for reads.
1871 // Reading it as `Unaligned<T>` instead of `T` reads those same bytes because
1872 // it's the same size (thus zero offset), but with alignment 1 instead.
1873 //
1874 // Similarly, because it's the same bytes it's sound to transmute from the
1875 // `Unaligned<T>` to `T`. Transmute is a value-based (not a place-based)
1876 // operation that doesn't care about alignment.
1877 unsafe {
1878 let unaligned = read(src);
1879 // Can't just destructure because that's not allowed in const fn
1880 mem::transmute_neo(unaligned)
1881 }
1882}
1883
1884/// Overwrites a memory location with the given value without reading or
1885/// dropping the old value.
1886///
1887/// `write` does not drop the contents of `dst`. This is safe, but it could leak
1888/// allocations or resources, so care should be taken not to overwrite an object
1889/// that should be dropped.
1890///
1891/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1892/// location pointed to by `dst`.
1893///
1894/// This is appropriate for initializing uninitialized memory, or overwriting
1895/// memory that has previously been [`read`] from.
1896///
1897/// # Safety
1898///
1899/// Behavior is undefined if any of the following conditions are violated:
1900///
1901/// * `dst` must be [valid] for writes or `T` must be a ZST.
1902///
1903/// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
1904/// case.
1905///
1906/// Note that even if `T` has size `0`, the pointer must be properly aligned.
1907///
1908/// [valid]: self#safety
1909///
1910/// # Examples
1911///
1912/// Basic usage:
1913///
1914/// ```
1915/// let mut x = 0;
1916/// let y = &mut x as *mut i32;
1917/// let z = 12;
1918///
1919/// unsafe {
1920/// std::ptr::write(y, z);
1921/// assert_eq!(std::ptr::read(y), 12);
1922/// }
1923/// ```
1924///
1925/// Manually implement [`mem::swap`]:
1926///
1927/// ```
1928/// use std::ptr;
1929///
1930/// fn swap<T>(a: &mut T, b: &mut T) {
1931/// unsafe {
1932/// // Create a bitwise copy of the value at `a` in `tmp`.
1933/// let tmp = ptr::read(a);
1934///
1935/// // Exiting at this point (either by explicitly returning or by
1936/// // calling a function which panics) would cause the value in `tmp` to
1937/// // be dropped while the same value is still referenced by `a`. This
1938/// // could trigger undefined behavior if `T` is not `Copy`.
1939///
1940/// // Create a bitwise copy of the value at `b` in `a`.
1941/// // This is safe because mutable references cannot alias.
1942/// ptr::copy_nonoverlapping(b, a, 1);
1943///
1944/// // As above, exiting here could trigger undefined behavior because
1945/// // the same value is referenced by `a` and `b`.
1946///
1947/// // Move `tmp` into `b`.
1948/// ptr::write(b, tmp);
1949///
1950/// // `tmp` has been moved (`write` takes ownership of its second argument),
1951/// // so nothing is dropped implicitly here.
1952/// }
1953/// }
1954///
1955/// let mut foo = "foo".to_owned();
1956/// let mut bar = "bar".to_owned();
1957///
1958/// swap(&mut foo, &mut bar);
1959///
1960/// assert_eq!(foo, "bar");
1961/// assert_eq!(bar, "foo");
1962/// ```
1963#[inline(always)]
1964#[stable(feature = "rust1", since = "1.0.0")]
1965#[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
1966#[rustc_diagnostic_item = "ptr_write"]
1967#[track_caller]
1968#[ferrocene::prevalidated]
1969pub const unsafe fn write<T>(dst: *mut T, src: T) {
1970 // Semantically, it would be fine for this to be implemented as a
1971 // `copy_nonoverlapping` and appropriate drop suppression of `src`.
1972
1973 // However, implementing via that currently produces more MIR than is ideal.
1974 // Using an intrinsic keeps it down to just the simple `*dst = move src` in
1975 // MIR (11 statements shorter, at the time of writing), and also allows
1976 // `src` to stay an SSA value in codegen_ssa, rather than a memory one.
1977
1978 // SAFETY: the caller must guarantee that `dst` is valid for writes.
1979 // `dst` cannot overlap `src` because the caller has mutable access
1980 // to `dst` while `src` is owned by this function.
1981 unsafe {
1982 #[cfg(debug_assertions)] // Too expensive to always enable (for now?)
1983 ub_checks::assert_unsafe_precondition!(
1984 check_language_ub,
1985 "ptr::write requires that the pointer argument is aligned and non-null",
1986 (
1987 addr: *mut () = dst as *mut (),
1988 align: usize = align_of::<T>(),
1989 is_zst: bool = T::IS_ZST,
1990 ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst)
1991 );
1992 intrinsics::write_via_move(dst, src)
1993 }
1994}
1995
1996/// Overwrites a memory location with the given value without reading or
1997/// dropping the old value.
1998///
1999/// Unlike [`write()`], the pointer may be unaligned.
2000///
2001/// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
2002/// could leak allocations or resources, so care should be taken not to overwrite
2003/// an object that should be dropped.
2004///
2005/// Additionally, it does not drop `src`. Semantically, `src` is moved into the
2006/// location pointed to by `dst`.
2007///
2008/// This is appropriate for initializing uninitialized memory, or overwriting
2009/// memory that has previously been read with [`read_unaligned`].
2010///
2011/// # Safety
2012///
2013/// Behavior is undefined if any of the following conditions are violated:
2014///
2015/// * `dst` must be [valid] for writes.
2016///
2017/// [valid]: self#safety
2018///
2019/// ## On `packed` structs
2020///
2021/// Attempting to create a raw pointer to an `unaligned` struct field with
2022/// an expression such as `&packed.unaligned as *const FieldType` creates an
2023/// intermediate unaligned reference before converting that to a raw pointer.
2024/// That this reference is temporary and immediately cast is inconsequential
2025/// as the compiler always expects references to be properly aligned.
2026/// As a result, using `&packed.unaligned as *const FieldType` causes immediate
2027/// *undefined behavior* in your program.
2028///
2029/// Instead, you must use the `&raw mut` syntax to create the pointer.
2030/// You may use that constructed pointer together with this function.
2031///
2032/// An example of how to do it and how this relates to `write_unaligned` is:
2033///
2034/// ```
2035/// #[repr(packed, C)]
2036/// struct Packed {
2037/// _padding: u8,
2038/// unaligned: u32,
2039/// }
2040///
2041/// let mut packed: Packed = unsafe { std::mem::zeroed() };
2042///
2043/// // Take the address of a 32-bit integer which is not aligned.
2044/// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
2045/// let unaligned = &raw mut packed.unaligned;
2046///
2047/// unsafe { std::ptr::write_unaligned(unaligned, 42) };
2048///
2049/// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
2050/// ```
2051///
2052/// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
2053/// (as can be seen in the `assert_eq!` above).
2054///
2055/// # Examples
2056///
2057/// Write a `usize` value to a byte buffer:
2058///
2059/// ```
2060/// fn write_usize(x: &mut [u8], val: usize) {
2061/// assert!(x.len() >= size_of::<usize>());
2062///
2063/// let ptr = x.as_mut_ptr() as *mut usize;
2064///
2065/// unsafe { ptr.write_unaligned(val) }
2066/// }
2067/// ```
2068#[inline(always)]
2069#[stable(feature = "ptr_unaligned", since = "1.17.0")]
2070#[rustc_const_stable(feature = "const_ptr_write", since = "1.83.0")]
2071#[rustc_diagnostic_item = "ptr_write_unaligned"]
2072#[track_caller]
2073#[ferrocene::prevalidated]
2074pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
2075 // Always true thanks to the repr, but to demonstrate
2076 const {
2077 assert!(mem::offset_of!(Unaligned::<T>, 0) == 0);
2078 assert!(size_of::<T>() == size_of::<Unaligned<T>>());
2079 }
2080
2081 let dst = dst.cast::<Unaligned<T>>();
2082 let src = Unaligned(src);
2083 // SAFETY: the caller must guarantee that `dst` is valid for writes.
2084 // Writing it as `Unaligned<T>` instead of `T` writes those same bytes because
2085 // it's the same size (thus zero offset), but with alignment 1 instead.
2086 unsafe { write(dst, src) }
2087}
2088
2089/// Performs a volatile read of the value from `src` without moving it.
2090///
2091/// Volatile operations are intended to act on I/O memory. As such, they are considered externally
2092/// observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or
2093/// reordered by the compiler across other externally observable events. With this in mind, there
2094/// are two cases of usage that need to be distinguished:
2095///
2096/// - When a volatile operation is used for memory inside an [allocation], it behaves exactly like
2097/// [`read`], except for the additional guarantee that it won't be elided or reordered across
2098/// other externally observable events (see above). This implies that the operation will actually
2099/// access memory and not e.g. be lowered to reusing data from a previous read. Other than that,
2100/// all the usual rules for memory accesses apply (including provenance). In particular, just
2101/// like in C, whether an operation is volatile has no bearing whatsoever on questions involving
2102/// concurrent accesses from multiple threads. Volatile accesses behave exactly like non-atomic
2103/// accesses in that regard.
2104///
2105/// - Volatile operations, however, may also be used to access memory that is _outside_ of any Rust
2106/// allocation. In this use-case, the pointer does *not* have to be [valid] for reads. This is
2107/// typically used for CPU and peripheral registers that must be accessed via an I/O memory
2108/// mapping, most commonly at fixed addresses reserved by the hardware. These often have special
2109/// semantics associated to their manipulation, and cannot be used as general purpose memory.
2110/// Here, any address value is possible, including 0 and [`usize::MAX`], so long as the semantics
2111/// of such a read are well-defined by the target hardware. The provenance of the pointer is
2112/// irrelevant, and it can be created with [`without_provenance`]. The access is allowed to trap,
2113/// which must immediately abort the process. It can also cause other side-effects, but those
2114/// must not affect Rust-allocated memory in any way. This access is still not considered
2115/// [atomic], and as such it cannot be used for inter-thread synchronization.
2116///
2117/// Note that volatile memory operations where T is a zero-sized type are noops and may be ignored.
2118///
2119/// When invoked during const evaluation, this behaves like a regular read. In particular, such
2120/// reads must always follow the first of the two cases above.
2121///
2122/// [allocation]: crate::ptr#allocated-object
2123/// [atomic]: crate::sync::atomic#memory-model-for-atomic-accesses
2124///
2125/// # Load splitting
2126///
2127/// Exactly which hardware loads are performed by this function is, in general, highly target-dependent.
2128///
2129/// For a simple scalar, such as when `T` is a thin pointer, this will typically be one load assuming
2130/// your target supports a load of exactly that size and alignment.
2131///
2132/// For anything else, it will be split into multiple loads in some unspecified way.
2133/// This can happen even for scalars: notably, on many targets loading a `u128` will still need to be split,
2134/// despite being "one" scalar. On many targets loading anything larger than a pointer will need to be split.
2135/// On all current targets a load larger than 64 bytes will need to be split.
2136/// Any load whose size is not a power of two will also almost certainly need to be split.
2137///
2138/// There is no stability guarantee on how that splitting happens. It may change at any point.
2139///
2140/// # Safety
2141///
2142/// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of whether `T` is
2143/// [`Copy`]. If `T` is not [`Copy`], using both the returned value and the value at `*src` can
2144/// [violate memory safety][read-ownership]. However, storing non-[`Copy`] types in volatile memory
2145/// is almost certainly incorrect.
2146///
2147/// Behavior is undefined if any of the following conditions are violated:
2148///
2149/// * `src` must be either [valid] for reads, or `T` must be a ZST, or `src` must point to memory
2150/// outside of all Rust allocations and reading from that memory must not cause any memory inside
2151/// a Rust allocation to be modified.
2152///
2153/// * `src` must be properly aligned.
2154///
2155/// * Reading from `src` must produce a properly initialized value of type `T`.
2156///
2157/// Note that even if `T` has size `0`, the pointer must be properly aligned.
2158///
2159/// [valid]: self#safety
2160/// [read-ownership]: read#ownership-of-the-returned-value
2161///
2162/// # Examples
2163///
2164/// Basic usage:
2165///
2166/// ```
2167/// let x = 12;
2168/// let y = &x as *const i32;
2169///
2170/// unsafe {
2171/// assert_eq!(std::ptr::read_volatile(y), 12);
2172/// }
2173/// ```
2174#[ferrocene::prevalidated]
2175#[inline(always)]
2176#[stable(feature = "volatile", since = "1.9.0")]
2177#[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
2178#[track_caller]
2179#[rustc_diagnostic_item = "ptr_read_volatile"]
2180pub const unsafe fn read_volatile<T>(src: *const T) -> T {
2181 // SAFETY: the caller must uphold the safety contract for `volatile_load`.
2182 unsafe {
2183 ub_checks::assert_unsafe_precondition!(
2184 check_language_ub,
2185 "ptr::read_volatile requires that the pointer argument is aligned",
2186 (
2187 addr: *const () = src as *const (),
2188 align: usize = align_of::<T>(),
2189 ) => ub_checks::maybe_is_aligned(addr, align)
2190 );
2191 intrinsics::volatile_load(src)
2192 }
2193}
2194
2195/// Performs a volatile write of a memory location with the given value without reading or dropping
2196/// the old value.
2197///
2198/// Volatile operations are intended to act on I/O memory. As such, they are considered externally
2199/// observable events (just like syscalls), and are guaranteed to not be elided or reordered by the
2200/// compiler across other externally observable events. With this in mind, there are two cases of
2201/// usage that need to be distinguished:
2202///
2203/// - When a volatile operation is used for memory inside an [allocation], it behaves exactly like
2204/// [`write`][write()], except for the additional guarantee that it won't be elided or reordered
2205/// across other externally observable events (see above). This implies that the operation will
2206/// actually access memory and not e.g. be lowered to a register access. Other than that, all the
2207/// usual rules for memory accesses apply (including provenance). In particular, just like in C,
2208/// whether an operation is volatile has no bearing whatsoever on questions involving concurrent
2209/// access from multiple threads. Volatile accesses behave exactly like non-atomic accesses in
2210/// that regard.
2211///
2212/// - Volatile operations, however, may also be used to access memory that is _outside_ of any Rust
2213/// allocation. In this use-case, the pointer does *not* have to be [valid] for writes. This is
2214/// typically used for CPU and peripheral registers that must be accessed via an I/O memory
2215/// mapping, most commonly at fixed addresses reserved by the hardware. These often have special
2216/// semantics associated to their manipulation, and cannot be used as general purpose memory.
2217/// Here, any address value is possible, including 0 and [`usize::MAX`], so long as the semantics
2218/// of such a write are well-defined by the target hardware. The provenance of the pointer is
2219/// irrelevant, and it can be created with [`without_provenance_mut`]. The access is allowed to
2220/// trap, which must immediately abort the process. It can also cause other side-effects, but
2221/// those must not affect Rust-allocated memory in any way. This access is still not considered
2222/// [atomic], and as such it cannot be used for inter-thread synchronization.
2223///
2224/// Note that volatile memory operations on zero-sized types (e.g., if a zero-sized type is passed
2225/// to `write_volatile`) are noops and may be ignored.
2226///
2227/// `write_volatile` does not drop the contents of `dst`. This is safe, but it could leak
2228/// allocations or resources, so care should be taken not to overwrite an object that should be
2229/// dropped when operating on Rust memory. Additionally, it does not drop `src`. Semantically, `src`
2230/// is moved into the location pointed to by `dst`.
2231///
2232/// When invoked during const evaluation, this behaves like a regular write. In particular, such
2233/// reads must always follow the first of the two cases above.
2234///
2235/// [allocation]: crate::ptr#allocated-object
2236/// [atomic]: crate::sync::atomic#memory-model-for-atomic-accesses
2237///
2238/// # Store splitting
2239///
2240/// Exactly which hardware stores are performed by this function is, in general, highly target-dependent.
2241///
2242/// For a simple scalar, such as when `T` is a thin pointer, this will typically be one store assuming
2243/// your target supports a store of exactly that size and alignment.
2244///
2245/// For anything else, it will be split into multiple stores in some unspecified way.
2246/// This can happen even for scalars: notably, on many targets storing a `u128` will still need to be split,
2247/// despite being "one" scalar. On many targets storing anything larger than a pointer will need to be split.
2248/// On all current targets a store larger than 64 bytes will need to be split.
2249/// Any store whose size is not a power of two will also almost certainly need to be split.
2250///
2251/// There is no stability guarantee on how that splitting happens. It may change at any point.
2252///
2253/// # Safety
2254///
2255/// Behavior is undefined if any of the following conditions are violated:
2256///
2257/// * `dst` must be either [valid] for writes, or `T` must be a ZST, or `dst` must point to memory
2258/// outside of all Rust allocations and writing to that memory must not cause any memory inside a
2259/// Rust allocation to be modified.
2260///
2261/// * `dst` must be properly aligned.
2262///
2263/// Note that even if `T` has size `0`, the pointer must be properly aligned.
2264///
2265/// [valid]: self#safety
2266///
2267/// # Examples
2268///
2269/// Basic usage:
2270///
2271/// ```
2272/// let mut x = 0;
2273/// let y = &mut x as *mut i32;
2274/// let z = 12;
2275///
2276/// unsafe {
2277/// std::ptr::write_volatile(y, z);
2278/// assert_eq!(std::ptr::read_volatile(y), 12);
2279/// }
2280/// ```
2281#[ferrocene::prevalidated]
2282#[inline(always)]
2283#[stable(feature = "volatile", since = "1.9.0")]
2284#[rustc_const_unstable(feature = "const_volatile", issue = "159094")]
2285#[rustc_diagnostic_item = "ptr_write_volatile"]
2286#[track_caller]
2287pub const unsafe fn write_volatile<T>(dst: *mut T, src: T) {
2288 // SAFETY: the caller must uphold the safety contract for `volatile_store`.
2289 unsafe {
2290 ub_checks::assert_unsafe_precondition!(
2291 check_language_ub,
2292 "ptr::write_volatile requires that the pointer argument is aligned",
2293 (
2294 addr: *mut () = dst as *mut (),
2295 align: usize = align_of::<T>(),
2296 ) => ub_checks::maybe_is_aligned(addr, align)
2297 );
2298 intrinsics::volatile_store(dst, src);
2299 }
2300}
2301
2302/// Calculate an element-offset that increases a pointer's alignment.
2303///
2304/// Calculate an element-offset (not byte-offset) that when added to a given pointer `p`, increases `p`'s alignment to at least the given alignment `a`.
2305///
2306/// # Safety
2307/// `a` must be a power of two.
2308///
2309/// # Notes
2310/// This implementation has been carefully tailored to not panic. It is UB for this to panic.
2311/// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
2312/// constants.
2313///
2314/// If we ever decide to make it possible to call the intrinsic with `a` that is not a
2315/// power-of-two, it will probably be more prudent to just change to a naive implementation rather
2316/// than trying to adapt this to accommodate that change.
2317///
2318/// Any questions go to @nagisa.
2319#[allow(ptr_to_integer_transmute_in_consts)]
2320#[ferrocene::prevalidated]
2321pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
2322 // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
2323 // 1, where the method versions of these operations are not inlined.
2324 use intrinsics::{
2325 assume, cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl,
2326 unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
2327 };
2328
2329 /// Calculate multiplicative modular inverse of `x` modulo `m`.
2330 ///
2331 /// This implementation is tailored for `align_offset` and has following preconditions:
2332 ///
2333 /// * `m` is a power-of-two;
2334 /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
2335 ///
2336 /// Implementation of this function shall not panic. Ever.
2337 #[inline]
2338 #[ferrocene::prevalidated]
2339 const unsafe fn mod_inv(x: usize, m: usize) -> usize {
2340 /// Multiplicative modular inverse table modulo 2⁴ = 16.
2341 ///
2342 /// Note, that this table does not contain values where inverse does not exist (i.e., for
2343 /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
2344 const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
2345 /// Modulo for which the `INV_TABLE_MOD_16` is intended.
2346 const INV_TABLE_MOD: usize = 16;
2347
2348 // SAFETY: `m` is required to be a power-of-two, hence non-zero.
2349 let m_minus_one = unsafe { unchecked_sub(m, 1) };
2350 let mut inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
2351 let mut mod_gate = INV_TABLE_MOD;
2352 // We iterate "up" using the following formula:
2353 //
2354 // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
2355 //
2356 // This application needs to be applied at least until `2²ⁿ ≥ m`, at which point we can
2357 // finally reduce the computation to our desired `m` by taking `inverse mod m`.
2358 //
2359 // This computation is `O(log log m)`, which is to say, that on 64-bit machines this loop
2360 // will always finish in at most 4 iterations.
2361 loop {
2362 // y = y * (2 - xy) mod n
2363 //
2364 // Note, that we use wrapping operations here intentionally – the original formula
2365 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
2366 // usize::MAX` instead, because we take the result `mod n` at the end
2367 // anyway.
2368 if mod_gate >= m {
2369 break;
2370 }
2371 inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
2372 let (new_gate, overflow) = mul_with_overflow(mod_gate, mod_gate);
2373 if overflow {
2374 break;
2375 }
2376 mod_gate = new_gate;
2377 }
2378 inverse & m_minus_one
2379 }
2380
2381 let stride = size_of::<T>();
2382
2383 let addr: usize = p.addr();
2384
2385 // SAFETY: `a` is a power-of-two, therefore non-zero.
2386 let a_minus_one = unsafe { unchecked_sub(a, 1) };
2387
2388 if stride == 0 {
2389 // SPECIAL_CASE: handle 0-sized types. No matter how many times we step, the address will
2390 // stay the same, so no offset will be able to align the pointer unless it is already
2391 // aligned. This branch _will_ be optimized out as `stride` is known at compile-time.
2392 let p_mod_a = addr & a_minus_one;
2393 return if p_mod_a == 0 { 0 } else { usize::MAX };
2394 }
2395
2396 // SAFETY: `stride == 0` case has been handled by the special case above.
2397 let a_mod_stride = unsafe { unchecked_rem(a, stride) };
2398 if a_mod_stride == 0 {
2399 // SPECIAL_CASE: In cases where the `a` is divisible by `stride`, byte offset to align a
2400 // pointer can be computed more simply through `-p (mod a)`. In the off-chance the byte
2401 // offset is not a multiple of `stride`, the input pointer was misaligned and no pointer
2402 // offset will be able to produce a `p` aligned to the specified `a`.
2403 //
2404 // The naive `-p (mod a)` equation inhibits LLVM's ability to select instructions
2405 // like `lea`. We compute `(round_up_to_next_alignment(p, a) - p)` instead. This
2406 // redistributes operations around the load-bearing, but pessimizing `and` instruction
2407 // sufficiently for LLVM to be able to utilize the various optimizations it knows about.
2408 //
2409 // LLVM handles the branch here particularly nicely. If this branch needs to be evaluated
2410 // at runtime, it will produce a mask `if addr_mod_stride == 0 { 0 } else { usize::MAX }`
2411 // in a branch-free way and then bitwise-OR it with whatever result the `-p mod a`
2412 // computation produces.
2413
2414 let aligned_address = wrapping_add(addr, a_minus_one) & wrapping_sub(0, a);
2415 let byte_offset = wrapping_sub(aligned_address, addr);
2416 // FIXME: Remove the assume after <https://github.com/llvm/llvm-project/issues/62502>
2417 // SAFETY: Masking by `-a` can only affect the low bits, and thus cannot have reduced
2418 // the value by more than `a-1`, so even though the intermediate values might have
2419 // wrapped, the byte_offset is always in `[0, a)`.
2420 unsafe { assume(byte_offset < a) };
2421
2422 // SAFETY: `stride == 0` case has been handled by the special case above.
2423 let addr_mod_stride = unsafe { unchecked_rem(addr, stride) };
2424
2425 return if addr_mod_stride == 0 {
2426 // SAFETY: `stride` is non-zero. This is guaranteed to divide exactly as well, because
2427 // addr has been verified to be aligned to the original type’s alignment requirements.
2428 unsafe { exact_div(byte_offset, stride) }
2429 } else {
2430 usize::MAX
2431 };
2432 }
2433
2434 // GENERAL_CASE: From here on we’re handling the very general case where `addr` may be
2435 // misaligned, there isn’t an obvious relationship between `stride` and `a` that we can take an
2436 // advantage of, etc. This case produces machine code that isn’t particularly high quality,
2437 // compared to the special cases above. The code produced here is still within the realm of
2438 // miracles, given the situations this case has to deal with.
2439
2440 // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
2441 // FIXME(const-hack) replace with min
2442 let gcdpow = unsafe {
2443 let x = cttz_nonzero(stride);
2444 let y = cttz_nonzero(a);
2445 if x < y { x } else { y }
2446 };
2447 // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a `usize`.
2448 let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
2449 // SAFETY: gcd is always greater or equal to 1.
2450 if addr & unsafe { unchecked_sub(gcd, 1) } == 0 {
2451 // This branch solves for the following linear congruence equation:
2452 //
2453 // ` p + so = 0 mod a `
2454 //
2455 // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
2456 // requested alignment.
2457 //
2458 // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
2459 // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
2460 //
2461 // ` p' + s'o = 0 mod a' `
2462 // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
2463 //
2464 // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the
2465 // second term is "how does incrementing `p` by `s` bytes change the relative alignment of
2466 // `p`" (again divided by `g`). Division by `g` is necessary to make the inverse well
2467 // formed if `a` and `s` are not co-prime.
2468 //
2469 // Furthermore, the result produced by this solution is not "minimal", so it is necessary
2470 // to take the result `o mod lcm(s, a)`. This `lcm(s, a)` is the same as `a'`.
2471
2472 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
2473 // `a`.
2474 let a2 = unsafe { unchecked_shr(a, gcdpow) };
2475 // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
2476 // in `a` (of which it has exactly one).
2477 let a2minus1 = unsafe { unchecked_sub(a2, 1) };
2478 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
2479 // `a`.
2480 let s2 = unsafe { unchecked_shr(stride & a_minus_one, gcdpow) };
2481 // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
2482 // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
2483 // always be strictly greater than `(p % a) >> gcdpow`.
2484 let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(addr & a_minus_one, gcdpow)) };
2485 // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
2486 // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
2487 return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
2488 }
2489
2490 // Cannot be aligned at all.
2491 usize::MAX
2492}
2493
2494/// Compares raw pointers for equality.
2495///
2496/// This is the same as using the `==` operator, but less generic:
2497/// the arguments have to be `*const T` raw pointers,
2498/// not anything that implements `PartialEq`.
2499///
2500/// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
2501/// by their address rather than comparing the values they point to
2502/// (which is what the `PartialEq for &T` implementation does).
2503///
2504/// When comparing wide pointers, both the address and the metadata are tested for equality.
2505/// However, note that comparing trait object pointers (`*const dyn Trait`) is unreliable: pointers
2506/// to values of the same underlying type can compare inequal (because vtables are duplicated in
2507/// multiple codegen units), and pointers to values of *different* underlying type can compare equal
2508/// (since identical vtables can be deduplicated within a codegen unit).
2509///
2510/// # Examples
2511///
2512/// ```
2513/// use std::ptr;
2514///
2515/// let five = 5;
2516/// let other_five = 5;
2517/// let five_ref = &five;
2518/// let same_five_ref = &five;
2519/// let other_five_ref = &other_five;
2520///
2521/// assert!(five_ref == same_five_ref);
2522/// assert!(ptr::eq(five_ref, same_five_ref));
2523///
2524/// assert!(five_ref == other_five_ref);
2525/// assert!(!ptr::eq(five_ref, other_five_ref));
2526/// ```
2527///
2528/// Slices are also compared by their length (fat pointers):
2529///
2530/// ```
2531/// let a = [1, 2, 3];
2532/// assert!(std::ptr::eq(&a[..3], &a[..3]));
2533/// assert!(!std::ptr::eq(&a[..2], &a[..3]));
2534/// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
2535/// ```
2536#[stable(feature = "ptr_eq", since = "1.17.0")]
2537#[inline(always)]
2538#[must_use = "pointer comparison produces a value"]
2539#[rustc_diagnostic_item = "ptr_eq"]
2540#[allow(ambiguous_wide_pointer_comparisons)] // it's actually clear here
2541pub fn eq<T: PointeeSized>(a: *const T, b: *const T) -> bool {
2542 a == b
2543}
2544
2545/// Compares the *addresses* of the two pointers for equality,
2546/// ignoring any metadata in fat pointers.
2547///
2548/// If the arguments are thin pointers of the same type,
2549/// then this is the same as [`eq`].
2550///
2551/// # Examples
2552///
2553/// ```
2554/// use std::ptr;
2555///
2556/// let whole: &[i32; 3] = &[1, 2, 3];
2557/// let first: &i32 = &whole[0];
2558///
2559/// assert!(ptr::addr_eq(whole, first));
2560/// assert!(!ptr::eq::<dyn std::fmt::Debug>(whole, first));
2561/// ```
2562#[stable(feature = "ptr_addr_eq", since = "1.76.0")]
2563#[inline(always)]
2564#[must_use = "pointer comparison produces a value"]
2565pub fn addr_eq<T: PointeeSized, U: PointeeSized>(p: *const T, q: *const U) -> bool {
2566 (p as *const ()) == (q as *const ())
2567}
2568
2569/// Compares the *addresses* of the two function pointers for equality.
2570///
2571/// This is the same as `f == g`, but using this function makes clear that the potentially
2572/// surprising semantics of function pointer comparison are involved.
2573///
2574/// There are **very few guarantees** about how functions are compiled and they have no intrinsic
2575/// “identity”; in particular, this comparison:
2576///
2577/// * May return `true` unexpectedly, in cases where functions are equivalent.
2578///
2579/// For example, the following program is likely (but not guaranteed) to print `(true, true)`
2580/// when compiled with optimization:
2581///
2582/// ```
2583/// let f: fn(i32) -> i32 = |x| x;
2584/// let g: fn(i32) -> i32 = |x| x + 0; // different closure, different body
2585/// let h: fn(u32) -> u32 = |x| x + 0; // different signature too
2586/// dbg!(std::ptr::fn_addr_eq(f, g), std::ptr::fn_addr_eq(f, h)); // not guaranteed to be equal
2587/// ```
2588///
2589/// * May return `false` in any case.
2590///
2591/// This is particularly likely with generic functions but may happen with any function.
2592/// (From an implementation perspective, this is possible because functions may sometimes be
2593/// processed more than once by the compiler, resulting in duplicate machine code.)
2594///
2595/// Despite these false positives and false negatives, this comparison can still be useful.
2596/// Specifically, if
2597///
2598/// * `T` is the same type as `U`, `T` is a [subtype] of `U`, or `U` is a [subtype] of `T`, and
2599/// * `ptr::fn_addr_eq(f, g)` returns true,
2600///
2601/// then calling `f` and calling `g` will be equivalent.
2602///
2603///
2604/// # Examples
2605///
2606/// ```
2607/// use std::ptr;
2608///
2609/// fn a() { println!("a"); }
2610/// fn b() { println!("b"); }
2611/// assert!(!ptr::fn_addr_eq(a as fn(), b as fn()));
2612/// ```
2613///
2614/// [subtype]: https://doc.rust-lang.org/reference/subtyping.html
2615#[stable(feature = "ptr_fn_addr_eq", since = "1.85.0")]
2616#[inline(always)]
2617#[must_use = "function pointer comparison produces a value"]
2618pub fn fn_addr_eq<T: FnPtr, U: FnPtr>(f: T, g: U) -> bool {
2619 f.addr() == g.addr()
2620}
2621
2622/// Hash a raw pointer.
2623///
2624/// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
2625/// by its address rather than the value it points to
2626/// (which is what the `Hash for &T` implementation does).
2627///
2628/// # Examples
2629///
2630/// ```
2631/// use std::hash::{DefaultHasher, Hash, Hasher};
2632/// use std::ptr;
2633///
2634/// let five = 5;
2635/// let five_ref = &five;
2636///
2637/// let mut hasher = DefaultHasher::new();
2638/// ptr::hash(five_ref, &mut hasher);
2639/// let actual = hasher.finish();
2640///
2641/// let mut hasher = DefaultHasher::new();
2642/// (five_ref as *const i32).hash(&mut hasher);
2643/// let expected = hasher.finish();
2644///
2645/// assert_eq!(actual, expected);
2646/// ```
2647#[stable(feature = "ptr_hash", since = "1.35.0")]
2648pub fn hash<T: PointeeSized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
2649 use crate::hash::Hash;
2650 hashee.hash(into);
2651}
2652
2653#[stable(feature = "fnptr_impls", since = "1.4.0")]
2654#[diagnostic::on_const(
2655 message = "pointers cannot be reliably compared during const eval",
2656 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2657)]
2658impl<F: FnPtr> PartialEq for F {
2659 #[inline]
2660 fn eq(&self, other: &Self) -> bool {
2661 self.addr() == other.addr()
2662 }
2663}
2664#[stable(feature = "fnptr_impls", since = "1.4.0")]
2665#[diagnostic::on_const(
2666 message = "pointers cannot be reliably compared during const eval",
2667 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2668)]
2669impl<F: FnPtr> Eq for F {}
2670
2671#[stable(feature = "fnptr_impls", since = "1.4.0")]
2672#[diagnostic::on_const(
2673 message = "pointers cannot be reliably compared during const eval",
2674 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2675)]
2676impl<F: FnPtr> PartialOrd for F {
2677 #[inline]
2678 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2679 self.addr().partial_cmp(&other.addr())
2680 }
2681}
2682#[stable(feature = "fnptr_impls", since = "1.4.0")]
2683#[diagnostic::on_const(
2684 message = "pointers cannot be reliably compared during const eval",
2685 note = "see issue #53020 <https://github.com/rust-lang/rust/issues/53020> for more information"
2686)]
2687impl<F: FnPtr> Ord for F {
2688 #[inline]
2689 fn cmp(&self, other: &Self) -> Ordering {
2690 self.addr().cmp(&other.addr())
2691 }
2692}
2693
2694#[stable(feature = "fnptr_impls", since = "1.4.0")]
2695impl<F: FnPtr> hash::Hash for F {
2696 fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
2697 state.write_usize(self.addr())
2698 }
2699}
2700
2701#[stable(feature = "fnptr_impls", since = "1.4.0")]
2702impl<F: FnPtr> fmt::Pointer for F {
2703 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2704 fmt::pointer_fmt_inner(self.addr(), f)
2705 }
2706}
2707
2708#[stable(feature = "fnptr_impls", since = "1.4.0")]
2709impl<F: FnPtr> fmt::Debug for F {
2710 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2711 fmt::pointer_fmt_inner(self.addr(), f)
2712 }
2713}
2714
2715/// Creates a `const` raw pointer to a place, without creating an intermediate reference.
2716///
2717/// `addr_of!(expr)` is equivalent to `&raw const expr`. The macro is *soft-deprecated*;
2718/// use `&raw const` instead.
2719///
2720/// It is still an open question under which conditions writing through an `addr_of!`-created
2721/// pointer is permitted. If the place `expr` evaluates to is based on a raw pointer, then the
2722/// result of `addr_of!` inherits all permissions from that raw pointer. However, if the place is
2723/// based on a reference, local variable, or `static`, then until all details are decided, the same
2724/// rules as for shared references apply: it is UB to write through a pointer created with this
2725/// operation, except for bytes located inside an `UnsafeCell`. Use `&raw mut` (or [`addr_of_mut`])
2726/// to create a raw pointer that definitely permits mutation.
2727///
2728/// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
2729/// and points to initialized data. For cases where those requirements do not hold,
2730/// raw pointers should be used instead. However, `&expr as *const _` creates a reference
2731/// before casting it to a raw pointer, and that reference is subject to the same rules
2732/// as all other references. This macro can create a raw pointer *without* creating
2733/// a reference first.
2734///
2735/// See [`addr_of_mut`] for how to create a pointer to uninitialized data.
2736/// Doing that with `addr_of` would not make much sense since one could only
2737/// read the data, and that would be Undefined Behavior.
2738///
2739/// # Safety
2740///
2741/// The `expr` in `addr_of!(expr)` is evaluated as a place expression, but never loads from the
2742/// place or requires the place to be dereferenceable. This means that `addr_of!((*ptr).field)`
2743/// still requires the projection to `field` to be in-bounds, using the same rules as [`offset`].
2744/// However, `addr_of!(*ptr)` is defined behavior even if `ptr` is null, dangling, or misaligned.
2745///
2746/// Note that `Deref`/`Index` coercions (and their mutable counterparts) are applied inside
2747/// `addr_of!` like everywhere else, in which case a reference is created to call `Deref::deref` or
2748/// `Index::index`, respectively. The statements above only apply when no such coercions are
2749/// applied.
2750///
2751/// [`offset`]: pointer::offset
2752///
2753/// # Example
2754///
2755/// **Correct usage: Creating a pointer to unaligned data**
2756///
2757/// ```
2758/// use std::ptr;
2759///
2760/// #[repr(packed)]
2761/// struct Packed {
2762/// f1: u8,
2763/// f2: u16,
2764/// }
2765///
2766/// let packed = Packed { f1: 1, f2: 2 };
2767/// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
2768/// let raw_f2 = ptr::addr_of!(packed.f2);
2769/// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
2770/// ```
2771///
2772/// **Incorrect usage: Out-of-bounds fields projection**
2773///
2774/// ```rust,no_run
2775/// use std::ptr;
2776///
2777/// #[repr(C)]
2778/// struct MyStruct {
2779/// field1: i32,
2780/// field2: i32,
2781/// }
2782///
2783/// let ptr: *const MyStruct = ptr::null();
2784/// let fieldptr = unsafe { ptr::addr_of!((*ptr).field2) }; // Undefined Behavior ⚠️
2785/// ```
2786///
2787/// The field projection `.field2` would offset the pointer by 4 bytes,
2788/// but the pointer is not in-bounds of an allocation for 4 bytes,
2789/// so this offset is Undefined Behavior.
2790/// See the [`offset`] docs for a full list of requirements for inbounds pointer arithmetic; the
2791/// same requirements apply to field projections, even inside `addr_of!`. (In particular, it makes
2792/// no difference whether the pointer is null or dangling.)
2793#[stable(feature = "raw_ref_macros", since = "1.51.0")]
2794#[rustc_macro_transparency = "semiopaque"]
2795pub macro addr_of($place:expr) {
2796 &raw const $place
2797}
2798
2799/// Creates a `mut` raw pointer to a place, without creating an intermediate reference.
2800///
2801/// `addr_of_mut!(expr)` is equivalent to `&raw mut expr`. The macro is *soft-deprecated*;
2802/// use `&raw mut` instead.
2803///
2804/// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
2805/// and points to initialized data. For cases where those requirements do not hold,
2806/// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
2807/// before casting it to a raw pointer, and that reference is subject to the same rules
2808/// as all other references. This macro can create a raw pointer *without* creating
2809/// a reference first.
2810///
2811/// # Safety
2812///
2813/// The `expr` in `addr_of_mut!(expr)` is evaluated as a place expression, but never loads from the
2814/// place or requires the place to be dereferenceable. This means that `addr_of_mut!((*ptr).field)`
2815/// still requires the projection to `field` to be in-bounds, using the same rules as [`offset`].
2816/// However, `addr_of_mut!(*ptr)` is defined behavior even if `ptr` is null, dangling, or misaligned.
2817///
2818/// Note that `Deref`/`Index` coercions (and their mutable counterparts) are applied inside
2819/// `addr_of_mut!` like everywhere else, in which case a reference is created to call `Deref::deref`
2820/// or `Index::index`, respectively. The statements above only apply when no such coercions are
2821/// applied.
2822///
2823/// [`offset`]: pointer::offset
2824///
2825/// # Examples
2826///
2827/// **Correct usage: Creating a pointer to unaligned data**
2828///
2829/// ```
2830/// use std::ptr;
2831///
2832/// #[repr(packed)]
2833/// struct Packed {
2834/// f1: u8,
2835/// f2: u16,
2836/// }
2837///
2838/// let mut packed = Packed { f1: 1, f2: 2 };
2839/// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
2840/// let raw_f2 = ptr::addr_of_mut!(packed.f2);
2841/// unsafe { raw_f2.write_unaligned(42); }
2842/// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
2843/// ```
2844///
2845/// **Correct usage: Creating a pointer to uninitialized data**
2846///
2847/// ```rust
2848/// use std::{ptr, mem::MaybeUninit};
2849///
2850/// struct Demo {
2851/// field: bool,
2852/// }
2853///
2854/// let mut uninit = MaybeUninit::<Demo>::uninit();
2855/// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
2856/// // and thus be Undefined Behavior!
2857/// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
2858/// unsafe { f1_ptr.write(true); }
2859/// let init = unsafe { uninit.assume_init() };
2860/// ```
2861///
2862/// **Incorrect usage: Out-of-bounds fields projection**
2863///
2864/// ```rust,no_run
2865/// use std::ptr;
2866///
2867/// #[repr(C)]
2868/// struct MyStruct {
2869/// field1: i32,
2870/// field2: i32,
2871/// }
2872///
2873/// let ptr: *mut MyStruct = ptr::null_mut();
2874/// let fieldptr = unsafe { ptr::addr_of_mut!((*ptr).field2) }; // Undefined Behavior ⚠️
2875/// ```
2876///
2877/// The field projection `.field2` would offset the pointer by 4 bytes,
2878/// but the pointer is not in-bounds of an allocation for 4 bytes,
2879/// so this offset is Undefined Behavior.
2880/// See the [`offset`] docs for a full list of requirements for inbounds pointer arithmetic; the
2881/// same requirements apply to field projections, even inside `addr_of_mut!`. (In particular, it
2882/// makes no difference whether the pointer is null or dangling.)
2883#[stable(feature = "raw_ref_macros", since = "1.51.0")]
2884#[rustc_macro_transparency = "semiopaque"]
2885pub macro addr_of_mut($place:expr) {
2886 &raw mut $place
2887}
2888
2889/// Used in [`read_unaligned`] and [`write_unaligned`] to load and store `T`
2890/// with alignment 1 rather than its usual `align_of::<T>()` alignment.
2891#[repr(Rust, packed)]
2892struct Unaligned<T>(T);