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