]> git.lizzy.rs Git - rust.git/blob - library/core/src/ptr/mod.rs
a3730448f735428c48f7e4271b86420c6d51fcac
[rust.git] / library / core / src / 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
8 //! or write to them. For this to be safe, these pointers must be *valid*.
9 //! Whether a pointer is valid depends on the operation it is used for
10 //! (read or write), and the extent of the memory that is accessed (i.e.,
11 //! how many bytes are read/written). Most functions use `*mut T` and `*const T`
12 //! to access only a single value, in which case the documentation omits the size
13 //! and 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, not even for accesses of [size zero][zst].
19 //! * For a pointer to be valid, it is necessary, but not always sufficient, that the pointer
20 //!   be *dereferenceable*: the memory range of the given size starting at the pointer must all be
21 //!   within the bounds of a single allocated object. Note that in Rust,
22 //!   every (stack-allocated) variable is considered a separate allocated object.
23 //! * Even for operations of [size zero][zst], the pointer must not be pointing to deallocated
24 //!   memory, i.e., deallocation makes pointers invalid even for zero-sized operations. However,
25 //!   casting any non-zero integer *literal* to a pointer is valid for zero-sized accesses, even if
26 //!   some memory happens to exist at that address and gets deallocated. This corresponds to writing
27 //!   your own allocator: allocating zero-sized objects is not very hard. The canonical way to
28 //!   obtain a pointer that is valid for zero-sized accesses is [`NonNull::dangling`].
29 //! * All accesses performed by functions in this module are *non-atomic* in the sense
30 //!   of [atomic operations] used to synchronize between threads. This means it is
31 //!   undefined behavior to perform two concurrent accesses to the same location from different
32 //!   threads unless both accesses only read from memory. Notice that this explicitly
33 //!   includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot
34 //!   be used for inter-thread synchronization.
35 //! * The result of casting a reference to a pointer is valid for as long as the
36 //!   underlying object is live and no reference (just raw pointers) is used to
37 //!   access the same memory.
38 //!
39 //! These axioms, along with careful use of [`offset`] for pointer arithmetic,
40 //! are enough to correctly implement many useful things in unsafe code. Stronger guarantees
41 //! will be provided eventually, as the [aliasing] rules are being determined. For more
42 //! information, see the [book] as well as the section in the reference devoted
43 //! to [undefined behavior][ub].
44 //!
45 //! ## Alignment
46 //!
47 //! Valid raw pointers as defined above are not necessarily properly aligned (where
48 //! "proper" alignment is defined by the pointee type, i.e., `*const T` must be
49 //! aligned to `mem::align_of::<T>()`). However, most functions require their
50 //! arguments to be properly aligned, and will explicitly state
51 //! this requirement in their documentation. Notable exceptions to this are
52 //! [`read_unaligned`] and [`write_unaligned`].
53 //!
54 //! When a function requires proper alignment, it does so even if the access
55 //! has size 0, i.e., even if memory is not actually touched. Consider using
56 //! [`NonNull::dangling`] in such cases.
57 //!
58 //! ## Allocated object
59 //!
60 //! For several operations, such as [`offset`] or field projections (`expr.field`), the notion of an
61 //! "allocated object" becomes relevant. An allocated object is a contiguous region of memory.
62 //! Common examples of allocated objects include stack-allocated variables (each variable is a
63 //! separate allocated object), heap allocations (each allocation created by the global allocator is
64 //! a separate allocated object), and `static` variables.
65 //!
66 //!
67 //! # Strict Provenance
68 //!
69 //! **The following text is non-normative, insufficiently formal, and is an extremely strict
70 //! interpretation of provenance. It's ok if your code doesn't strictly conform to it.**
71 //!
72 //! [Strict Provenance][] is an experimental set of APIs that help tools that try
73 //! to validate the memory-safety of your program's execution. Notably this includes [Miri][]
74 //! and [CHERI][], which can detect when you access out of bounds memory or otherwise violate
75 //! Rust's memory model.
76 //!
77 //! Provenance must exist in some form for any programming
78 //! language compiled for modern computer architectures, but specifying a model for provenance
79 //! in a way that is useful to both compilers and programmers is an ongoing challenge.
80 //! The [Strict Provenance][] experiment seeks to explore the question: *what if we just said you
81 //! couldn't do all the nasty operations that make provenance so messy?*
82 //!
83 //! What APIs would have to be removed? What APIs would have to be added? How much would code
84 //! have to change, and is it worse or better now? Would any patterns become truly inexpressible?
85 //! Could we carve out special exceptions for those patterns? Should we?
86 //!
87 //! A secondary goal of this project is to see if we can disambiguate the many functions of
88 //! pointer<->integer casts enough for the definition of `usize` to be loosened so that it
89 //! isn't *pointer*-sized but address-space/offset/allocation-sized (we'll probably continue
90 //! to conflate these notions). This would potentially make it possible to more efficiently
91 //! target platforms where pointers are larger than offsets, such as CHERI and maybe some
92 //! segmented architecures.
93 //!
94 //! ## Provenance
95 //!
96 //! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
97 //!
98 //! Pointers are not *simply* an "integer" or "address". For instance, it's uncontroversial
99 //! to say that a Use After Free is clearly Undefined Behaviour, even if you "get lucky"
100 //! and the freed memory gets reallocated before your read/write (in fact this is the
101 //! worst-case scenario, UAFs would be much less concerning if this didn't happen!).
102 //! To rationalize this claim, pointers need to somehow be *more* than just their addresses:
103 //! they must have provenance.
104 //!
105 //! When an allocation is created, that allocation has a unique Original Pointer. For alloc
106 //! APIs this is literally the pointer the call returns, and for local variables and statics,
107 //! this is the name of the variable/static. This is mildly overloading the term "pointer"
108 //! for the sake of brevity/exposition.
109 //!
110 //! The Original Pointer for an allocation is guaranteed to have unique access to the entire
111 //! allocation and *only* that allocation. In this sense, an allocation can be thought of
112 //! as a "sandbox" that cannot be broken into or out of. *Provenance* is the permission
113 //! to access an allocation's sandbox and has both a *spatial* and *temporal* component:
114 //!
115 //! * Spatial: A range of bytes that the pointer is allowed to access.
116 //! * Temporal: The lifetime (of the allocation) that access to these bytes is tied to.
117 //!
118 //! Spatial provenance makes sure you don't go beyond your sandbox, while temporal provenance
119 //! makes sure that you can't "get lucky" after your permission to access some memory
120 //! has been revoked (either through deallocations or borrows expiring).
121 //!
122 //! Provenance is implicitly shared with all pointers transitively derived from
123 //! The Original Pointer through operations like [`offset`], borrowing, and pointer casts.
124 //! Some operations may *shrink* the derived provenance, limiting how much memory it can
125 //! access or how long it's valid for (i.e. borrowing a subfield and subslicing).
126 //!
127 //! Shrinking provenance cannot be undone: even if you "know" there is a larger allocation, you
128 //! can't derive a pointer with a larger provenance. Similarly, you cannot "recombine"
129 //! two contiguous provenances back into one (i.e. with a `fn merge(&[T], &[T]) -> &[T]`).
130 //!
131 //! A reference to a value always has provenance over exactly the memory that field occupies.
132 //! A reference to a slice always has provenance over exactly the range that slice describes.
133 //!
134 //! If an allocation is deallocated, all pointers with provenance to that allocation become
135 //! invalidated, and effectively lose their provenance.
136 //!
137 //! The strict provenance experiment is mostly only interested in exploring stricter *spatial*
138 //! provenance. In this sense it can be thought of as a subset of the more ambitious and
139 //! formal [Stacked Borrows][] research project, which is what tools like [Miri][] are based on.
140 //! In particular, Stacked Borrows is necessary to properly describe what borrows are allowed
141 //! to do and when they become invalidated. This necessarily involves much more complex
142 //! *temporal* reasoning than simply identifying allocations. Adjusting APIs and code
143 //! for the strict provenance experiment will also greatly help Stacked Borrows.
144 //!
145 //!
146 //! ## Pointer Vs Addresses
147 //!
148 //! **This section is *non-normative* and is part of the [Strict Provenance][] experiment.**
149 //!
150 //! One of the largest historical issues with trying to define provenance is that programmers
151 //! freely convert between pointers and integers. Once you allow for this, it generally becomes
152 //! impossible to accurately track and preserve provenance information, and you need to appeal
153 //! to very complex and unreliable heuristics. But of course, converting between pointers and
154 //! integers is very useful, so what can we do?
155 //!
156 //! Also did you know WASM is actually a "Harvard Architecture"? As in function pointers are
157 //! handled completely differently from data pointers? And we kind of just shipped Rust on WASM
158 //! without really addressing the fact that we let you freely convert between function pointers
159 //! and data pointers, because it mostly Just Works? Let's just put that on the "pointer casts
160 //! are dubious" pile.
161 //!
162 //! Strict Provenance attempts to square these circles by decoupling Rust's traditional conflation
163 //! of pointers and `usize` (and `isize`), and defining a pointer to semantically contain the
164 //! following information:
165 //!
166 //! * The **address-space** it is part of (e.g. "data" vs "code" in WASM).
167 //! * The **address** it points to, which can be represented by a `usize`.
168 //! * The **provenance** it has, defining the memory it has permission to access.
169 //!
170 //! Under Strict Provenance, a usize *cannot* accurately represent a pointer, and converting from
171 //! a pointer to a usize is generally an operation which *only* extracts the address. It is
172 //! therefore *impossible* to construct a valid pointer from a usize because there is no way
173 //! to restore the address-space and provenance. In other words, pointer-integer-pointer
174 //! roundtrips are not possible (in the sense that the resulting pointer is not dereferencable).
175 //!
176 //! The key insight to making this model *at all* viable is the [`with_addr`][] method:
177 //!
178 //! ```text
179 //!     /// Creates a new pointer with the given address.
180 //!     ///
181 //!     /// This performs the same operation as an `addr as ptr` cast, but copies
182 //!     /// the *address-space* and *provenance* of `self` to the new pointer.
183 //!     /// This allows us to dynamically preserve and propagate this important
184 //!     /// information in a way that is otherwise impossible with a unary cast.
185 //!     ///
186 //!     /// This is equivalent to using `wrapping_offset` to offset `self` to the
187 //!     /// given address, and therefore has all the same capabilities and restrictions.
188 //!     pub fn with_addr(self, addr: usize) -> Self;
189 //! ```
190 //!
191 //! So you're still able to drop down to the address representation and do whatever
192 //! clever bit tricks you want *as long as* you're able to keep around a pointer
193 //! into the allocation you care about that can "reconstitute" the other parts of the pointer.
194 //! Usually this is very easy, because you only are taking a pointer, messing with the address,
195 //! and then immediately converting back to a pointer. To make this use case more ergonomic,
196 //! we provide the [`map_addr`][] method.
197 //!
198 //! To help make it clear that code is "following" Strict Provenance semantics, we also provide an
199 //! [`addr`][] method which promises that the returned address is not part of a
200 //! pointer-usize-pointer roundtrip. In the future we may provide a lint for pointer<->integer
201 //! casts to help you audit if your code conforms to strict provenance.
202 //!
203 //!
204 //! ## Using Strict Provenance
205 //!
206 //! Most code needs no changes to conform to strict provenance, as the only really concerning
207 //! operation that *wasn't* obviously already Undefined Behaviour is casts from usize to a
208 //! pointer. For code which *does* cast a usize to a pointer, the scope of the change depends
209 //! on exactly what you're doing.
210 //!
211 //! In general you just need to make sure that if you want to convert a usize address to a
212 //! pointer and then use that pointer to read/write memory, you need to keep around a pointer
213 //! that has sufficient provenance to perform that read/write itself. In this way all of your
214 //! casts from an address to a pointer are essentially just applying offsets/indexing.
215 //!
216 //! This is generally trivial to do for simple cases like tagged pointers *as long as you
217 //! represent the tagged pointer as an actual pointer and not a usize*. For instance:
218 //!
219 //! ```
220 //! #![feature(strict_provenance)]
221 //!
222 //! unsafe {
223 //!     // A flag we want to pack into our pointer
224 //!     static HAS_DATA: usize = 0x1;
225 //!     static FLAG_MASK: usize = !HAS_DATA;
226 //!
227 //!     // Our value, which must have enough alignment to have spare least-significant-bits.
228 //!     let my_precious_data: u32 = 17;
229 //!     assert!(core::mem::align_of::<u32>() > 1);
230 //!
231 //!     // Create a tagged pointer
232 //!     let ptr = &my_precious_data as *const u32;
233 //!     let tagged = ptr.map_addr(|addr| addr | HAS_DATA);
234 //!
235 //!     // Check the flag:
236 //!     if tagged.addr() & HAS_DATA != 0 {
237 //!         // Untag and read the pointer
238 //!         let data = *tagged.map_addr(|addr| addr & FLAG_MASK);
239 //!         assert_eq!(data, 17);
240 //!     } else {
241 //!         unreachable!()
242 //!     }
243 //! }
244 //! ```
245 //!
246 //! (Yes, if you've been using AtomicUsize for pointers in concurrent datastructures, you should
247 //! be using AtomicPtr instead. If that messes up the way you atomically manipulate pointers,
248 //! we would like to know why, and what needs to be done to fix it.)
249 //!
250 //! Something more complicated and just generally *evil* like an XOR-List requires more significant
251 //! changes like allocating all nodes in a pre-allocated Vec or Arena and using a pointer
252 //! to the whole allocation to reconstitute the XORed addresses.
253 //!
254 //! Situations where a valid pointer *must* be created from just an address, such as baremetal code
255 //! accessing a memory-mapped interface at a fixed address, are an open question on how to support.
256 //! These situations *will* still be allowed, but we might require some kind of "I know what I'm
257 //! doing" annotation to explain the situation to the compiler. It's also possible they need no
258 //! special attention at all, because they're generally accessing memory outside the scope of
259 //! "the abstract machine", or already using "I know what I'm doing" annotations like "volatile".
260 //!
261 //! Under [Strict Provenance] it is Undefined Behaviour to:
262 //!
263 //! * Access memory through a pointer that does not have provenance over that memory.
264 //!
265 //! * [`offset`] a pointer to or from an address it doesn't have provenance over.
266 //!   This means it's always UB to offset a pointer derived from something deallocated,
267 //!   even if the offset is 0. Note that a pointer "one past the end" of its provenance
268 //!   is not actually outside its provenance, it just has 0 bytes it can load/store.
269 //!
270 //! But it *is* still sound to:
271 //!
272 //! * Create an invalid pointer from just an address (see [`ptr::invalid`][]). This can
273 //!   be used for sentinel values like `null` *or* to represent a tagged pointer that will
274 //!   never be dereferencable. In general, it is always sound for an integer to pretend
275 //!   to be a pointer "for fun" as long as you don't use operations on it which require
276 //!   it to be valid (offset, read, write, etc).
277 //!
278 //! * Forge an allocation of size zero at any sufficiently aligned non-null address.
279 //!   i.e. the usual "ZSTs are fake, do what you want" rules apply *but* this only applies
280 //!   for actual forgery (integers cast to pointers). If you borrow some struct's field
281 //!   that *happens* to be zero-sized, the resulting pointer will have provenance tied to
282 //!   that allocation and it will still get invalidated if the allocation gets deallocated.
283 //!   In the future we may introduce an API to make such a forged allocation explicit.
284 //!
285 //! * [`wrapping_offset`][] a pointer outside its provenance. This includes invalid pointers
286 //!   which have "no" provenance. Unfortunately there may be practical limits on this for a
287 //!   particular platform, and it's an open question as to how to specify this (if at all).
288 //!   Notably, [CHERI][] relies on a compression scheme that can't handle a
289 //!   pointer getting offset "too far" out of bounds. If this happens, the address
290 //!   returned by `addr` will be the value you expect, but the provenance will get invalidated
291 //!   and using it to read/write will fault. The details of this are architecture-specific
292 //!   and based on alignment, but the buffer on either side of the pointer's range is pretty
293 //!   generous (think kilobytes, not bytes).
294 //!
295 //! * Compare arbitrary pointers by address. Addresses *are* just integers and so there is
296 //!   always a coherent answer, even if the pointers are invalid or from different
297 //!   address-spaces/provenances. Of course, comparing addresses from different address-spaces
298 //!   is generally going to be *meaningless*, but so is comparing Kilograms to Meters, and Rust
299 //!   doesn't prevent that either. Similarly, if you get "lucky" and notice that a pointer
300 //!   one-past-the-end is the "same" address as the start of an unrelated allocation, anything
301 //!   you do with that fact is *probably* going to be gibberish. The scope of that gibberish
302 //!   is kept under control by the fact that the two pointers *still* aren't allowed to access
303 //!   the other's allocation (bytes), because they still have different provenance.
304 //!
305 //! * Perform pointer tagging tricks. This falls out of [`wrapping_offset`] but is worth
306 //!   mentioning in more detail because of the limitations of [CHERI][]. Low-bit tagging
307 //!   is very robust, and often doesn't even go out of bounds because types ensure
308 //!   size >= align (and over-aligning actually gives CHERI more flexibility). Anything
309 //!   more complex than this rapidly enters "extremely platform-specific" territory as
310 //!   certain things may or may not be allowed based on specific supported operations.
311 //!   For instance, ARM explicitly supports high-bit tagging, and so CHERI on ARM inherits
312 //!   that and should support it.
313 //!
314 //! ## Pointer-usize-pointer roundtrips and 'exposed' provenance
315 //!
316 //! **This section is *non-normative* and is part of the [Strict Provenance] experiment.**
317 //!
318 //! As discussed above, pointer-usize-pointer roundtrips are not possible under [Strict Provenance].
319 //! However, there exists legacy Rust code that is full of such roundtrips, and legacy platform APIs
320 //! regularly assume that `usize` can capture all the information that makes up a pointer. There
321 //! also might be code that cannot be ported to Strict Provenance (which is something we would [like
322 //! to hear about][Strict Provenance]).
323 //!
324 //! For situations like this, there is a fallback plan, a way to 'opt out' of Strict Provenance.
325 //! However, note that this makes your code a lot harder to specify, and the code will not work
326 //! (well) with tools like [Miri] and [CHERI].
327 //!
328 //! This fallback plan is provided by the [`expose_addr`] and [`from_exposed_addr`] methods (which
329 //! are equivalent to `as` casts between pointers and integers). [`expose_addr`] is a lot like
330 //! [`addr`], but additionally adds the provenance of the pointer to a global list of 'exposed'
331 //! provenances. (This list is purely conceptual, it exists for the purpose of specifying Rust but
332 //! is not materialized in actual executions, except in tools like [Miri].) [`from_exposed_addr`]
333 //! can be used to construct a pointer with one of these previously 'exposed' provenances.
334 //! [`from_exposed_addr`] takes only `addr: usize` as arguments, so unlike in [`with_addr`] there is
335 //! no indication of what the correct provenance for the returned pointer is -- and that is exactly
336 //! what makes pointer-usize-pointer roundtrips so tricky to rigorously specify! There is no
337 //! algorithm that decides which provenance will be used. You can think of this as "guessing" the
338 //! right provenance, and the guess will be "maximally in your favor", in the sense that if there is
339 //! any way to avoid undefined behavior, then that is the guess that will be taken. However, if
340 //! there is *no* previously 'exposed' provenance that justifies the way the returned pointer will
341 //! be used, the program has undefined behavior.
342 //!
343 //! Using [`expose_addr`] or [`from_exposed_addr`] (or the equivalent `as` casts) means that code is
344 //! *not* following Strict Provenance rules. The goal of the Strict Provenance experiment is to
345 //! determine whether it is possible to use Rust without [`expose_addr`] and [`from_exposed_addr`].
346 //! If this is successful, it would be a major win for avoiding specification complexity and to
347 //! facilitate adoption of tools like [CHERI] and [Miri] that can be a big help in increasing the
348 //! confidence in (unsafe) Rust code.
349 //!
350 //! [aliasing]: ../../nomicon/aliasing.html
351 //! [book]: ../../book/ch19-01-unsafe-rust.html#dereferencing-a-raw-pointer
352 //! [ub]: ../../reference/behavior-considered-undefined.html
353 //! [zst]: ../../nomicon/exotic-sizes.html#zero-sized-types-zsts
354 //! [atomic operations]: crate::sync::atomic
355 //! [`offset`]: pointer::offset
356 //! [`wrapping_offset`]: pointer::wrapping_offset
357 //! [`with_addr`]: pointer::with_addr
358 //! [`map_addr`]: pointer::map_addr
359 //! [`addr`]: pointer::addr
360 //! [`ptr::invalid`]: core::ptr::invalid
361 //! [`expose_addr`]: pointer::expose_addr
362 //! [`from_exposed_addr`]: from_exposed_addr
363 //! [Miri]: https://github.com/rust-lang/miri
364 //! [CHERI]: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
365 //! [Strict Provenance]: https://github.com/rust-lang/rust/issues/95228
366 //! [Stacked Borrows]: https://plv.mpi-sws.org/rustbelt/stacked-borrows/
367
368 #![stable(feature = "rust1", since = "1.0.0")]
369
370 use crate::cmp::Ordering;
371 use crate::fmt;
372 use crate::hash;
373 use crate::intrinsics::{
374     self, assert_unsafe_precondition, is_aligned_and_not_null, is_nonoverlapping,
375 };
376
377 use crate::mem::{self, MaybeUninit};
378
379 #[stable(feature = "rust1", since = "1.0.0")]
380 #[doc(inline)]
381 pub use crate::intrinsics::copy_nonoverlapping;
382
383 #[stable(feature = "rust1", since = "1.0.0")]
384 #[doc(inline)]
385 pub use crate::intrinsics::copy;
386
387 #[stable(feature = "rust1", since = "1.0.0")]
388 #[doc(inline)]
389 pub use crate::intrinsics::write_bytes;
390
391 mod metadata;
392 pub(crate) use metadata::PtrRepr;
393 #[unstable(feature = "ptr_metadata", issue = "81513")]
394 pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin};
395
396 mod non_null;
397 #[stable(feature = "nonnull", since = "1.25.0")]
398 pub use non_null::NonNull;
399
400 mod unique;
401 #[unstable(feature = "ptr_internals", issue = "none")]
402 pub use unique::Unique;
403
404 mod const_ptr;
405 mod mut_ptr;
406
407 /// Executes the destructor (if any) of the pointed-to value.
408 ///
409 /// This is semantically equivalent to calling [`ptr::read`] and discarding
410 /// the result, but has the following advantages:
411 ///
412 /// * It is *required* to use `drop_in_place` to drop unsized types like
413 ///   trait objects, because they can't be read out onto the stack and
414 ///   dropped normally.
415 ///
416 /// * It is friendlier to the optimizer to do this over [`ptr::read`] when
417 ///   dropping manually allocated memory (e.g., in the implementations of
418 ///   `Box`/`Rc`/`Vec`), as the compiler doesn't need to prove that it's
419 ///   sound to elide the copy.
420 ///
421 /// * It can be used to drop [pinned] data when `T` is not `repr(packed)`
422 ///   (pinned data must not be moved before it is dropped).
423 ///
424 /// Unaligned values cannot be dropped in place, they must be copied to an aligned
425 /// location first using [`ptr::read_unaligned`]. For packed structs, this move is
426 /// done automatically by the compiler. This means the fields of packed structs
427 /// are not dropped in-place.
428 ///
429 /// [`ptr::read`]: self::read
430 /// [`ptr::read_unaligned`]: self::read_unaligned
431 /// [pinned]: crate::pin
432 ///
433 /// # Safety
434 ///
435 /// Behavior is undefined if any of the following conditions are violated:
436 ///
437 /// * `to_drop` must be [valid] for both reads and writes.
438 ///
439 /// * `to_drop` must be properly aligned.
440 ///
441 /// * The value `to_drop` points to must be valid for dropping, which may mean it must uphold
442 ///   additional invariants - this is type-dependent.
443 ///
444 /// Additionally, if `T` is not [`Copy`], using the pointed-to value after
445 /// calling `drop_in_place` can cause undefined behavior. Note that `*to_drop =
446 /// foo` counts as a use because it will cause the value to be dropped
447 /// again. [`write()`] can be used to overwrite data without causing it to be
448 /// dropped.
449 ///
450 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
451 ///
452 /// [valid]: self#safety
453 ///
454 /// # Examples
455 ///
456 /// Manually remove the last item from a vector:
457 ///
458 /// ```
459 /// use std::ptr;
460 /// use std::rc::Rc;
461 ///
462 /// let last = Rc::new(1);
463 /// let weak = Rc::downgrade(&last);
464 ///
465 /// let mut v = vec![Rc::new(0), last];
466 ///
467 /// unsafe {
468 ///     // Get a raw pointer to the last element in `v`.
469 ///     let ptr = &mut v[1] as *mut _;
470 ///     // Shorten `v` to prevent the last item from being dropped. We do that first,
471 ///     // to prevent issues if the `drop_in_place` below panics.
472 ///     v.set_len(1);
473 ///     // Without a call `drop_in_place`, the last item would never be dropped,
474 ///     // and the memory it manages would be leaked.
475 ///     ptr::drop_in_place(ptr);
476 /// }
477 ///
478 /// assert_eq!(v, &[0.into()]);
479 ///
480 /// // Ensure that the last item was dropped.
481 /// assert!(weak.upgrade().is_none());
482 /// ```
483 #[stable(feature = "drop_in_place", since = "1.8.0")]
484 #[lang = "drop_in_place"]
485 #[allow(unconditional_recursion)]
486 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
487     // Code here does not matter - this is replaced by the
488     // real drop glue by the compiler.
489
490     // SAFETY: see comment above
491     unsafe { drop_in_place(to_drop) }
492 }
493
494 /// Creates a null raw pointer.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use std::ptr;
500 ///
501 /// let p: *const i32 = ptr::null();
502 /// assert!(p.is_null());
503 /// ```
504 #[inline(always)]
505 #[must_use]
506 #[stable(feature = "rust1", since = "1.0.0")]
507 #[rustc_promotable]
508 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
509 #[rustc_diagnostic_item = "ptr_null"]
510 pub const fn null<T>() -> *const T {
511     invalid(0)
512 }
513
514 /// Creates a null mutable raw pointer.
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// use std::ptr;
520 ///
521 /// let p: *mut i32 = ptr::null_mut();
522 /// assert!(p.is_null());
523 /// ```
524 #[inline(always)]
525 #[must_use]
526 #[stable(feature = "rust1", since = "1.0.0")]
527 #[rustc_promotable]
528 #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")]
529 #[rustc_diagnostic_item = "ptr_null_mut"]
530 pub const fn null_mut<T>() -> *mut T {
531     invalid_mut(0)
532 }
533
534 /// Creates an invalid pointer with the given address.
535 ///
536 /// This is *currently* equivalent to `addr as *const T` but it expresses the intended semantic
537 /// more clearly, and may become important under future memory models.
538 ///
539 /// The module's top-level documentation discusses the precise meaning of an "invalid"
540 /// pointer but essentially this expresses that the pointer is not associated
541 /// with any actual allocation and is little more than a usize address in disguise.
542 ///
543 /// This pointer will have no provenance associated with it and is therefore
544 /// UB to read/write/offset. This mostly exists to facilitate things
545 /// like ptr::null and NonNull::dangling which make invalid pointers.
546 ///
547 /// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
548 /// may be desirable to give them their own API just to make that 100% clear.)
549 ///
550 /// This API and its claimed semantics are part of the Strict Provenance experiment,
551 /// see the [module documentation][crate::ptr] for details.
552 #[inline(always)]
553 #[must_use]
554 #[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")]
555 #[unstable(feature = "strict_provenance", issue = "95228")]
556 pub const fn invalid<T>(addr: usize) -> *const T {
557     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
558     addr as *const T
559 }
560
561 /// Creates an invalid mutable pointer with the given address.
562 ///
563 /// This is *currently* equivalent to `addr as *mut T` but it expresses the intended semantic
564 /// more clearly, and may become important under future memory models.
565 ///
566 /// The module's top-level documentation discusses the precise meaning of an "invalid"
567 /// pointer but essentially this expresses that the pointer is not associated
568 /// with any actual allocation and is little more than a usize address in disguise.
569 ///
570 /// This pointer will have no provenance associated with it and is therefore
571 /// UB to read/write/offset. This mostly exists to facilitate things
572 /// like ptr::null and NonNull::dangling which make invalid pointers.
573 ///
574 /// (Standard "Zero-Sized-Types get to cheat and lie" caveats apply, although it
575 /// may be desirable to give them their own API just to make that 100% clear.)
576 ///
577 /// This API and its claimed semantics are part of the Strict Provenance experiment,
578 /// see the [module documentation][crate::ptr] for details.
579 #[inline(always)]
580 #[must_use]
581 #[rustc_const_stable(feature = "stable_things_using_strict_provenance", since = "1.61.0")]
582 #[unstable(feature = "strict_provenance", issue = "95228")]
583 pub const fn invalid_mut<T>(addr: usize) -> *mut T {
584     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
585     addr as *mut T
586 }
587
588 /// Convert an address back to a pointer, picking up a previously 'exposed' provenance.
589 ///
590 /// This is equivalent to `addr as *const T`. The provenance of the returned pointer is that of *any*
591 /// pointer that was previously passed to [`expose_addr`][pointer::expose_addr] or a `ptr as usize`
592 /// cast. If there is no previously 'exposed' provenance that justifies the way this pointer will be
593 /// used, the program has undefined behavior. Note that there is no algorithm that decides which
594 /// provenance will be used. You can think of this as "guessing" the right provenance, and the guess
595 /// will be "maximally in your favor", in the sense that if there is any way to avoid undefined
596 /// behavior, then that is the guess that will be taken.
597 ///
598 /// On platforms with multiple address spaces, it is your responsibility to ensure that the
599 /// address makes sense in the address space that this pointer will be used with.
600 ///
601 /// Using this method means that code is *not* following strict provenance rules. "Guessing" a
602 /// suitable provenance complicates specification and reasoning and may not be supported by
603 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
604 /// use [`with_addr`][pointer::with_addr] wherever possible.
605 ///
606 /// On most platforms this will produce a value with the same bytes as the address. Platforms
607 /// which need to store additional information in a pointer may not support this operation,
608 /// since it is generally not possible to actually *compute* which provenance the returned
609 /// pointer has to pick up.
610 ///
611 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
612 /// [module documentation][crate::ptr] for details.
613 #[must_use]
614 #[inline]
615 #[unstable(feature = "strict_provenance", issue = "95228")]
616 pub fn from_exposed_addr<T>(addr: usize) -> *const T
617 where
618     T: Sized,
619 {
620     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
621     addr as *const T
622 }
623
624 /// Convert an address back to a mutable pointer, picking up a previously 'exposed' provenance.
625 ///
626 /// This is equivalent to `addr as *mut T`. The provenance of the returned pointer is that of *any*
627 /// pointer that was previously passed to [`expose_addr`][pointer::expose_addr] or a `ptr as usize`
628 /// cast. If there is no previously 'exposed' provenance that justifies the way this pointer will be
629 /// used, the program has undefined behavior. Note that there is no algorithm that decides which
630 /// provenance will be used. You can think of this as "guessing" the right provenance, and the guess
631 /// will be "maximally in your favor", in the sense that if there is any way to avoid undefined
632 /// behavior, then that is the guess that will be taken.
633 ///
634 /// On platforms with multiple address spaces, it is your responsibility to ensure that the
635 /// address makes sense in the address space that this pointer will be used with.
636 ///
637 /// Using this method means that code is *not* following strict provenance rules. "Guessing" a
638 /// suitable provenance complicates specification and reasoning and may not be supported by
639 /// tools that help you to stay conformant with the Rust memory model, so it is recommended to
640 /// use [`with_addr`][pointer::with_addr] wherever possible.
641 ///
642 /// On most platforms this will produce a value with the same bytes as the address. Platforms
643 /// which need to store additional information in a pointer may not support this operation,
644 /// since it is generally not possible to actually *compute* which provenance the returned
645 /// pointer has to pick up.
646 ///
647 /// This API and its claimed semantics are part of the Strict Provenance experiment, see the
648 /// [module documentation][crate::ptr] for details.
649 #[must_use]
650 #[inline]
651 #[unstable(feature = "strict_provenance", issue = "95228")]
652 pub fn from_exposed_addr_mut<T>(addr: usize) -> *mut T
653 where
654     T: Sized,
655 {
656     // FIXME(strict_provenance_magic): I am magic and should be a compiler intrinsic.
657     addr as *mut T
658 }
659
660 /// Forms a raw slice from a pointer and a length.
661 ///
662 /// The `len` argument is the number of **elements**, not the number of bytes.
663 ///
664 /// This function is safe, but actually using the return value is unsafe.
665 /// See the documentation of [`slice::from_raw_parts`] for slice safety requirements.
666 ///
667 /// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
668 ///
669 /// # Examples
670 ///
671 /// ```rust
672 /// use std::ptr;
673 ///
674 /// // create a slice pointer when starting out with a pointer to the first element
675 /// let x = [5, 6, 7];
676 /// let raw_pointer = x.as_ptr();
677 /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3);
678 /// assert_eq!(unsafe { &*slice }[2], 7);
679 /// ```
680 #[inline]
681 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
682 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
683 pub const fn slice_from_raw_parts<T>(data: *const T, len: usize) -> *const [T] {
684     from_raw_parts(data.cast(), len)
685 }
686
687 /// Performs the same functionality as [`slice_from_raw_parts`], except that a
688 /// raw mutable slice is returned, as opposed to a raw immutable slice.
689 ///
690 /// See the documentation of [`slice_from_raw_parts`] for more details.
691 ///
692 /// This function is safe, but actually using the return value is unsafe.
693 /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements.
694 ///
695 /// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
696 ///
697 /// # Examples
698 ///
699 /// ```rust
700 /// use std::ptr;
701 ///
702 /// let x = &mut [5, 6, 7];
703 /// let raw_pointer = x.as_mut_ptr();
704 /// let slice = ptr::slice_from_raw_parts_mut(raw_pointer, 3);
705 ///
706 /// unsafe {
707 ///     (*slice)[2] = 99; // assign a value at an index in the slice
708 /// };
709 ///
710 /// assert_eq!(unsafe { &*slice }[2], 99);
711 /// ```
712 #[inline]
713 #[stable(feature = "slice_from_raw_parts", since = "1.42.0")]
714 #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")]
715 pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
716     from_raw_parts_mut(data.cast(), len)
717 }
718
719 /// Swaps the values at two mutable locations of the same type, without
720 /// deinitializing either.
721 ///
722 /// But for the following two exceptions, this function is semantically
723 /// equivalent to [`mem::swap`]:
724 ///
725 /// * It operates on raw pointers instead of references. When references are
726 ///   available, [`mem::swap`] should be preferred.
727 ///
728 /// * The two pointed-to values may overlap. If the values do overlap, then the
729 ///   overlapping region of memory from `x` will be used. This is demonstrated
730 ///   in the second example below.
731 ///
732 /// # Safety
733 ///
734 /// Behavior is undefined if any of the following conditions are violated:
735 ///
736 /// * Both `x` and `y` must be [valid] for both reads and writes.
737 ///
738 /// * Both `x` and `y` must be properly aligned.
739 ///
740 /// Note that even if `T` has size `0`, the pointers must be non-null and properly aligned.
741 ///
742 /// [valid]: self#safety
743 ///
744 /// # Examples
745 ///
746 /// Swapping two non-overlapping regions:
747 ///
748 /// ```
749 /// use std::ptr;
750 ///
751 /// let mut array = [0, 1, 2, 3];
752 ///
753 /// let x = array[0..].as_mut_ptr() as *mut [u32; 2]; // this is `array[0..2]`
754 /// let y = array[2..].as_mut_ptr() as *mut [u32; 2]; // this is `array[2..4]`
755 ///
756 /// unsafe {
757 ///     ptr::swap(x, y);
758 ///     assert_eq!([2, 3, 0, 1], array);
759 /// }
760 /// ```
761 ///
762 /// Swapping two overlapping regions:
763 ///
764 /// ```
765 /// use std::ptr;
766 ///
767 /// let mut array: [i32; 4] = [0, 1, 2, 3];
768 ///
769 /// let array_ptr: *mut i32 = array.as_mut_ptr();
770 ///
771 /// let x = array_ptr as *mut [i32; 3]; // this is `array[0..3]`
772 /// let y = unsafe { array_ptr.add(1) } as *mut [i32; 3]; // this is `array[1..4]`
773 ///
774 /// unsafe {
775 ///     ptr::swap(x, y);
776 ///     // The indices `1..3` of the slice overlap between `x` and `y`.
777 ///     // Reasonable results would be for to them be `[2, 3]`, so that indices `0..3` are
778 ///     // `[1, 2, 3]` (matching `y` before the `swap`); or for them to be `[0, 1]`
779 ///     // so that indices `1..4` are `[0, 1, 2]` (matching `x` before the `swap`).
780 ///     // This implementation is defined to make the latter choice.
781 ///     assert_eq!([1, 0, 1, 2], array);
782 /// }
783 /// ```
784 #[inline]
785 #[stable(feature = "rust1", since = "1.0.0")]
786 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
787 pub const unsafe fn swap<T>(x: *mut T, y: *mut T) {
788     // Give ourselves some scratch space to work with.
789     // We do not have to worry about drops: `MaybeUninit` does nothing when dropped.
790     let mut tmp = MaybeUninit::<T>::uninit();
791
792     // Perform the swap
793     // SAFETY: the caller must guarantee that `x` and `y` are
794     // valid for writes and properly aligned. `tmp` cannot be
795     // overlapping either `x` or `y` because `tmp` was just allocated
796     // on the stack as a separate allocated object.
797     unsafe {
798         copy_nonoverlapping(x, tmp.as_mut_ptr(), 1);
799         copy(y, x, 1); // `x` and `y` may overlap
800         copy_nonoverlapping(tmp.as_ptr(), y, 1);
801     }
802 }
803
804 /// Swaps `count * size_of::<T>()` bytes between the two regions of memory
805 /// beginning at `x` and `y`. The two regions must *not* overlap.
806 ///
807 /// # Safety
808 ///
809 /// Behavior is undefined if any of the following conditions are violated:
810 ///
811 /// * Both `x` and `y` must be [valid] for both reads and writes of `count *
812 ///   size_of::<T>()` bytes.
813 ///
814 /// * Both `x` and `y` must be properly aligned.
815 ///
816 /// * The region of memory beginning at `x` with a size of `count *
817 ///   size_of::<T>()` bytes must *not* overlap with the region of memory
818 ///   beginning at `y` with the same size.
819 ///
820 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is `0`,
821 /// the pointers must be non-null and properly aligned.
822 ///
823 /// [valid]: self#safety
824 ///
825 /// # Examples
826 ///
827 /// Basic usage:
828 ///
829 /// ```
830 /// use std::ptr;
831 ///
832 /// let mut x = [1, 2, 3, 4];
833 /// let mut y = [7, 8, 9];
834 ///
835 /// unsafe {
836 ///     ptr::swap_nonoverlapping(x.as_mut_ptr(), y.as_mut_ptr(), 2);
837 /// }
838 ///
839 /// assert_eq!(x, [7, 8, 3, 4]);
840 /// assert_eq!(y, [1, 2, 9]);
841 /// ```
842 #[inline]
843 #[stable(feature = "swap_nonoverlapping", since = "1.27.0")]
844 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
845 pub const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
846     #[allow(unused)]
847     macro_rules! attempt_swap_as_chunks {
848         ($ChunkTy:ty) => {
849             if mem::align_of::<T>() >= mem::align_of::<$ChunkTy>()
850                 && mem::size_of::<T>() % mem::size_of::<$ChunkTy>() == 0
851             {
852                 let x: *mut MaybeUninit<$ChunkTy> = x.cast();
853                 let y: *mut MaybeUninit<$ChunkTy> = y.cast();
854                 let count = count * (mem::size_of::<T>() / mem::size_of::<$ChunkTy>());
855                 // SAFETY: these are the same bytes that the caller promised were
856                 // ok, just typed as `MaybeUninit<ChunkTy>`s instead of as `T`s.
857                 // The `if` condition above ensures that we're not violating
858                 // alignment requirements, and that the division is exact so
859                 // that we don't lose any bytes off the end.
860                 return unsafe { swap_nonoverlapping_simple(x, y, count) };
861             }
862         };
863     }
864
865     // SAFETY: the caller must guarantee that `x` and `y` are
866     // valid for writes and properly aligned.
867     unsafe {
868         assert_unsafe_precondition!(
869             is_aligned_and_not_null(x)
870                 && is_aligned_and_not_null(y)
871                 && is_nonoverlapping(x, y, count)
872         );
873     }
874
875     // NOTE(scottmcm) Miri is disabled here as reading in smaller units is a
876     // pessimization for it.  Also, if the type contains any unaligned pointers,
877     // copying those over multiple reads is difficult to support.
878     #[cfg(not(miri))]
879     {
880         // Split up the slice into small power-of-two-sized chunks that LLVM is able
881         // to vectorize (unless it's a special type with more-than-pointer alignment,
882         // because we don't want to pessimize things like slices of SIMD vectors.)
883         if mem::align_of::<T>() <= mem::size_of::<usize>()
884             && (!mem::size_of::<T>().is_power_of_two()
885                 || mem::size_of::<T>() > mem::size_of::<usize>() * 2)
886         {
887             attempt_swap_as_chunks!(usize);
888             attempt_swap_as_chunks!(u8);
889         }
890     }
891
892     // SAFETY: Same preconditions as this function
893     unsafe { swap_nonoverlapping_simple(x, y, count) }
894 }
895
896 /// Same behaviour and safety conditions as [`swap_nonoverlapping`]
897 ///
898 /// LLVM can vectorize this (at least it can for the power-of-two-sized types
899 /// `swap_nonoverlapping` tries to use) so no need to manually SIMD it.
900 #[inline]
901 #[rustc_const_unstable(feature = "const_swap", issue = "83163")]
902 const unsafe fn swap_nonoverlapping_simple<T>(x: *mut T, y: *mut T, count: usize) {
903     let mut i = 0;
904     while i < count {
905         let x: &mut T =
906             // SAFETY: By precondition, `i` is in-bounds because it's below `n`
907             unsafe { &mut *x.add(i) };
908         let y: &mut T =
909             // SAFETY: By precondition, `i` is in-bounds because it's below `n`
910             // and it's distinct from `x` since the ranges are non-overlapping
911             unsafe { &mut *y.add(i) };
912         mem::swap_simple(x, y);
913
914         i += 1;
915     }
916 }
917
918 /// Moves `src` into the pointed `dst`, returning the previous `dst` value.
919 ///
920 /// Neither value is dropped.
921 ///
922 /// This function is semantically equivalent to [`mem::replace`] except that it
923 /// operates on raw pointers instead of references. When references are
924 /// available, [`mem::replace`] should be preferred.
925 ///
926 /// # Safety
927 ///
928 /// Behavior is undefined if any of the following conditions are violated:
929 ///
930 /// * `dst` must be [valid] for both reads and writes.
931 ///
932 /// * `dst` must be properly aligned.
933 ///
934 /// * `dst` must point to a properly initialized value of type `T`.
935 ///
936 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
937 ///
938 /// [valid]: self#safety
939 ///
940 /// # Examples
941 ///
942 /// ```
943 /// use std::ptr;
944 ///
945 /// let mut rust = vec!['b', 'u', 's', 't'];
946 ///
947 /// // `mem::replace` would have the same effect without requiring the unsafe
948 /// // block.
949 /// let b = unsafe {
950 ///     ptr::replace(&mut rust[0], 'r')
951 /// };
952 ///
953 /// assert_eq!(b, 'b');
954 /// assert_eq!(rust, &['r', 'u', 's', 't']);
955 /// ```
956 #[inline]
957 #[stable(feature = "rust1", since = "1.0.0")]
958 #[rustc_const_unstable(feature = "const_replace", issue = "83164")]
959 pub const unsafe fn replace<T>(dst: *mut T, mut src: T) -> T {
960     // SAFETY: the caller must guarantee that `dst` is valid to be
961     // cast to a mutable reference (valid for writes, aligned, initialized),
962     // and cannot overlap `src` since `dst` must point to a distinct
963     // allocated object.
964     unsafe {
965         assert_unsafe_precondition!(is_aligned_and_not_null(dst));
966         mem::swap(&mut *dst, &mut src); // cannot overlap
967     }
968     src
969 }
970
971 /// Reads the value from `src` without moving it. This leaves the
972 /// memory in `src` unchanged.
973 ///
974 /// # Safety
975 ///
976 /// Behavior is undefined if any of the following conditions are violated:
977 ///
978 /// * `src` must be [valid] for reads.
979 ///
980 /// * `src` must be properly aligned. Use [`read_unaligned`] if this is not the
981 ///   case.
982 ///
983 /// * `src` must point to a properly initialized value of type `T`.
984 ///
985 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
986 ///
987 /// # Examples
988 ///
989 /// Basic usage:
990 ///
991 /// ```
992 /// let x = 12;
993 /// let y = &x as *const i32;
994 ///
995 /// unsafe {
996 ///     assert_eq!(std::ptr::read(y), 12);
997 /// }
998 /// ```
999 ///
1000 /// Manually implement [`mem::swap`]:
1001 ///
1002 /// ```
1003 /// use std::ptr;
1004 ///
1005 /// fn swap<T>(a: &mut T, b: &mut T) {
1006 ///     unsafe {
1007 ///         // Create a bitwise copy of the value at `a` in `tmp`.
1008 ///         let tmp = ptr::read(a);
1009 ///
1010 ///         // Exiting at this point (either by explicitly returning or by
1011 ///         // calling a function which panics) would cause the value in `tmp` to
1012 ///         // be dropped while the same value is still referenced by `a`. This
1013 ///         // could trigger undefined behavior if `T` is not `Copy`.
1014 ///
1015 ///         // Create a bitwise copy of the value at `b` in `a`.
1016 ///         // This is safe because mutable references cannot alias.
1017 ///         ptr::copy_nonoverlapping(b, a, 1);
1018 ///
1019 ///         // As above, exiting here could trigger undefined behavior because
1020 ///         // the same value is referenced by `a` and `b`.
1021 ///
1022 ///         // Move `tmp` into `b`.
1023 ///         ptr::write(b, tmp);
1024 ///
1025 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
1026 ///         // so nothing is dropped implicitly here.
1027 ///     }
1028 /// }
1029 ///
1030 /// let mut foo = "foo".to_owned();
1031 /// let mut bar = "bar".to_owned();
1032 ///
1033 /// swap(&mut foo, &mut bar);
1034 ///
1035 /// assert_eq!(foo, "bar");
1036 /// assert_eq!(bar, "foo");
1037 /// ```
1038 ///
1039 /// ## Ownership of the Returned Value
1040 ///
1041 /// `read` creates a bitwise copy of `T`, regardless of whether `T` is [`Copy`].
1042 /// If `T` is not [`Copy`], using both the returned value and the value at
1043 /// `*src` can violate memory safety. Note that assigning to `*src` counts as a
1044 /// use because it will attempt to drop the value at `*src`.
1045 ///
1046 /// [`write()`] can be used to overwrite data without causing it to be dropped.
1047 ///
1048 /// ```
1049 /// use std::ptr;
1050 ///
1051 /// let mut s = String::from("foo");
1052 /// unsafe {
1053 ///     // `s2` now points to the same underlying memory as `s`.
1054 ///     let mut s2: String = ptr::read(&s);
1055 ///
1056 ///     assert_eq!(s2, "foo");
1057 ///
1058 ///     // Assigning to `s2` causes its original value to be dropped. Beyond
1059 ///     // this point, `s` must no longer be used, as the underlying memory has
1060 ///     // been freed.
1061 ///     s2 = String::default();
1062 ///     assert_eq!(s2, "");
1063 ///
1064 ///     // Assigning to `s` would cause the old value to be dropped again,
1065 ///     // resulting in undefined behavior.
1066 ///     // s = String::from("bar"); // ERROR
1067 ///
1068 ///     // `ptr::write` can be used to overwrite a value without dropping it.
1069 ///     ptr::write(&mut s, String::from("bar"));
1070 /// }
1071 ///
1072 /// assert_eq!(s, "bar");
1073 /// ```
1074 ///
1075 /// [valid]: self#safety
1076 #[inline]
1077 #[stable(feature = "rust1", since = "1.0.0")]
1078 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1079 pub const unsafe fn read<T>(src: *const T) -> T {
1080     // We are calling the intrinsics directly to avoid function calls in the generated code
1081     // as `intrinsics::copy_nonoverlapping` is a wrapper function.
1082     extern "rust-intrinsic" {
1083         #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1084         fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
1085     }
1086
1087     let mut tmp = MaybeUninit::<T>::uninit();
1088     // SAFETY: the caller must guarantee that `src` is valid for reads.
1089     // `src` cannot overlap `tmp` because `tmp` was just allocated on
1090     // the stack as a separate allocated object.
1091     //
1092     // Also, since we just wrote a valid value into `tmp`, it is guaranteed
1093     // to be properly initialized.
1094     unsafe {
1095         copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
1096         tmp.assume_init()
1097     }
1098 }
1099
1100 /// Reads the value from `src` without moving it. This leaves the
1101 /// memory in `src` unchanged.
1102 ///
1103 /// Unlike [`read`], `read_unaligned` works with unaligned pointers.
1104 ///
1105 /// # Safety
1106 ///
1107 /// Behavior is undefined if any of the following conditions are violated:
1108 ///
1109 /// * `src` must be [valid] for reads.
1110 ///
1111 /// * `src` must point to a properly initialized value of type `T`.
1112 ///
1113 /// Like [`read`], `read_unaligned` creates a bitwise copy of `T`, regardless of
1114 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1115 /// value and the value at `*src` can [violate memory safety][read-ownership].
1116 ///
1117 /// Note that even if `T` has size `0`, the pointer must be non-null.
1118 ///
1119 /// [read-ownership]: read#ownership-of-the-returned-value
1120 /// [valid]: self#safety
1121 ///
1122 /// ## On `packed` structs
1123 ///
1124 /// Attempting to create a raw pointer to an `unaligned` struct field with
1125 /// an expression such as `&packed.unaligned as *const FieldType` creates an
1126 /// intermediate unaligned reference before converting that to a raw pointer.
1127 /// That this reference is temporary and immediately cast is inconsequential
1128 /// as the compiler always expects references to be properly aligned.
1129 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1130 /// *undefined behavior* in your program.
1131 ///
1132 /// Instead you must use the [`ptr::addr_of!`](addr_of) macro to
1133 /// create the pointer. You may use that returned pointer together with this
1134 /// function.
1135 ///
1136 /// An example of what not to do and how this relates to `read_unaligned` is:
1137 ///
1138 /// ```
1139 /// #[repr(packed, C)]
1140 /// struct Packed {
1141 ///     _padding: u8,
1142 ///     unaligned: u32,
1143 /// }
1144 ///
1145 /// let packed = Packed {
1146 ///     _padding: 0x00,
1147 ///     unaligned: 0x01020304,
1148 /// };
1149 ///
1150 /// // Take the address of a 32-bit integer which is not aligned.
1151 /// // In contrast to `&packed.unaligned as *const _`, this has no undefined behavior.
1152 /// let unaligned = std::ptr::addr_of!(packed.unaligned);
1153 ///
1154 /// let v = unsafe { std::ptr::read_unaligned(unaligned) };
1155 /// assert_eq!(v, 0x01020304);
1156 /// ```
1157 ///
1158 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however.
1159 ///
1160 /// # Examples
1161 ///
1162 /// Read a usize value from a byte buffer:
1163 ///
1164 /// ```
1165 /// use std::mem;
1166 ///
1167 /// fn read_usize(x: &[u8]) -> usize {
1168 ///     assert!(x.len() >= mem::size_of::<usize>());
1169 ///
1170 ///     let ptr = x.as_ptr() as *const usize;
1171 ///
1172 ///     unsafe { ptr.read_unaligned() }
1173 /// }
1174 /// ```
1175 #[inline]
1176 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1177 #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")]
1178 pub const unsafe fn read_unaligned<T>(src: *const T) -> T {
1179     let mut tmp = MaybeUninit::<T>::uninit();
1180     // SAFETY: the caller must guarantee that `src` is valid for reads.
1181     // `src` cannot overlap `tmp` because `tmp` was just allocated on
1182     // the stack as a separate allocated object.
1183     //
1184     // Also, since we just wrote a valid value into `tmp`, it is guaranteed
1185     // to be properly initialized.
1186     unsafe {
1187         copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::<T>());
1188         tmp.assume_init()
1189     }
1190 }
1191
1192 /// Overwrites a memory location with the given value without reading or
1193 /// dropping the old value.
1194 ///
1195 /// `write` does not drop the contents of `dst`. This is safe, but it could leak
1196 /// allocations or resources, so care should be taken not to overwrite an object
1197 /// that should be dropped.
1198 ///
1199 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1200 /// location pointed to by `dst`.
1201 ///
1202 /// This is appropriate for initializing uninitialized memory, or overwriting
1203 /// memory that has previously been [`read`] from.
1204 ///
1205 /// # Safety
1206 ///
1207 /// Behavior is undefined if any of the following conditions are violated:
1208 ///
1209 /// * `dst` must be [valid] for writes.
1210 ///
1211 /// * `dst` must be properly aligned. Use [`write_unaligned`] if this is not the
1212 ///   case.
1213 ///
1214 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1215 ///
1216 /// [valid]: self#safety
1217 ///
1218 /// # Examples
1219 ///
1220 /// Basic usage:
1221 ///
1222 /// ```
1223 /// let mut x = 0;
1224 /// let y = &mut x as *mut i32;
1225 /// let z = 12;
1226 ///
1227 /// unsafe {
1228 ///     std::ptr::write(y, z);
1229 ///     assert_eq!(std::ptr::read(y), 12);
1230 /// }
1231 /// ```
1232 ///
1233 /// Manually implement [`mem::swap`]:
1234 ///
1235 /// ```
1236 /// use std::ptr;
1237 ///
1238 /// fn swap<T>(a: &mut T, b: &mut T) {
1239 ///     unsafe {
1240 ///         // Create a bitwise copy of the value at `a` in `tmp`.
1241 ///         let tmp = ptr::read(a);
1242 ///
1243 ///         // Exiting at this point (either by explicitly returning or by
1244 ///         // calling a function which panics) would cause the value in `tmp` to
1245 ///         // be dropped while the same value is still referenced by `a`. This
1246 ///         // could trigger undefined behavior if `T` is not `Copy`.
1247 ///
1248 ///         // Create a bitwise copy of the value at `b` in `a`.
1249 ///         // This is safe because mutable references cannot alias.
1250 ///         ptr::copy_nonoverlapping(b, a, 1);
1251 ///
1252 ///         // As above, exiting here could trigger undefined behavior because
1253 ///         // the same value is referenced by `a` and `b`.
1254 ///
1255 ///         // Move `tmp` into `b`.
1256 ///         ptr::write(b, tmp);
1257 ///
1258 ///         // `tmp` has been moved (`write` takes ownership of its second argument),
1259 ///         // so nothing is dropped implicitly here.
1260 ///     }
1261 /// }
1262 ///
1263 /// let mut foo = "foo".to_owned();
1264 /// let mut bar = "bar".to_owned();
1265 ///
1266 /// swap(&mut foo, &mut bar);
1267 ///
1268 /// assert_eq!(foo, "bar");
1269 /// assert_eq!(bar, "foo");
1270 /// ```
1271 #[inline]
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1274 pub const unsafe fn write<T>(dst: *mut T, src: T) {
1275     // We are calling the intrinsics directly to avoid function calls in the generated code
1276     // as `intrinsics::copy_nonoverlapping` is a wrapper function.
1277     extern "rust-intrinsic" {
1278         #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
1279         fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
1280     }
1281
1282     // SAFETY: the caller must guarantee that `dst` is valid for writes.
1283     // `dst` cannot overlap `src` because the caller has mutable access
1284     // to `dst` while `src` is owned by this function.
1285     unsafe {
1286         copy_nonoverlapping(&src as *const T, dst, 1);
1287         intrinsics::forget(src);
1288     }
1289 }
1290
1291 /// Overwrites a memory location with the given value without reading or
1292 /// dropping the old value.
1293 ///
1294 /// Unlike [`write()`], the pointer may be unaligned.
1295 ///
1296 /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it
1297 /// could leak allocations or resources, so care should be taken not to overwrite
1298 /// an object that should be dropped.
1299 ///
1300 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1301 /// location pointed to by `dst`.
1302 ///
1303 /// This is appropriate for initializing uninitialized memory, or overwriting
1304 /// memory that has previously been read with [`read_unaligned`].
1305 ///
1306 /// # Safety
1307 ///
1308 /// Behavior is undefined if any of the following conditions are violated:
1309 ///
1310 /// * `dst` must be [valid] for writes.
1311 ///
1312 /// Note that even if `T` has size `0`, the pointer must be non-null.
1313 ///
1314 /// [valid]: self#safety
1315 ///
1316 /// ## On `packed` structs
1317 ///
1318 /// Attempting to create a raw pointer to an `unaligned` struct field with
1319 /// an expression such as `&packed.unaligned as *const FieldType` creates an
1320 /// intermediate unaligned reference before converting that to a raw pointer.
1321 /// That this reference is temporary and immediately cast is inconsequential
1322 /// as the compiler always expects references to be properly aligned.
1323 /// As a result, using `&packed.unaligned as *const FieldType` causes immediate
1324 /// *undefined behavior* in your program.
1325 ///
1326 /// Instead you must use the [`ptr::addr_of_mut!`](addr_of_mut)
1327 /// macro to create the pointer. You may use that returned pointer together with
1328 /// this function.
1329 ///
1330 /// An example of how to do it and how this relates to `write_unaligned` is:
1331 ///
1332 /// ```
1333 /// #[repr(packed, C)]
1334 /// struct Packed {
1335 ///     _padding: u8,
1336 ///     unaligned: u32,
1337 /// }
1338 ///
1339 /// let mut packed: Packed = unsafe { std::mem::zeroed() };
1340 ///
1341 /// // Take the address of a 32-bit integer which is not aligned.
1342 /// // In contrast to `&packed.unaligned as *mut _`, this has no undefined behavior.
1343 /// let unaligned = std::ptr::addr_of_mut!(packed.unaligned);
1344 ///
1345 /// unsafe { std::ptr::write_unaligned(unaligned, 42) };
1346 ///
1347 /// assert_eq!({packed.unaligned}, 42); // `{...}` forces copying the field instead of creating a reference.
1348 /// ```
1349 ///
1350 /// Accessing unaligned fields directly with e.g. `packed.unaligned` is safe however
1351 /// (as can be seen in the `assert_eq!` above).
1352 ///
1353 /// # Examples
1354 ///
1355 /// Write a usize value to a byte buffer:
1356 ///
1357 /// ```
1358 /// use std::mem;
1359 ///
1360 /// fn write_usize(x: &mut [u8], val: usize) {
1361 ///     assert!(x.len() >= mem::size_of::<usize>());
1362 ///
1363 ///     let ptr = x.as_mut_ptr() as *mut usize;
1364 ///
1365 ///     unsafe { ptr.write_unaligned(val) }
1366 /// }
1367 /// ```
1368 #[inline]
1369 #[stable(feature = "ptr_unaligned", since = "1.17.0")]
1370 #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")]
1371 pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) {
1372     // SAFETY: the caller must guarantee that `dst` is valid for writes.
1373     // `dst` cannot overlap `src` because the caller has mutable access
1374     // to `dst` while `src` is owned by this function.
1375     unsafe {
1376         copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::<T>());
1377         // We are calling the intrinsic directly to avoid function calls in the generated code.
1378         intrinsics::forget(src);
1379     }
1380 }
1381
1382 /// Performs a volatile read of the value from `src` without moving it. This
1383 /// leaves the memory in `src` unchanged.
1384 ///
1385 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1386 /// to not be elided or reordered by the compiler across other volatile
1387 /// operations.
1388 ///
1389 /// # Notes
1390 ///
1391 /// Rust does not currently have a rigorously and formally defined memory model,
1392 /// so the precise semantics of what "volatile" means here is subject to change
1393 /// over time. That being said, the semantics will almost always end up pretty
1394 /// similar to [C11's definition of volatile][c11].
1395 ///
1396 /// The compiler shouldn't change the relative order or number of volatile
1397 /// memory operations. However, volatile memory operations on zero-sized types
1398 /// (e.g., if a zero-sized type is passed to `read_volatile`) are noops
1399 /// and may be ignored.
1400 ///
1401 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1402 ///
1403 /// # Safety
1404 ///
1405 /// Behavior is undefined if any of the following conditions are violated:
1406 ///
1407 /// * `src` must be [valid] for reads.
1408 ///
1409 /// * `src` must be properly aligned.
1410 ///
1411 /// * `src` must point to a properly initialized value of type `T`.
1412 ///
1413 /// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of
1414 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned
1415 /// value and the value at `*src` can [violate memory safety][read-ownership].
1416 /// However, storing non-[`Copy`] types in volatile memory is almost certainly
1417 /// incorrect.
1418 ///
1419 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1420 ///
1421 /// [valid]: self#safety
1422 /// [read-ownership]: read#ownership-of-the-returned-value
1423 ///
1424 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1425 /// on questions involving concurrent access from multiple threads. Volatile
1426 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1427 /// a race between a `read_volatile` and any write operation to the same location
1428 /// is undefined behavior.
1429 ///
1430 /// # Examples
1431 ///
1432 /// Basic usage:
1433 ///
1434 /// ```
1435 /// let x = 12;
1436 /// let y = &x as *const i32;
1437 ///
1438 /// unsafe {
1439 ///     assert_eq!(std::ptr::read_volatile(y), 12);
1440 /// }
1441 /// ```
1442 #[inline]
1443 #[stable(feature = "volatile", since = "1.9.0")]
1444 pub unsafe fn read_volatile<T>(src: *const T) -> T {
1445     // SAFETY: the caller must uphold the safety contract for `volatile_load`.
1446     unsafe {
1447         assert_unsafe_precondition!(is_aligned_and_not_null(src));
1448         intrinsics::volatile_load(src)
1449     }
1450 }
1451
1452 /// Performs a volatile write of a memory location with the given value without
1453 /// reading or dropping the old value.
1454 ///
1455 /// Volatile operations are intended to act on I/O memory, and are guaranteed
1456 /// to not be elided or reordered by the compiler across other volatile
1457 /// operations.
1458 ///
1459 /// `write_volatile` does not drop the contents of `dst`. This is safe, but it
1460 /// could leak allocations or resources, so care should be taken not to overwrite
1461 /// an object that should be dropped.
1462 ///
1463 /// Additionally, it does not drop `src`. Semantically, `src` is moved into the
1464 /// location pointed to by `dst`.
1465 ///
1466 /// # Notes
1467 ///
1468 /// Rust does not currently have a rigorously and formally defined memory model,
1469 /// so the precise semantics of what "volatile" means here is subject to change
1470 /// over time. That being said, the semantics will almost always end up pretty
1471 /// similar to [C11's definition of volatile][c11].
1472 ///
1473 /// The compiler shouldn't change the relative order or number of volatile
1474 /// memory operations. However, volatile memory operations on zero-sized types
1475 /// (e.g., if a zero-sized type is passed to `write_volatile`) are noops
1476 /// and may be ignored.
1477 ///
1478 /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
1479 ///
1480 /// # Safety
1481 ///
1482 /// Behavior is undefined if any of the following conditions are violated:
1483 ///
1484 /// * `dst` must be [valid] for writes.
1485 ///
1486 /// * `dst` must be properly aligned.
1487 ///
1488 /// Note that even if `T` has size `0`, the pointer must be non-null and properly aligned.
1489 ///
1490 /// [valid]: self#safety
1491 ///
1492 /// Just like in C, whether an operation is volatile has no bearing whatsoever
1493 /// on questions involving concurrent access from multiple threads. Volatile
1494 /// accesses behave exactly like non-atomic accesses in that regard. In particular,
1495 /// a race between a `write_volatile` and any other operation (reading or writing)
1496 /// on the same location is undefined behavior.
1497 ///
1498 /// # Examples
1499 ///
1500 /// Basic usage:
1501 ///
1502 /// ```
1503 /// let mut x = 0;
1504 /// let y = &mut x as *mut i32;
1505 /// let z = 12;
1506 ///
1507 /// unsafe {
1508 ///     std::ptr::write_volatile(y, z);
1509 ///     assert_eq!(std::ptr::read_volatile(y), 12);
1510 /// }
1511 /// ```
1512 #[inline]
1513 #[stable(feature = "volatile", since = "1.9.0")]
1514 pub unsafe fn write_volatile<T>(dst: *mut T, src: T) {
1515     // SAFETY: the caller must uphold the safety contract for `volatile_store`.
1516     unsafe {
1517         assert_unsafe_precondition!(is_aligned_and_not_null(dst));
1518         intrinsics::volatile_store(dst, src);
1519     }
1520 }
1521
1522 /// Align pointer `p`.
1523 ///
1524 /// Calculate offset (in terms of elements of `stride` stride) that has to be applied
1525 /// to pointer `p` so that pointer `p` would get aligned to `a`.
1526 ///
1527 /// Note: This implementation has been carefully tailored to not panic. It is UB for this to panic.
1528 /// The only real change that can be made here is change of `INV_TABLE_MOD_16` and associated
1529 /// constants.
1530 ///
1531 /// If we ever decide to make it possible to call the intrinsic with `a` that is not a
1532 /// power-of-two, it will probably be more prudent to just change to a naive implementation rather
1533 /// than trying to adapt this to accommodate that change.
1534 ///
1535 /// Any questions go to @nagisa.
1536 #[lang = "align_offset"]
1537 pub(crate) unsafe fn align_offset<T: Sized>(p: *const T, a: usize) -> usize {
1538     // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <=
1539     // 1, where the method versions of these operations are not inlined.
1540     use intrinsics::{
1541         unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub,
1542     };
1543
1544     let addr = p.addr();
1545
1546     /// Calculate multiplicative modular inverse of `x` modulo `m`.
1547     ///
1548     /// This implementation is tailored for `align_offset` and has following preconditions:
1549     ///
1550     /// * `m` is a power-of-two;
1551     /// * `x < m`; (if `x ≥ m`, pass in `x % m` instead)
1552     ///
1553     /// Implementation of this function shall not panic. Ever.
1554     #[inline]
1555     unsafe fn mod_inv(x: usize, m: usize) -> usize {
1556         /// Multiplicative modular inverse table modulo 2⁴ = 16.
1557         ///
1558         /// Note, that this table does not contain values where inverse does not exist (i.e., for
1559         /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.)
1560         const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15];
1561         /// Modulo for which the `INV_TABLE_MOD_16` is intended.
1562         const INV_TABLE_MOD: usize = 16;
1563         /// INV_TABLE_MOD²
1564         const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD;
1565
1566         let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize;
1567         // SAFETY: `m` is required to be a power-of-two, hence non-zero.
1568         let m_minus_one = unsafe { unchecked_sub(m, 1) };
1569         if m <= INV_TABLE_MOD {
1570             table_inverse & m_minus_one
1571         } else {
1572             // We iterate "up" using the following formula:
1573             //
1574             // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$
1575             //
1576             // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`.
1577             let mut inverse = table_inverse;
1578             let mut going_mod = INV_TABLE_MOD_SQUARED;
1579             loop {
1580                 // y = y * (2 - xy) mod n
1581                 //
1582                 // Note, that we use wrapping operations here intentionally – the original formula
1583                 // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod
1584                 // usize::MAX` instead, because we take the result `mod n` at the end
1585                 // anyway.
1586                 inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse)));
1587                 if going_mod >= m {
1588                     return inverse & m_minus_one;
1589                 }
1590                 going_mod = wrapping_mul(going_mod, going_mod);
1591             }
1592         }
1593     }
1594
1595     let stride = mem::size_of::<T>();
1596     // SAFETY: `a` is a power-of-two, therefore non-zero.
1597     let a_minus_one = unsafe { unchecked_sub(a, 1) };
1598     if stride == 1 {
1599         // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so
1600         // inhibits LLVM's ability to select instructions like `lea`. Instead we compute
1601         //
1602         //    round_up_to_next_alignment(p, a) - p
1603         //
1604         // which distributes operations around the load-bearing, but pessimizing `and` sufficiently
1605         // for LLVM to be able to utilize the various optimizations it knows about.
1606         return wrapping_sub(wrapping_add(addr, a_minus_one) & wrapping_sub(0, a), addr);
1607     }
1608
1609     let pmoda = addr & a_minus_one;
1610     if pmoda == 0 {
1611         // Already aligned. Yay!
1612         return 0;
1613     } else if stride == 0 {
1614         // If the pointer is not aligned, and the element is zero-sized, then no amount of
1615         // elements will ever align the pointer.
1616         return usize::MAX;
1617     }
1618
1619     let smoda = stride & a_minus_one;
1620     // SAFETY: a is power-of-two hence non-zero. stride == 0 case is handled above.
1621     let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) };
1622     // SAFETY: gcdpow has an upper-bound that’s at most the number of bits in a usize.
1623     let gcd = unsafe { unchecked_shl(1usize, gcdpow) };
1624
1625     // SAFETY: gcd is always greater or equal to 1.
1626     if addr & unsafe { unchecked_sub(gcd, 1) } == 0 {
1627         // This branch solves for the following linear congruence equation:
1628         //
1629         // ` p + so = 0 mod a `
1630         //
1631         // `p` here is the pointer value, `s` - stride of `T`, `o` offset in `T`s, and `a` - the
1632         // requested alignment.
1633         //
1634         // With `g = gcd(a, s)`, and the above condition asserting that `p` is also divisible by
1635         // `g`, we can denote `a' = a/g`, `s' = s/g`, `p' = p/g`, then this becomes equivalent to:
1636         //
1637         // ` p' + s'o = 0 mod a' `
1638         // ` o = (a' - (p' mod a')) * (s'^-1 mod a') `
1639         //
1640         // The first term is "the relative alignment of `p` to `a`" (divided by the `g`), the second
1641         // term is "how does incrementing `p` by `s` bytes change the relative alignment of `p`" (again
1642         // divided by `g`).
1643         // Division by `g` is necessary to make the inverse well formed if `a` and `s` are not
1644         // co-prime.
1645         //
1646         // Furthermore, the result produced by this solution is not "minimal", so it is necessary
1647         // to take the result `o mod lcm(s, a)`. We can replace `lcm(s, a)` with just a `a'`.
1648
1649         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1650         // `a`.
1651         let a2 = unsafe { unchecked_shr(a, gcdpow) };
1652         // SAFETY: `a2` is non-zero. Shifting `a` by `gcdpow` cannot shift out any of the set bits
1653         // in `a` (of which it has exactly one).
1654         let a2minus1 = unsafe { unchecked_sub(a2, 1) };
1655         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1656         // `a`.
1657         let s2 = unsafe { unchecked_shr(smoda, gcdpow) };
1658         // SAFETY: `gcdpow` has an upper-bound not greater than the number of trailing 0-bits in
1659         // `a`. Furthermore, the subtraction cannot overflow, because `a2 = a >> gcdpow` will
1660         // always be strictly greater than `(p % a) >> gcdpow`.
1661         let minusp2 = unsafe { unchecked_sub(a2, unchecked_shr(pmoda, gcdpow)) };
1662         // SAFETY: `a2` is a power-of-two, as proven above. `s2` is strictly less than `a2`
1663         // because `(s % a) >> gcdpow` is strictly less than `a >> gcdpow`.
1664         return wrapping_mul(minusp2, unsafe { mod_inv(s2, a2) }) & a2minus1;
1665     }
1666
1667     // Cannot be aligned at all.
1668     usize::MAX
1669 }
1670
1671 /// Compares raw pointers for equality.
1672 ///
1673 /// This is the same as using the `==` operator, but less generic:
1674 /// the arguments have to be `*const T` raw pointers,
1675 /// not anything that implements `PartialEq`.
1676 ///
1677 /// This can be used to compare `&T` references (which coerce to `*const T` implicitly)
1678 /// by their address rather than comparing the values they point to
1679 /// (which is what the `PartialEq for &T` implementation does).
1680 ///
1681 /// # Examples
1682 ///
1683 /// ```
1684 /// use std::ptr;
1685 ///
1686 /// let five = 5;
1687 /// let other_five = 5;
1688 /// let five_ref = &five;
1689 /// let same_five_ref = &five;
1690 /// let other_five_ref = &other_five;
1691 ///
1692 /// assert!(five_ref == same_five_ref);
1693 /// assert!(ptr::eq(five_ref, same_five_ref));
1694 ///
1695 /// assert!(five_ref == other_five_ref);
1696 /// assert!(!ptr::eq(five_ref, other_five_ref));
1697 /// ```
1698 ///
1699 /// Slices are also compared by their length (fat pointers):
1700 ///
1701 /// ```
1702 /// let a = [1, 2, 3];
1703 /// assert!(std::ptr::eq(&a[..3], &a[..3]));
1704 /// assert!(!std::ptr::eq(&a[..2], &a[..3]));
1705 /// assert!(!std::ptr::eq(&a[0..2], &a[1..3]));
1706 /// ```
1707 ///
1708 /// Traits are also compared by their implementation:
1709 ///
1710 /// ```
1711 /// #[repr(transparent)]
1712 /// struct Wrapper { member: i32 }
1713 ///
1714 /// trait Trait {}
1715 /// impl Trait for Wrapper {}
1716 /// impl Trait for i32 {}
1717 ///
1718 /// let wrapper = Wrapper { member: 10 };
1719 ///
1720 /// // Pointers have equal addresses.
1721 /// assert!(std::ptr::eq(
1722 ///     &wrapper as *const Wrapper as *const u8,
1723 ///     &wrapper.member as *const i32 as *const u8
1724 /// ));
1725 ///
1726 /// // Objects have equal addresses, but `Trait` has different implementations.
1727 /// assert!(!std::ptr::eq(
1728 ///     &wrapper as &dyn Trait,
1729 ///     &wrapper.member as &dyn Trait,
1730 /// ));
1731 /// assert!(!std::ptr::eq(
1732 ///     &wrapper as &dyn Trait as *const dyn Trait,
1733 ///     &wrapper.member as &dyn Trait as *const dyn Trait,
1734 /// ));
1735 ///
1736 /// // Converting the reference to a `*const u8` compares by address.
1737 /// assert!(std::ptr::eq(
1738 ///     &wrapper as &dyn Trait as *const dyn Trait as *const u8,
1739 ///     &wrapper.member as &dyn Trait as *const dyn Trait as *const u8,
1740 /// ));
1741 /// ```
1742 #[stable(feature = "ptr_eq", since = "1.17.0")]
1743 #[inline]
1744 pub fn eq<T: ?Sized>(a: *const T, b: *const T) -> bool {
1745     a == b
1746 }
1747
1748 /// Hash a raw pointer.
1749 ///
1750 /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly)
1751 /// by its address rather than the value it points to
1752 /// (which is what the `Hash for &T` implementation does).
1753 ///
1754 /// # Examples
1755 ///
1756 /// ```
1757 /// use std::collections::hash_map::DefaultHasher;
1758 /// use std::hash::{Hash, Hasher};
1759 /// use std::ptr;
1760 ///
1761 /// let five = 5;
1762 /// let five_ref = &five;
1763 ///
1764 /// let mut hasher = DefaultHasher::new();
1765 /// ptr::hash(five_ref, &mut hasher);
1766 /// let actual = hasher.finish();
1767 ///
1768 /// let mut hasher = DefaultHasher::new();
1769 /// (five_ref as *const i32).hash(&mut hasher);
1770 /// let expected = hasher.finish();
1771 ///
1772 /// assert_eq!(actual, expected);
1773 /// ```
1774 #[stable(feature = "ptr_hash", since = "1.35.0")]
1775 pub fn hash<T: ?Sized, S: hash::Hasher>(hashee: *const T, into: &mut S) {
1776     use crate::hash::Hash;
1777     hashee.hash(into);
1778 }
1779
1780 // FIXME(strict_provenance_magic): function pointers have buggy codegen that
1781 // necessitates casting to a usize to get the backend to do the right thing.
1782 // for now I will break AVR to silence *a billion* lints. We should probably
1783 // have a proper "opaque function pointer type" to handle this kind of thing.
1784
1785 // Impls for function pointers
1786 macro_rules! fnptr_impls_safety_abi {
1787     ($FnTy: ty, $($Arg: ident),*) => {
1788         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1789         impl<Ret, $($Arg),*> PartialEq for $FnTy {
1790             #[inline]
1791             fn eq(&self, other: &Self) -> bool {
1792                 *self as usize == *other as usize
1793             }
1794         }
1795
1796         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1797         impl<Ret, $($Arg),*> Eq for $FnTy {}
1798
1799         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1800         impl<Ret, $($Arg),*> PartialOrd for $FnTy {
1801             #[inline]
1802             fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1803                 (*self as usize).partial_cmp(&(*other as usize))
1804             }
1805         }
1806
1807         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1808         impl<Ret, $($Arg),*> Ord for $FnTy {
1809             #[inline]
1810             fn cmp(&self, other: &Self) -> Ordering {
1811                 (*self as usize).cmp(&(*other as usize))
1812             }
1813         }
1814
1815         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1816         impl<Ret, $($Arg),*> hash::Hash for $FnTy {
1817             fn hash<HH: hash::Hasher>(&self, state: &mut HH) {
1818                 state.write_usize(*self as usize)
1819             }
1820         }
1821
1822         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1823         impl<Ret, $($Arg),*> fmt::Pointer for $FnTy {
1824             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1825                 // HACK: The intermediate cast as usize is required for AVR
1826                 // so that the address space of the source function pointer
1827                 // is preserved in the final function pointer.
1828                 //
1829                 // https://github.com/avr-rust/rust/issues/143
1830                 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1831             }
1832         }
1833
1834         #[stable(feature = "fnptr_impls", since = "1.4.0")]
1835         impl<Ret, $($Arg),*> fmt::Debug for $FnTy {
1836             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1837                 // HACK: The intermediate cast as usize is required for AVR
1838                 // so that the address space of the source function pointer
1839                 // is preserved in the final function pointer.
1840                 //
1841                 // https://github.com/avr-rust/rust/issues/143
1842                 fmt::Pointer::fmt(&(*self as usize as *const ()), f)
1843             }
1844         }
1845     }
1846 }
1847
1848 macro_rules! fnptr_impls_args {
1849     ($($Arg: ident),+) => {
1850         fnptr_impls_safety_abi! { extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1851         fnptr_impls_safety_abi! { extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1852         fnptr_impls_safety_abi! { extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1853         fnptr_impls_safety_abi! { unsafe extern "Rust" fn($($Arg),+) -> Ret, $($Arg),+ }
1854         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+) -> Ret, $($Arg),+ }
1855         fnptr_impls_safety_abi! { unsafe extern "C" fn($($Arg),+ , ...) -> Ret, $($Arg),+ }
1856     };
1857     () => {
1858         // No variadic functions with 0 parameters
1859         fnptr_impls_safety_abi! { extern "Rust" fn() -> Ret, }
1860         fnptr_impls_safety_abi! { extern "C" fn() -> Ret, }
1861         fnptr_impls_safety_abi! { unsafe extern "Rust" fn() -> Ret, }
1862         fnptr_impls_safety_abi! { unsafe extern "C" fn() -> Ret, }
1863     };
1864 }
1865
1866 fnptr_impls_args! {}
1867 fnptr_impls_args! { A }
1868 fnptr_impls_args! { A, B }
1869 fnptr_impls_args! { A, B, C }
1870 fnptr_impls_args! { A, B, C, D }
1871 fnptr_impls_args! { A, B, C, D, E }
1872 fnptr_impls_args! { A, B, C, D, E, F }
1873 fnptr_impls_args! { A, B, C, D, E, F, G }
1874 fnptr_impls_args! { A, B, C, D, E, F, G, H }
1875 fnptr_impls_args! { A, B, C, D, E, F, G, H, I }
1876 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J }
1877 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K }
1878 fnptr_impls_args! { A, B, C, D, E, F, G, H, I, J, K, L }
1879
1880 /// Create a `const` raw pointer to a place, without creating an intermediate reference.
1881 ///
1882 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1883 /// and points to initialized data. For cases where those requirements do not hold,
1884 /// raw pointers should be used instead. However, `&expr as *const _` creates a reference
1885 /// before casting it to a raw pointer, and that reference is subject to the same rules
1886 /// as all other references. This macro can create a raw pointer *without* creating
1887 /// a reference first.
1888 ///
1889 /// Note, however, that the `expr` in `addr_of!(expr)` is still subject to all
1890 /// the usual rules. In particular, `addr_of!(*ptr::null())` is Undefined
1891 /// Behavior because it dereferences a null pointer.
1892 ///
1893 /// # Example
1894 ///
1895 /// ```
1896 /// use std::ptr;
1897 ///
1898 /// #[repr(packed)]
1899 /// struct Packed {
1900 ///     f1: u8,
1901 ///     f2: u16,
1902 /// }
1903 ///
1904 /// let packed = Packed { f1: 1, f2: 2 };
1905 /// // `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1906 /// let raw_f2 = ptr::addr_of!(packed.f2);
1907 /// assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
1908 /// ```
1909 ///
1910 /// See [`addr_of_mut`] for how to create a pointer to unininitialized data.
1911 /// Doing that with `addr_of` would not make much sense since one could only
1912 /// read the data, and that would be Undefined Behavior.
1913 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1914 #[rustc_macro_transparency = "semitransparent"]
1915 #[allow_internal_unstable(raw_ref_op)]
1916 pub macro addr_of($place:expr) {
1917     &raw const $place
1918 }
1919
1920 /// Create a `mut` raw pointer to a place, without creating an intermediate reference.
1921 ///
1922 /// Creating a reference with `&`/`&mut` is only allowed if the pointer is properly aligned
1923 /// and points to initialized data. For cases where those requirements do not hold,
1924 /// raw pointers should be used instead. However, `&mut expr as *mut _` creates a reference
1925 /// before casting it to a raw pointer, and that reference is subject to the same rules
1926 /// as all other references. This macro can create a raw pointer *without* creating
1927 /// a reference first.
1928 ///
1929 /// Note, however, that the `expr` in `addr_of_mut!(expr)` is still subject to all
1930 /// the usual rules. In particular, `addr_of_mut!(*ptr::null_mut())` is Undefined
1931 /// Behavior because it dereferences a null pointer.
1932 ///
1933 /// # Examples
1934 ///
1935 /// **Creating a pointer to unaligned data:**
1936 ///
1937 /// ```
1938 /// use std::ptr;
1939 ///
1940 /// #[repr(packed)]
1941 /// struct Packed {
1942 ///     f1: u8,
1943 ///     f2: u16,
1944 /// }
1945 ///
1946 /// let mut packed = Packed { f1: 1, f2: 2 };
1947 /// // `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
1948 /// let raw_f2 = ptr::addr_of_mut!(packed.f2);
1949 /// unsafe { raw_f2.write_unaligned(42); }
1950 /// assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
1951 /// ```
1952 ///
1953 /// **Creating a pointer to uninitialized data:**
1954 ///
1955 /// ```rust
1956 /// use std::{ptr, mem::MaybeUninit};
1957 ///
1958 /// struct Demo {
1959 ///     field: bool,
1960 /// }
1961 ///
1962 /// let mut uninit = MaybeUninit::<Demo>::uninit();
1963 /// // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
1964 /// // and thus be Undefined Behavior!
1965 /// let f1_ptr = unsafe { ptr::addr_of_mut!((*uninit.as_mut_ptr()).field) };
1966 /// unsafe { f1_ptr.write(true); }
1967 /// let init = unsafe { uninit.assume_init() };
1968 /// ```
1969 #[stable(feature = "raw_ref_macros", since = "1.51.0")]
1970 #[rustc_macro_transparency = "semitransparent"]
1971 #[allow_internal_unstable(raw_ref_op)]
1972 pub macro addr_of_mut($place:expr) {
1973     &raw mut $place
1974 }