zerocopy/pointer/ptr.rs
1// Copyright 2023 The Fuchsia Authors
2//
3// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
4// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
5// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
6// This file may not be copied, modified, or distributed except according to
7// those terms.
8
9use core::{
10 fmt::{Debug, Formatter},
11 marker::PhantomData,
12};
13
14use crate::{
15 pointer::{
16 inner::PtrInner,
17 invariant::*,
18 transmute::{MutationCompatible, SizeEq, TransmuteFromPtr},
19 },
20 AlignmentError, CastError, CastType, KnownLayout, SizeError, TryFromBytes, ValidityError,
21};
22
23/// Module used to gate access to [`Ptr`]'s fields.
24mod def {
25 #[cfg(doc)]
26 use super::super::invariant;
27 use super::*;
28
29 /// A raw pointer with more restrictions.
30 ///
31 /// `Ptr<T>` is similar to [`NonNull<T>`], but it is more restrictive in the
32 /// following ways (note that these requirements only hold of non-zero-sized
33 /// referents):
34 /// - It must derive from a valid allocation.
35 /// - It must reference a byte range which is contained inside the
36 /// allocation from which it derives.
37 /// - As a consequence, the byte range it references must have a size
38 /// which does not overflow `isize`.
39 ///
40 /// Depending on how `Ptr` is parameterized, it may have additional
41 /// invariants:
42 /// - `ptr` conforms to the aliasing invariant of
43 /// [`I::Aliasing`](invariant::Aliasing).
44 /// - `ptr` conforms to the alignment invariant of
45 /// [`I::Alignment`](invariant::Alignment).
46 /// - `ptr` conforms to the validity invariant of
47 /// [`I::Validity`](invariant::Validity).
48 ///
49 /// `Ptr<'a, T>` is [covariant] in `'a` and invariant in `T`.
50 ///
51 /// [`NonNull<T>`]: core::ptr::NonNull
52 /// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
53 pub struct Ptr<'a, T, I>
54 where
55 T: ?Sized,
56 I: Invariants,
57 {
58 /// # Invariants
59 ///
60 /// 0. `ptr` conforms to the aliasing invariant of
61 /// [`I::Aliasing`](invariant::Aliasing).
62 /// 1. `ptr` conforms to the alignment invariant of
63 /// [`I::Alignment`](invariant::Alignment).
64 /// 2. `ptr` conforms to the validity invariant of
65 /// [`I::Validity`](invariant::Validity).
66 // SAFETY: `PtrInner<'a, T>` is covariant in `'a` and invariant in `T`.
67 ptr: PtrInner<'a, T>,
68 _invariants: PhantomData<I>,
69 }
70
71 impl<'a, T, I> Ptr<'a, T, I>
72 where
73 T: 'a + ?Sized,
74 I: Invariants,
75 {
76 /// Constructs a new `Ptr` from a [`PtrInner`].
77 ///
78 /// # Safety
79 ///
80 /// The caller promises that:
81 ///
82 /// 0. `ptr` conforms to the aliasing invariant of
83 /// [`I::Aliasing`](invariant::Aliasing).
84 /// 1. `ptr` conforms to the alignment invariant of
85 /// [`I::Alignment`](invariant::Alignment).
86 /// 2. `ptr` conforms to the validity invariant of
87 /// [`I::Validity`](invariant::Validity).
88 pub(crate) unsafe fn from_inner(ptr: PtrInner<'a, T>) -> Ptr<'a, T, I> {
89 // SAFETY: The caller has promised to satisfy all safety invariants
90 // of `Ptr`.
91 Self { ptr, _invariants: PhantomData }
92 }
93
94 /// Converts this `Ptr<T>` to a [`PtrInner<T>`].
95 ///
96 /// Note that this method does not consume `self`. The caller should
97 /// watch out for `unsafe` code which uses the returned value in a way
98 /// that violates the safety invariants of `self`.
99 pub(crate) fn as_inner(&self) -> PtrInner<'a, T> {
100 self.ptr
101 }
102 }
103}
104
105#[allow(unreachable_pub)] // This is a false positive on our MSRV toolchain.
106pub use def::Ptr;
107
108/// External trait implementations on [`Ptr`].
109mod _external {
110 use super::*;
111
112 /// SAFETY: Shared pointers are safely `Copy`. `Ptr`'s other invariants
113 /// (besides aliasing) are unaffected by the number of references that exist
114 /// to `Ptr`'s referent. The notable cases are:
115 /// - Alignment is a property of the referent type (`T`) and the address,
116 /// both of which are unchanged
117 /// - Let `S(T, V)` be the set of bit values permitted to appear in the
118 /// referent of a `Ptr<T, I: Invariants<Validity = V>>`. Since this copy
119 /// does not change `I::Validity` or `T`, `S(T, I::Validity)` is also
120 /// unchanged.
121 ///
122 /// We are required to guarantee that the referents of the original `Ptr`
123 /// and of the copy (which, of course, are actually the same since they
124 /// live in the same byte address range) both remain in the set `S(T,
125 /// I::Validity)`. Since this invariant holds on the original `Ptr`, it
126 /// cannot be violated by the original `Ptr`, and thus the original `Ptr`
127 /// cannot be used to violate this invariant on the copy. The inverse
128 /// holds as well.
129 impl<'a, T, I> Copy for Ptr<'a, T, I>
130 where
131 T: 'a + ?Sized,
132 I: Invariants<Aliasing = Shared>,
133 {
134 }
135
136 /// SAFETY: See the safety comment on `Copy`.
137 impl<'a, T, I> Clone for Ptr<'a, T, I>
138 where
139 T: 'a + ?Sized,
140 I: Invariants<Aliasing = Shared>,
141 {
142 #[inline]
143 fn clone(&self) -> Self {
144 *self
145 }
146 }
147
148 impl<'a, T, I> Debug for Ptr<'a, T, I>
149 where
150 T: 'a + ?Sized,
151 I: Invariants,
152 {
153 #[inline]
154 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
155 self.as_inner().as_non_null().fmt(f)
156 }
157 }
158}
159
160/// Methods for converting to and from `Ptr` and Rust's safe reference types.
161mod _conversions {
162 use super::*;
163 use crate::pointer::cast::CastSized;
164
165 /// `&'a T` → `Ptr<'a, T>`
166 impl<'a, T> Ptr<'a, T, (Shared, Aligned, Valid)>
167 where
168 T: 'a + ?Sized,
169 {
170 /// Constructs a `Ptr` from a shared reference.
171 #[doc(hidden)]
172 #[inline(always)]
173 pub fn from_ref(ptr: &'a T) -> Self {
174 let inner = PtrInner::from_ref(ptr);
175 // SAFETY:
176 // 0. `ptr`, by invariant on `&'a T`, conforms to the aliasing
177 // invariant of `Shared`.
178 // 1. `ptr`, by invariant on `&'a T`, conforms to the alignment
179 // invariant of `Aligned`.
180 // 2. `ptr`'s referent, by invariant on `&'a T`, is a bit-valid `T`.
181 // This satisfies the requirement that a `Ptr<T, (_, _, Valid)>`
182 // point to a bit-valid `T`. Even if `T` permits interior
183 // mutation, this invariant guarantees that the returned `Ptr`
184 // can only ever be used to modify the referent to store
185 // bit-valid `T`s, which ensures that the returned `Ptr` cannot
186 // be used to violate the soundness of the original `ptr: &'a T`
187 // or of any other references that may exist to the same
188 // referent.
189 unsafe { Self::from_inner(inner) }
190 }
191 }
192
193 /// `&'a mut T` → `Ptr<'a, T>`
194 impl<'a, T> Ptr<'a, T, (Exclusive, Aligned, Valid)>
195 where
196 T: 'a + ?Sized,
197 {
198 /// Constructs a `Ptr` from an exclusive reference.
199 #[doc(hidden)]
200 #[inline(always)]
201 pub fn from_mut(ptr: &'a mut T) -> Self {
202 let inner = PtrInner::from_mut(ptr);
203 // SAFETY:
204 // 0. `ptr`, by invariant on `&'a mut T`, conforms to the aliasing
205 // invariant of `Exclusive`.
206 // 1. `ptr`, by invariant on `&'a mut T`, conforms to the alignment
207 // invariant of `Aligned`.
208 // 2. `ptr`'s referent, by invariant on `&'a mut T`, is a bit-valid
209 // `T`. This satisfies the requirement that a `Ptr<T, (_, _,
210 // Valid)>` point to a bit-valid `T`. This invariant guarantees
211 // that the returned `Ptr` can only ever be used to modify the
212 // referent to store bit-valid `T`s, which ensures that the
213 // returned `Ptr` cannot be used to violate the soundness of the
214 // original `ptr: &'a mut T`.
215 unsafe { Self::from_inner(inner) }
216 }
217 }
218
219 /// `Ptr<'a, T>` → `&'a T`
220 impl<'a, T, I> Ptr<'a, T, I>
221 where
222 T: 'a + ?Sized,
223 I: Invariants<Alignment = Aligned, Validity = Valid>,
224 I::Aliasing: Reference,
225 {
226 /// Converts `self` to a shared reference.
227 // This consumes `self`, not `&self`, because `self` is, logically, a
228 // pointer. For `I::Aliasing = invariant::Shared`, `Self: Copy`, and so
229 // this doesn't prevent the caller from still using the pointer after
230 // calling `as_ref`.
231 #[allow(clippy::wrong_self_convention)]
232 pub(crate) fn as_ref(self) -> &'a T {
233 let raw = self.as_inner().as_non_null();
234 // SAFETY: `self` satisfies the `Aligned` invariant, so we know that
235 // `raw` is validly-aligned for `T`.
236 #[cfg(miri)]
237 unsafe {
238 crate::util::miri_promise_symbolic_alignment(
239 raw.as_ptr().cast(),
240 core::mem::align_of_val_raw(raw.as_ptr()),
241 );
242 }
243 // SAFETY: This invocation of `NonNull::as_ref` satisfies its
244 // documented safety preconditions:
245 //
246 // 1. The pointer is properly aligned. This is ensured by-contract
247 // on `Ptr`, because the `I::Alignment` is `Aligned`.
248 //
249 // 2. If the pointer's referent is not zero-sized, then the pointer
250 // must be “dereferenceable” in the sense defined in the module
251 // documentation; i.e.:
252 //
253 // > The memory range of the given size starting at the pointer
254 // > must all be within the bounds of a single allocated object.
255 // > [2]
256 //
257 // This is ensured by contract on all `PtrInner`s.
258 //
259 // 3. The pointer must point to a validly-initialized instance of
260 // `T`. This is ensured by-contract on `Ptr`, because the
261 // `I::Validity` is `Valid`.
262 //
263 // 4. You must enforce Rust’s aliasing rules. This is ensured by
264 // contract on `Ptr`, because `I::Aliasing: Reference`. Either it
265 // is `Shared` or `Exclusive`. If it is `Shared`, other
266 // references may not mutate the referent outside of
267 // `UnsafeCell`s.
268 //
269 // [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_ref
270 // [2]: https://doc.rust-lang.org/std/ptr/index.html#safety
271 unsafe { raw.as_ref() }
272 }
273 }
274
275 impl<'a, T, I> Ptr<'a, T, I>
276 where
277 T: 'a + ?Sized,
278 I: Invariants,
279 I::Aliasing: Reference,
280 {
281 /// Reborrows `self`, producing another `Ptr`.
282 ///
283 /// Since `self` is borrowed immutably, this prevents any mutable
284 /// methods from being called on `self` as long as the returned `Ptr`
285 /// exists.
286 #[doc(hidden)]
287 #[inline]
288 #[allow(clippy::needless_lifetimes)] // Allows us to name the lifetime in the safety comment below.
289 pub fn reborrow<'b>(&'b mut self) -> Ptr<'b, T, I>
290 where
291 'a: 'b,
292 {
293 // SAFETY: The following all hold by invariant on `self`, and thus
294 // hold of `ptr = self.as_inner()`:
295 // 0. SEE BELOW.
296 // 1. `ptr` conforms to the alignment invariant of
297 // [`I::Alignment`](invariant::Alignment).
298 // 2. `ptr` conforms to the validity invariant of
299 // [`I::Validity`](invariant::Validity). `self` and the returned
300 // `Ptr` permit the same bit values in their referents since they
301 // have the same referent type (`T`) and the same validity
302 // (`I::Validity`). Thus, regardless of what mutation is
303 // permitted (`Exclusive` aliasing or `Shared`-aliased interior
304 // mutation), neither can be used to write a value to the
305 // referent which violates the other's validity invariant.
306 //
307 // For aliasing (0 above), since `I::Aliasing: Reference`,
308 // there are two cases for `I::Aliasing`:
309 // - For `invariant::Shared`: `'a` outlives `'b`, and so the
310 // returned `Ptr` does not permit accessing the referent any
311 // longer than is possible via `self`. For shared aliasing, it is
312 // sound for multiple `Ptr`s to exist simultaneously which
313 // reference the same memory, so creating a new one is not
314 // problematic.
315 // - For `invariant::Exclusive`: Since `self` is `&'b mut` and we
316 // return a `Ptr` with lifetime `'b`, `self` is inaccessible to
317 // the caller for the lifetime `'b` - in other words, `self` is
318 // inaccessible to the caller as long as the returned `Ptr`
319 // exists. Since `self` is an exclusive `Ptr`, no other live
320 // references or `Ptr`s may exist which refer to the same memory
321 // while `self` is live. Thus, as long as the returned `Ptr`
322 // exists, no other references or `Ptr`s which refer to the same
323 // memory may be live.
324 unsafe { Ptr::from_inner(self.as_inner()) }
325 }
326 }
327
328 /// `Ptr<'a, T>` → `&'a mut T`
329 impl<'a, T> Ptr<'a, T, (Exclusive, Aligned, Valid)>
330 where
331 T: 'a + ?Sized,
332 {
333 /// Converts `self` to a mutable reference.
334 #[allow(clippy::wrong_self_convention)]
335 pub(crate) fn as_mut(self) -> &'a mut T {
336 let mut raw = self.as_inner().as_non_null();
337 // SAFETY: `self` satisfies the `Aligned` invariant, so we know that
338 // `raw` is validly-aligned for `T`.
339 #[cfg(miri)]
340 unsafe {
341 crate::util::miri_promise_symbolic_alignment(
342 raw.as_ptr().cast(),
343 core::mem::align_of_val_raw(raw.as_ptr()),
344 );
345 }
346 // SAFETY: This invocation of `NonNull::as_mut` satisfies its
347 // documented safety preconditions:
348 //
349 // 1. The pointer is properly aligned. This is ensured by-contract
350 // on `Ptr`, because the `ALIGNMENT_INVARIANT` is `Aligned`.
351 //
352 // 2. If the pointer's referent is not zero-sized, then the pointer
353 // must be “dereferenceable” in the sense defined in the module
354 // documentation; i.e.:
355 //
356 // > The memory range of the given size starting at the pointer
357 // > must all be within the bounds of a single allocated object.
358 // > [2]
359 //
360 // This is ensured by contract on all `PtrInner`s.
361 //
362 // 3. The pointer must point to a validly-initialized instance of
363 // `T`. This is ensured by-contract on `Ptr`, because the
364 // validity invariant is `Valid`.
365 //
366 // 4. You must enforce Rust’s aliasing rules. This is ensured by
367 // contract on `Ptr`, because the `ALIASING_INVARIANT` is
368 // `Exclusive`.
369 //
370 // [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_mut
371 // [2]: https://doc.rust-lang.org/std/ptr/index.html#safety
372 unsafe { raw.as_mut() }
373 }
374 }
375
376 /// `Ptr<'a, T>` → `Ptr<'a, U>`
377 impl<'a, T: ?Sized, I> Ptr<'a, T, I>
378 where
379 I: Invariants,
380 {
381 pub(crate) fn transmute<U, V, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)>
382 where
383 V: Validity,
384 U: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, R> + SizeEq<T> + ?Sized,
385 {
386 // SAFETY:
387 // - By `SizeEq::CastFrom: Cast`, `SizeEq::CastFrom` preserves
388 // referent address, and so we don't need to consider projections
389 // in the following safety arguments.
390 // - If aliasing is `Shared`, then by `U: TransmuteFromPtr<T>`, at
391 // least one of the following holds:
392 // - `T: Immutable` and `U: Immutable`, in which case it is
393 // trivially sound for shared code to operate on a `&T` and `&U`
394 // at the same time, as neither can perform interior mutation
395 // - It is directly guaranteed that it is sound for shared code to
396 // operate on these references simultaneously
397 // - By `U: TransmuteFromPtr<T, I::Aliasing, I::Validity, V>`, it is
398 // sound to perform this transmute.
399 unsafe { self.project_transmute_unchecked::<_, _, <U as SizeEq<T>>::CastFrom>() }
400 }
401
402 #[doc(hidden)]
403 #[inline(always)]
404 #[must_use]
405 pub fn recall_validity<V, R>(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, V)>
406 where
407 V: Validity,
408 T: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, R>,
409 {
410 // SAFETY:
411 // - By `SizeEq::CastFrom: Cast`, `SizeEq::CastFrom` preserves
412 // referent address, and so we don't need to consider projections
413 // in the following safety arguments.
414 // - It is trivially sound to have multiple `&T` referencing the
415 // same referent simultaneously
416 // - By `T: TransmuteFromPtr<T, I::Aliasing, I::Validity, V>`, it is
417 // sound to perform this transmute.
418 let ptr =
419 unsafe { self.project_transmute_unchecked::<_, _, <T as SizeEq<T>>::CastFrom>() };
420 // SAFETY: `self` and `ptr` have the same address and referent type.
421 // Therefore, if `self` satisfies `I::Alignment`, then so does
422 // `ptr`.
423 unsafe { ptr.assume_alignment::<I::Alignment>() }
424 }
425
426 /// Projects and/or transmutes to a different (unsized) referent type
427 /// without checking interior mutability.
428 ///
429 /// Callers should prefer [`cast`] or [`project`] where possible.
430 ///
431 /// [`cast`]: Ptr::cast
432 /// [`project`]: Ptr::project
433 ///
434 /// # Safety
435 ///
436 /// The caller promises that:
437 /// - If `I::Aliasing` is [`Shared`], it must not be possible for safe
438 /// code, operating on a `&T` and `&U`, with the referents of `self`
439 /// and `self.project_transmute_unchecked()`, respectively, to cause
440 /// undefined behavior.
441 /// - It is sound to project and/or transmute a pointer of type `T` with
442 /// aliasing `I::Aliasing` and validity `I::Validity` to a pointer of
443 /// type `U` with aliasing `I::Aliasing` and validity `V`. This is a
444 /// subtle soundness requirement that is a function of `T`, `U`,
445 /// `I::Aliasing`, `I::Validity`, and `V`, and may depend upon the
446 /// presence, absence, or specific location of `UnsafeCell`s in `T`
447 /// and/or `U`. See [`Validity`] for more details.
448 #[doc(hidden)]
449 #[inline(always)]
450 #[must_use]
451 pub unsafe fn project_transmute_unchecked<U: ?Sized, V, P>(
452 self,
453 ) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)>
454 where
455 V: Validity,
456 P: crate::pointer::cast::Project<T, U>,
457 {
458 let ptr = self.as_inner().project::<_, P>();
459
460 // SAFETY:
461 //
462 // The following safety arguments rely on the fact that `P: Project`
463 // guarantees that `P` is a referent-preserving or -shrinking
464 // projection. Thus, `ptr` addresses a subset of the bytes of
465 // `*self`, and so certain properties that hold of `*self` also hold
466 // of `*ptr`.
467 //
468 // 0. `ptr` conforms to the aliasing invariant of `I::Aliasing`:
469 // - `Exclusive`: `self` is the only `Ptr` or reference which is
470 // permitted to read or modify the referent for the lifetime
471 // `'a`. Since we consume `self` by value, the returned pointer
472 // remains the only `Ptr` or reference which is permitted to
473 // read or modify the referent for the lifetime `'a`.
474 // - `Shared`: Since `self` has aliasing `Shared`, we know that
475 // no other code may mutate the referent during the lifetime
476 // `'a`, except via `UnsafeCell`s, and except as permitted by
477 // `T`'s library safety invariants. The caller promises that
478 // any safe operations which can be permitted on a `&T` and a
479 // `&U` simultaneously must be sound. Thus, no operations on a
480 // `&U` could violate `&T`'s library safety invariants, and
481 // vice-versa. Since any mutation via shared references outside
482 // of `UnsafeCell`s is unsound, this must be impossible using
483 // `&T` and `&U`.
484 // - `Inaccessible`: There are no restrictions we need to uphold.
485 // 1. `ptr` trivially satisfies the alignment invariant `Unaligned`.
486 // 2. The caller promises that the returned pointer satisfies the
487 // validity invariant `V` with respect to its referent type, `U`.
488 unsafe { Ptr::from_inner(ptr) }
489 }
490 }
491
492 /// `Ptr<'a, T, (_, _, _)>` → `Ptr<'a, Unalign<T>, (_, Aligned, _)>`
493 impl<'a, T, I> Ptr<'a, T, I>
494 where
495 I: Invariants,
496 {
497 /// Converts a `Ptr` an unaligned `T` into a `Ptr` to an aligned
498 /// `Unalign<T>`.
499 pub(crate) fn into_unalign(
500 self,
501 ) -> Ptr<'a, crate::Unalign<T>, (I::Aliasing, Aligned, I::Validity)> {
502 // SAFETY:
503 // - By `CastSized: Cast`, `CastSized` preserves referent address,
504 // and so we don't need to consider projections in the following
505 // safety arguments.
506 // - Since `Unalign<T>` has the same layout as `T`, the returned
507 // pointer refers to `UnsafeCell`s at the same locations as
508 // `self`.
509 // - `Unalign<T>` promises to have the same bit validity as `T`. By
510 // invariant on `Validity`, the set of bit patterns allowed in the
511 // referent of a `Ptr<X, (_, _, V)>` is only a function of the
512 // validity of `X` and of `V`. Thus, the set of bit patterns
513 // allowed in the referent of a `Ptr<T, (_, _, I::Validity)>` is
514 // the same as the set of bit patterns allowed in the referent of
515 // a `Ptr<Unalign<T>, (_, _, I::Validity)>`. As a result, `self`
516 // and the returned `Ptr` permit the same set of bit patterns in
517 // their referents, and so neither can be used to violate the
518 // validity of the other.
519 let ptr = unsafe { self.project_transmute_unchecked::<_, _, CastSized>() };
520 ptr.bikeshed_recall_aligned()
521 }
522 }
523
524 impl<'a, T, I> Ptr<'a, T, I>
525 where
526 T: ?Sized,
527 I: Invariants<Validity = Valid>,
528 I::Aliasing: Reference,
529 {
530 /// Reads the referent.
531 #[must_use]
532 #[inline]
533 pub fn read_unaligned<R>(self) -> T
534 where
535 T: Copy,
536 T: Read<I::Aliasing, R>,
537 {
538 (*self.into_unalign().as_ref()).into_inner()
539 }
540
541 /// Views the value as an aligned reference.
542 ///
543 /// This is only available if `T` is [`Unaligned`].
544 #[must_use]
545 #[inline]
546 pub fn unaligned_as_ref(self) -> &'a T
547 where
548 T: crate::Unaligned,
549 {
550 self.bikeshed_recall_aligned().as_ref()
551 }
552 }
553}
554
555/// State transitions between invariants.
556mod _transitions {
557 use super::*;
558 use crate::pointer::transmute::TryTransmuteFromPtr;
559
560 impl<'a, T, I> Ptr<'a, T, I>
561 where
562 T: 'a + ?Sized,
563 I: Invariants,
564 {
565 /// Returns a `Ptr` with [`Exclusive`] aliasing if `self` already has
566 /// `Exclusive` aliasing, or generates a compile-time assertion failure.
567 ///
568 /// This allows code which is generic over aliasing to down-cast to a
569 /// concrete aliasing.
570 ///
571 /// [`Exclusive`]: crate::pointer::invariant::Exclusive
572 #[inline]
573 pub(crate) fn into_exclusive_or_pme(
574 self,
575 ) -> Ptr<'a, T, (Exclusive, I::Alignment, I::Validity)> {
576 // NOTE(https://github.com/rust-lang/rust/issues/131625): We do this
577 // rather than just having `Aliasing::IS_EXCLUSIVE` have the panic
578 // behavior because doing it that way causes rustdoc to fail while
579 // attempting to document hidden items (since it evaluates the
580 // constant - and thus panics).
581 trait AliasingExt: Aliasing {
582 const IS_EXCL: bool;
583 }
584
585 impl<A: Aliasing> AliasingExt for A {
586 const IS_EXCL: bool = {
587 const_assert!(Self::IS_EXCLUSIVE);
588 true
589 };
590 }
591
592 assert!(I::Aliasing::IS_EXCL);
593
594 // SAFETY: We've confirmed that `self` already has the aliasing
595 // `Exclusive`. If it didn't, either the preceding assert would fail
596 // or evaluating `I::Aliasing::IS_EXCL` would fail. We're *pretty*
597 // sure that it's guaranteed to fail const eval, but the `assert!`
598 // provides a backstop in case that doesn't work.
599 unsafe { self.assume_exclusive() }
600 }
601
602 /// Assumes that `self` satisfies the invariants `H`.
603 ///
604 /// # Safety
605 ///
606 /// The caller promises that `self` satisfies the invariants `H`.
607 unsafe fn assume_invariants<H: Invariants>(self) -> Ptr<'a, T, H> {
608 // SAFETY: The caller has promised to satisfy all parameterized
609 // invariants of `Ptr`. `Ptr`'s other invariants are satisfied
610 // by-contract by the source `Ptr`.
611 unsafe { Ptr::from_inner(self.as_inner()) }
612 }
613
614 /// Helps the type system unify two distinct invariant types which are
615 /// actually the same.
616 pub(crate) fn unify_invariants<
617 H: Invariants<Aliasing = I::Aliasing, Alignment = I::Alignment, Validity = I::Validity>,
618 >(
619 self,
620 ) -> Ptr<'a, T, H> {
621 // SAFETY: The associated type bounds on `H` ensure that the
622 // invariants are unchanged.
623 unsafe { self.assume_invariants::<H>() }
624 }
625
626 /// Assumes that `self` satisfies the aliasing requirement of `A`.
627 ///
628 /// # Safety
629 ///
630 /// The caller promises that `self` satisfies the aliasing requirement
631 /// of `A`.
632 #[inline]
633 pub(crate) unsafe fn assume_aliasing<A: Aliasing>(
634 self,
635 ) -> Ptr<'a, T, (A, I::Alignment, I::Validity)> {
636 // SAFETY: The caller promises that `self` satisfies the aliasing
637 // requirements of `A`.
638 unsafe { self.assume_invariants() }
639 }
640
641 /// Assumes `self` satisfies the aliasing requirement of [`Exclusive`].
642 ///
643 /// # Safety
644 ///
645 /// The caller promises that `self` satisfies the aliasing requirement
646 /// of `Exclusive`.
647 ///
648 /// [`Exclusive`]: crate::pointer::invariant::Exclusive
649 #[inline]
650 pub(crate) unsafe fn assume_exclusive(
651 self,
652 ) -> Ptr<'a, T, (Exclusive, I::Alignment, I::Validity)> {
653 // SAFETY: The caller promises that `self` satisfies the aliasing
654 // requirements of `Exclusive`.
655 unsafe { self.assume_aliasing::<Exclusive>() }
656 }
657
658 /// Assumes that `self`'s referent is validly-aligned for `T` if
659 /// required by `A`.
660 ///
661 /// # Safety
662 ///
663 /// The caller promises that `self`'s referent conforms to the alignment
664 /// invariant of `T` if required by `A`.
665 #[inline]
666 pub(crate) unsafe fn assume_alignment<A: Alignment>(
667 self,
668 ) -> Ptr<'a, T, (I::Aliasing, A, I::Validity)> {
669 // SAFETY: The caller promises that `self`'s referent is
670 // well-aligned for `T` if required by `A` .
671 unsafe { self.assume_invariants() }
672 }
673
674 /// Checks the `self`'s alignment at runtime, returning an aligned `Ptr`
675 /// on success.
676 pub(crate) fn try_into_aligned(
677 self,
678 ) -> Result<Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)>, AlignmentError<Self, T>>
679 where
680 T: Sized,
681 {
682 if let Err(err) =
683 crate::util::validate_aligned_to::<_, T>(self.as_inner().as_non_null())
684 {
685 return Err(err.with_src(self));
686 }
687
688 // SAFETY: We just checked the alignment.
689 Ok(unsafe { self.assume_alignment::<Aligned>() })
690 }
691
692 /// Recalls that `self`'s referent is validly-aligned for `T`.
693 #[inline]
694 // FIXME(#859): Reconsider the name of this method before making it
695 // public.
696 pub(crate) fn bikeshed_recall_aligned(
697 self,
698 ) -> Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)>
699 where
700 T: crate::Unaligned,
701 {
702 // SAFETY: The bound `T: Unaligned` ensures that `T` has no
703 // non-trivial alignment requirement.
704 unsafe { self.assume_alignment::<Aligned>() }
705 }
706
707 /// Assumes that `self`'s referent conforms to the validity requirement
708 /// of `V`.
709 ///
710 /// # Safety
711 ///
712 /// The caller promises that `self`'s referent conforms to the validity
713 /// requirement of `V`.
714 #[doc(hidden)]
715 #[must_use]
716 #[inline]
717 pub unsafe fn assume_validity<V: Validity>(
718 self,
719 ) -> Ptr<'a, T, (I::Aliasing, I::Alignment, V)> {
720 // SAFETY: The caller promises that `self`'s referent conforms to
721 // the validity requirement of `V`.
722 unsafe { self.assume_invariants() }
723 }
724
725 /// A shorthand for `self.assume_validity<invariant::Initialized>()`.
726 ///
727 /// # Safety
728 ///
729 /// The caller promises to uphold the safety preconditions of
730 /// `self.assume_validity<invariant::Initialized>()`.
731 #[doc(hidden)]
732 #[must_use]
733 #[inline]
734 pub unsafe fn assume_initialized(
735 self,
736 ) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Initialized)> {
737 // SAFETY: The caller has promised to uphold the safety
738 // preconditions.
739 unsafe { self.assume_validity::<Initialized>() }
740 }
741
742 /// A shorthand for `self.assume_validity<Valid>()`.
743 ///
744 /// # Safety
745 ///
746 /// The caller promises to uphold the safety preconditions of
747 /// `self.assume_validity<Valid>()`.
748 #[doc(hidden)]
749 #[must_use]
750 #[inline]
751 pub unsafe fn assume_valid(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)> {
752 // SAFETY: The caller has promised to uphold the safety
753 // preconditions.
754 unsafe { self.assume_validity::<Valid>() }
755 }
756
757 /// Recalls that `self`'s referent is initialized.
758 #[doc(hidden)]
759 #[must_use]
760 #[inline]
761 // FIXME(#859): Reconsider the name of this method before making it
762 // public.
763 pub fn bikeshed_recall_initialized_from_bytes(
764 self,
765 ) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Initialized)>
766 where
767 T: crate::IntoBytes + crate::FromBytes,
768 I: Invariants<Validity = Valid>,
769 {
770 // SAFETY: The `T: IntoBytes + FromBytes` bound ensures that `T`'s
771 // bit validity is equivalent to `[u8]`. In other words, the set of
772 // allowed referents for a `Ptr<T, (_, _, Valid)>` is the set of
773 // initialized bit patterns. The same is true of the set of allowed
774 // referents for any `Ptr<_, (_, _, Initialized)>`. Thus, this call
775 // does not change the set of allowed values in the referent.
776 unsafe { self.assume_initialized() }
777 }
778
779 /// Recalls that `self`'s referent is initialized.
780 #[doc(hidden)]
781 #[must_use]
782 #[inline]
783 // FIXME(#859): Reconsider the name of this method before making it
784 // public.
785 pub fn bikeshed_recall_initialized_immutable(
786 self,
787 ) -> Ptr<'a, T, (Shared, I::Alignment, Initialized)>
788 where
789 T: crate::IntoBytes + crate::Immutable,
790 I: Invariants<Aliasing = Shared, Validity = Valid>,
791 {
792 // SAFETY: Let `O` (for "old") be the set of allowed bit patterns in
793 // `self`'s referent, and let `N` (for "new") be the set of allowed
794 // bit patterns in the referent of the returned `Ptr`. `T:
795 // IntoBytes` and `I: Invariants<Validity = Valid>` ensures that `O`
796 // cannot contain any uninitialized bit patterns. Since the returned
797 // `Ptr` has validity `Initialized`, `N` is equal to the set of all
798 // initialized bit patterns. Thus, `O` is a subset of `N`, and so
799 // the returned `Ptr`'s validity invariant is upheld.
800 //
801 // Since `T: Immutable` and aliasing is `Shared`, the returned `Ptr`
802 // cannot be used to modify the referent. Before this call, `self`'s
803 // referent is guaranteed by invariant on `Ptr` to satisfy `self`'s
804 // validity invariant. Since the returned `Ptr` cannot be used to
805 // modify the referent, this guarantee cannot be violated by the
806 // returned `Ptr` (even if `O` is a strict subset of `N`).
807 unsafe { self.assume_initialized() }
808 }
809
810 /// Checks that `self`'s referent is validly initialized for `T`,
811 /// returning a `Ptr` with `Valid` on success.
812 ///
813 /// # Panics
814 ///
815 /// This method will panic if
816 /// [`T::is_bit_valid`][TryFromBytes::is_bit_valid] panics.
817 ///
818 /// # Safety
819 ///
820 /// On error, unsafe code may rely on this method's returned
821 /// `ValidityError` containing `self`.
822 #[inline]
823 pub(crate) fn try_into_valid<R, S>(
824 mut self,
825 ) -> Result<Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)>, ValidityError<Self, T>>
826 where
827 T: TryFromBytes
828 + Read<I::Aliasing, R>
829 + TryTransmuteFromPtr<T, I::Aliasing, I::Validity, Valid, S>,
830 I::Aliasing: Reference,
831 I: Invariants<Validity = Initialized>,
832 {
833 // This call may panic. If that happens, it doesn't cause any
834 // soundness issues, as we have not generated any invalid state
835 // which we need to fix before returning.
836 if T::is_bit_valid(self.reborrow().forget_aligned()) {
837 // SAFETY: If `T::is_bit_valid`, code may assume that `self`
838 // contains a bit-valid instance of `T`. By `T:
839 // TryTransmuteFromPtr<T, I::Aliasing, I::Validity, Valid>`, so
840 // long as `self`'s referent conforms to the `Valid` validity
841 // for `T` (which we just confirmed), then this transmute is
842 // sound.
843 Ok(unsafe { self.assume_valid() })
844 } else {
845 Err(ValidityError::new(self))
846 }
847 }
848
849 /// Forgets that `self`'s referent is validly-aligned for `T`.
850 #[doc(hidden)]
851 #[must_use]
852 #[inline]
853 pub fn forget_aligned(self) -> Ptr<'a, T, (I::Aliasing, Unaligned, I::Validity)> {
854 // SAFETY: `Unaligned` is less restrictive than `Aligned`.
855 unsafe { self.assume_invariants() }
856 }
857 }
858}
859
860/// Casts of the referent type.
861mod _casts {
862 use core::cell::UnsafeCell;
863
864 use super::*;
865 use crate::{
866 pointer::cast::{AsBytesCast, Cast},
867 HasField,
868 };
869
870 impl<'a, T, I> Ptr<'a, T, I>
871 where
872 T: 'a + ?Sized,
873 I: Invariants,
874 {
875 /// Casts to a different referent type without checking interior
876 /// mutability.
877 ///
878 /// Callers should prefer [`cast`][Ptr::cast] where possible.
879 ///
880 /// # Safety
881 ///
882 /// If `I::Aliasing` is [`Shared`], it must not be possible for safe
883 /// code, operating on a `&T` and `&U` with the same referent
884 /// simultaneously, to cause undefined behavior.
885 #[doc(hidden)]
886 #[inline(always)]
887 #[must_use]
888 pub unsafe fn cast_unchecked<U, C: Cast<T, U>>(
889 self,
890 ) -> Ptr<'a, U, (I::Aliasing, Unaligned, I::Validity)>
891 where
892 U: 'a + CastableFrom<T, I::Validity, I::Validity> + ?Sized,
893 {
894 // SAFETY:
895 // - By `C: Cast`, `C` preserves the address of the referent.
896 // - If `I::Aliasing` is [`Shared`], the caller promises that it
897 // is not possible for safe code, operating on a `&T` and `&U`
898 // with the same referent simultaneously, to cause undefined
899 // behavior.
900 // - By `U: CastableFrom<T, I::Validity, I::Validity>`,
901 // `I::Validity` is either `Uninit` or `Initialized`. In both
902 // cases, the bit validity `I::Validity` has the same semantics
903 // regardless of referent type. In other words, the set of allowed
904 // referent values for `Ptr<T, (_, _, I::Validity)>` and `Ptr<U,
905 // (_, _, I::Validity)>` are identical. As a consequence, neither
906 // `self` nor the returned `Ptr` can be used to write values which
907 // are invalid for the other.
908 unsafe { self.project_transmute_unchecked::<_, _, C>() }
909 }
910
911 /// Casts to a different referent type.
912 #[doc(hidden)]
913 #[inline(always)]
914 #[must_use]
915 pub fn cast<U, C, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, I::Validity)>
916 where
917 T: MutationCompatible<U, I::Aliasing, I::Validity, I::Validity, R>,
918 U: 'a + ?Sized + CastableFrom<T, I::Validity, I::Validity>,
919 C: Cast<T, U>,
920 {
921 // SAFETY: Because `T: MutationCompatible<U, I::Aliasing, R>`, one
922 // of the following holds:
923 // - `T: Read<I::Aliasing>` and `U: Read<I::Aliasing>`, in which
924 // case one of the following holds:
925 // - `I::Aliasing` is `Exclusive`
926 // - `T` and `U` are both `Immutable`
927 // - It is sound for safe code to operate on `&T` and `&U` with the
928 // same referent simultaneously.
929 unsafe { self.cast_unchecked::<_, C>() }
930 }
931
932 // FIXME(#196): Support all validity invariants (not just those that are
933 // `CastableFrom`).
934 #[must_use]
935 #[inline(always)]
936 pub fn project<F, const FIELD_ID: i128>(
937 self,
938 ) -> Ptr<'a, T::Type, (I::Aliasing, Unaligned, I::Validity)>
939 where
940 T: HasField<F, { crate::STRUCT_VARIANT_ID }, FIELD_ID>,
941 T::Type: 'a + CastableFrom<T, I::Validity, I::Validity>,
942 {
943 let ptr = self.as_inner().project::<_, crate::pointer::cast::Projection<
944 F,
945 { crate::STRUCT_VARIANT_ID },
946 FIELD_ID,
947 >>();
948
949 // SAFETY:
950 // 0. `PtrInner::project` promises that it produces a pointer which
951 // references a subset of its argument's referent. Since, by
952 // invariant on `Ptr`, its argument (`self.as_inner()`) satisfies
953 // the aliasing invariant `I::Aliasing`, so does `ptr`.
954 // 1. The `Ptr` has alignment `Unaligned`, which is trivially
955 // satisfied.
956 // 2. By `CastableFrom<T, I::Validity, I::Validity>`, `I::Validity`
957 // is `Uninit` or `Initialized`. In either case, if `I::Validity`
958 // holds of `self`'s referent, then it holds any subset of its
959 // referent.
960 unsafe { Ptr::from_inner(ptr) }
961 }
962 }
963
964 impl<'a, T, I> Ptr<'a, T, I>
965 where
966 T: 'a + KnownLayout + ?Sized,
967 I: Invariants<Validity = Initialized>,
968 {
969 /// Casts this pointer-to-initialized into a pointer-to-bytes.
970 #[allow(clippy::wrong_self_convention)]
971 #[must_use]
972 #[inline]
973 pub fn as_bytes<R>(self) -> Ptr<'a, [u8], (I::Aliasing, Aligned, Valid)>
974 where
975 T: Read<I::Aliasing, R>,
976 I::Aliasing: Reference,
977 {
978 let ptr = self.cast::<_, AsBytesCast, _>();
979 ptr.bikeshed_recall_aligned().recall_validity::<Valid, (_, (_, _))>()
980 }
981 }
982
983 impl<'a, T, I, const N: usize> Ptr<'a, [T; N], I>
984 where
985 T: 'a,
986 I: Invariants,
987 {
988 /// Casts this pointer-to-array into a slice.
989 #[allow(clippy::wrong_self_convention)]
990 pub(crate) fn as_slice(self) -> Ptr<'a, [T], I> {
991 let slice = self.as_inner().as_slice();
992 // SAFETY: Note that, by post-condition on `PtrInner::as_slice`,
993 // `slice` refers to the same byte range as `self.as_inner()`.
994 //
995 // 0. Thus, `slice` conforms to the aliasing invariant of
996 // `I::Aliasing` because `self` does.
997 // 1. By the above lemma, `slice` conforms to the alignment
998 // invariant of `I::Alignment` because `self` does.
999 // 2. Since `[T; N]` and `[T]` have the same bit validity [1][2],
1000 // and since `self` and the returned `Ptr` have the same validity
1001 // invariant, neither `self` nor the returned `Ptr` can be used
1002 // to write a value to the referent which violates the other's
1003 // validity invariant.
1004 //
1005 // [1] Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#array-layout:
1006 //
1007 // An array of `[T; N]` has a size of `size_of::<T>() * N` and the
1008 // same alignment of `T`. Arrays are laid out so that the
1009 // zero-based `nth` element of the array is offset from the start
1010 // of the array by `n * size_of::<T>()` bytes.
1011 //
1012 // ...
1013 //
1014 // Slices have the same layout as the section of the array they
1015 // slice.
1016 //
1017 // [2] Per https://doc.rust-lang.org/1.81.0/reference/types/array.html#array-types:
1018 //
1019 // All elements of arrays are always initialized
1020 unsafe { Ptr::from_inner(slice) }
1021 }
1022 }
1023
1024 /// For caller convenience, these methods are generic over alignment
1025 /// invariant. In practice, the referent is always well-aligned, because the
1026 /// alignment of `[u8]` is 1.
1027 impl<'a, I> Ptr<'a, [u8], I>
1028 where
1029 I: Invariants<Validity = Valid>,
1030 {
1031 /// Attempts to cast `self` to a `U` using the given cast type.
1032 ///
1033 /// If `U` is a slice DST and pointer metadata (`meta`) is provided,
1034 /// then the cast will only succeed if it would produce an object with
1035 /// the given metadata.
1036 ///
1037 /// Returns `None` if the resulting `U` would be invalidly-aligned, if
1038 /// no `U` can fit in `self`, or if the provided pointer metadata
1039 /// describes an invalid instance of `U`. On success, returns a pointer
1040 /// to the largest-possible `U` which fits in `self`.
1041 ///
1042 /// # Safety
1043 ///
1044 /// The caller may assume that this implementation is correct, and may
1045 /// rely on that assumption for the soundness of their code. In
1046 /// particular, the caller may assume that, if `try_cast_into` returns
1047 /// `Some((ptr, remainder))`, then `ptr` and `remainder` refer to
1048 /// non-overlapping byte ranges within `self`, and that `ptr` and
1049 /// `remainder` entirely cover `self`. Finally:
1050 /// - If this is a prefix cast, `ptr` has the same address as `self`.
1051 /// - If this is a suffix cast, `remainder` has the same address as
1052 /// `self`.
1053 #[inline(always)]
1054 pub(crate) fn try_cast_into<U, R>(
1055 self,
1056 cast_type: CastType,
1057 meta: Option<U::PointerMetadata>,
1058 ) -> Result<
1059 (Ptr<'a, U, (I::Aliasing, Aligned, Initialized)>, Ptr<'a, [u8], I>),
1060 CastError<Self, U>,
1061 >
1062 where
1063 I::Aliasing: Reference,
1064 U: 'a + ?Sized + KnownLayout + Read<I::Aliasing, R>,
1065 {
1066 let (inner, remainder) =
1067 self.as_inner().try_cast_into(cast_type, meta).map_err(|err| {
1068 err.map_src(|inner|
1069 // SAFETY: `PtrInner::try_cast_into` promises to return its
1070 // original argument on error, which was originally produced
1071 // by `self.as_inner()`, which is guaranteed to satisfy
1072 // `Ptr`'s invariants.
1073 unsafe { Ptr::from_inner(inner) })
1074 })?;
1075
1076 // SAFETY:
1077 // 0. Since `U: Read<I::Aliasing, _>`, either:
1078 // - `I::Aliasing` is `Exclusive`, in which case both `src` and
1079 // `ptr` conform to `Exclusive`
1080 // - `I::Aliasing` is `Shared` and `U` is `Immutable` (we already
1081 // know that `[u8]: Immutable`). In this case, neither `U` nor
1082 // `[u8]` permit mutation, and so `Shared` aliasing is
1083 // satisfied.
1084 // 1. `ptr` conforms to the alignment invariant of `Aligned` because
1085 // it is derived from `try_cast_into`, which promises that the
1086 // object described by `target` is validly aligned for `U`.
1087 // 2. By trait bound, `self` - and thus `target` - is a bit-valid
1088 // `[u8]`. `Ptr<[u8], (_, _, Valid)>` and `Ptr<_, (_, _,
1089 // Initialized)>` have the same bit validity, and so neither
1090 // `self` nor `res` can be used to write a value to the referent
1091 // which violates the other's validity invariant.
1092 let res = unsafe { Ptr::from_inner(inner) };
1093
1094 // SAFETY:
1095 // 0. `self` and `remainder` both have the type `[u8]`. Thus, they
1096 // have `UnsafeCell`s at the same locations. Type casting does
1097 // not affect aliasing.
1098 // 1. `[u8]` has no alignment requirement.
1099 // 2. `self` has validity `Valid` and has type `[u8]`. Since
1100 // `remainder` references a subset of `self`'s referent, it is
1101 // also a bit-valid `[u8]`. Thus, neither `self` nor `remainder`
1102 // can be used to write a value to the referent which violates
1103 // the other's validity invariant.
1104 let remainder = unsafe { Ptr::from_inner(remainder) };
1105
1106 Ok((res, remainder))
1107 }
1108
1109 /// Attempts to cast `self` into a `U`, failing if all of the bytes of
1110 /// `self` cannot be treated as a `U`.
1111 ///
1112 /// In particular, this method fails if `self` is not validly-aligned
1113 /// for `U` or if `self`'s size is not a valid size for `U`.
1114 ///
1115 /// # Safety
1116 ///
1117 /// On success, the caller may assume that the returned pointer
1118 /// references the same byte range as `self`.
1119 #[allow(unused)]
1120 #[inline(always)]
1121 pub(crate) fn try_cast_into_no_leftover<U, R>(
1122 self,
1123 meta: Option<U::PointerMetadata>,
1124 ) -> Result<Ptr<'a, U, (I::Aliasing, Aligned, Initialized)>, CastError<Self, U>>
1125 where
1126 I::Aliasing: Reference,
1127 U: 'a + ?Sized + KnownLayout + Read<I::Aliasing, R>,
1128 {
1129 // FIXME(#67): Remove this allow. See NonNulSlicelExt for more
1130 // details.
1131 #[allow(unstable_name_collisions)]
1132 match self.try_cast_into(CastType::Prefix, meta) {
1133 Ok((slf, remainder)) => {
1134 if remainder.len() == 0 {
1135 Ok(slf)
1136 } else {
1137 // Undo the cast so we can return the original bytes.
1138 let slf = slf.as_bytes();
1139 // Restore the initial alignment invariant of `self`.
1140 //
1141 // SAFETY: The referent type of `slf` is now equal to
1142 // that of `self`, but the alignment invariants
1143 // nominally differ. Since `slf` and `self` refer to the
1144 // same memory and no actions have been taken that would
1145 // violate the original invariants on `self`, it is
1146 // sound to apply the alignment invariant of `self` onto
1147 // `slf`.
1148 let slf = unsafe { slf.assume_alignment::<I::Alignment>() };
1149 let slf = slf.unify_invariants();
1150 Err(CastError::Size(SizeError::<_, U>::new(slf)))
1151 }
1152 }
1153 Err(err) => Err(err),
1154 }
1155 }
1156 }
1157
1158 impl<'a, T, I> Ptr<'a, UnsafeCell<T>, I>
1159 where
1160 T: 'a + ?Sized,
1161 I: Invariants<Aliasing = Exclusive>,
1162 {
1163 /// Converts this `Ptr` into a pointer to the underlying data.
1164 ///
1165 /// This call borrows the `UnsafeCell` mutably (at compile-time) which
1166 /// guarantees that we possess the only reference.
1167 ///
1168 /// This is like [`UnsafeCell::get_mut`], but for `Ptr`.
1169 ///
1170 /// [`UnsafeCell::get_mut`]: core::cell::UnsafeCell::get_mut
1171 #[must_use]
1172 #[inline(always)]
1173 pub fn get_mut(self) -> Ptr<'a, T, I> {
1174 // SAFETY: As described below, `UnsafeCell<T>` has the same size
1175 // as `T: ?Sized` (same static size or same DST layout). Thus,
1176 // `*const UnsafeCell<T> as *const T` is a size-preserving cast.
1177 define_cast!(unsafe { Cast<T: ?Sized> = UnsafeCell<T> => T });
1178
1179 // SAFETY:
1180 // - Aliasing is `Exclusive`, and so we are not required to promise
1181 // anything about the locations of `UnsafeCell`s.
1182 // - `UnsafeCell<T>` has the same bit validity as `T` [1].
1183 // Technically the term "representation" doesn't guarantee this,
1184 // but the subsequent sentence in the documentation makes it clear
1185 // that this is the intention.
1186 //
1187 // By invariant on `Validity`, since `T` and `UnsafeCell<T>` have
1188 // the same bit validity, then the set of values which may appear
1189 // in the referent of a `Ptr<T, (_, _, V)>` is the same as the set
1190 // which may appear in the referent of a `Ptr<UnsafeCell<T>, (_,
1191 // _, V)>`. Thus, neither `self` nor `ptr` may be used to write a
1192 // value to the referent which would violate the other's validity
1193 // invariant.
1194 //
1195 // [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.UnsafeCell.html#memory-layout:
1196 //
1197 // `UnsafeCell<T>` has the same in-memory representation as its
1198 // inner type `T`. A consequence of this guarantee is that it is
1199 // possible to convert between `T` and `UnsafeCell<T>`.
1200 let ptr = unsafe { self.project_transmute_unchecked::<_, _, Cast>() };
1201
1202 // SAFETY: `UnsafeCell<T>` has the same alignment as `T` [1],
1203 // and so if `self` is guaranteed to be aligned, then so is the
1204 // returned `Ptr`.
1205 //
1206 // [1] Per https://doc.rust-lang.org/1.81.0/core/cell/struct.UnsafeCell.html#memory-layout:
1207 //
1208 // `UnsafeCell<T>` has the same in-memory representation as
1209 // its inner type `T`. A consequence of this guarantee is that
1210 // it is possible to convert between `T` and `UnsafeCell<T>`.
1211 let ptr = unsafe { ptr.assume_alignment::<I::Alignment>() };
1212 ptr.unify_invariants()
1213 }
1214 }
1215}
1216
1217/// Projections through the referent.
1218mod _project {
1219 use super::*;
1220
1221 impl<'a, T, I> Ptr<'a, [T], I>
1222 where
1223 T: 'a,
1224 I: Invariants,
1225 I::Aliasing: Reference,
1226 {
1227 /// Iteratively projects the elements `Ptr<T>` from `Ptr<[T]>`.
1228 pub(crate) fn iter(&self) -> impl Iterator<Item = Ptr<'a, T, I>> {
1229 // SAFETY:
1230 // 0. `elem` conforms to the aliasing invariant of `I::Aliasing`
1231 // because projection does not impact the aliasing invariant.
1232 // 1. `elem`, conditionally, conforms to the validity invariant of
1233 // `I::Alignment`. If `elem` is projected from data well-aligned
1234 // for `[T]`, `elem` will be valid for `T`.
1235 // 2. `elem` conforms to the validity invariant of `I::Validity`.
1236 // Per https://doc.rust-lang.org/1.81.0/reference/type-layout.html#array-layout:
1237 //
1238 // Slices have the same layout as the section of the array they
1239 // slice.
1240 //
1241 // Arrays are laid out so that the zero-based `nth` element of
1242 // the array is offset from the start of the array by `n *
1243 // size_of::<T>()` bytes. Thus, `elem` addresses a valid `T`
1244 // within the slice. Since `self` satisfies `I::Validity`, `elem`
1245 // also satisfies `I::Validity`.
1246 self.as_inner().iter().map(|elem| unsafe { Ptr::from_inner(elem) })
1247 }
1248 }
1249
1250 #[allow(clippy::needless_lifetimes)]
1251 impl<'a, T, I> Ptr<'a, T, I>
1252 where
1253 T: 'a + ?Sized + KnownLayout<PointerMetadata = usize>,
1254 I: Invariants,
1255 {
1256 /// The number of slice elements in the object referenced by `self`.
1257 pub(crate) fn len(&self) -> usize {
1258 self.as_inner().meta().get()
1259 }
1260 }
1261}
1262
1263#[cfg(test)]
1264mod tests {
1265 use core::mem::{self, MaybeUninit};
1266
1267 use super::*;
1268 #[allow(unused)] // Needed on our MSRV, but considered unused on later toolchains.
1269 use crate::util::AsAddress;
1270 use crate::{pointer::BecauseImmutable, util::testutil::AU64, FromBytes, Immutable};
1271
1272 mod test_ptr_try_cast_into_soundness {
1273 use super::*;
1274
1275 // This test is designed so that if `Ptr::try_cast_into_xxx` are
1276 // buggy, it will manifest as unsoundness that Miri can detect.
1277
1278 // - If `size_of::<T>() == 0`, `N == 4`
1279 // - Else, `N == 4 * size_of::<T>()`
1280 //
1281 // Each test will be run for each metadata in `metas`.
1282 fn test<T, I, const N: usize>(metas: I)
1283 where
1284 T: ?Sized + KnownLayout + Immutable + FromBytes,
1285 I: IntoIterator<Item = Option<T::PointerMetadata>> + Clone,
1286 {
1287 let mut bytes = [MaybeUninit::<u8>::uninit(); N];
1288 let initialized = [MaybeUninit::new(0u8); N];
1289 for start in 0..=bytes.len() {
1290 for end in start..=bytes.len() {
1291 // Set all bytes to uninitialized other than those in
1292 // the range we're going to pass to `try_cast_from`.
1293 // This allows Miri to detect out-of-bounds reads
1294 // because they read uninitialized memory. Without this,
1295 // some out-of-bounds reads would still be in-bounds of
1296 // `bytes`, and so might spuriously be accepted.
1297 bytes = [MaybeUninit::<u8>::uninit(); N];
1298 let bytes = &mut bytes[start..end];
1299 // Initialize only the byte range we're going to pass to
1300 // `try_cast_from`.
1301 bytes.copy_from_slice(&initialized[start..end]);
1302
1303 let bytes = {
1304 let bytes: *const [MaybeUninit<u8>] = bytes;
1305 #[allow(clippy::as_conversions)]
1306 let bytes = bytes as *const [u8];
1307 // SAFETY: We just initialized these bytes to valid
1308 // `u8`s.
1309 unsafe { &*bytes }
1310 };
1311
1312 // SAFETY: The bytes in `slf` must be initialized.
1313 unsafe fn validate_and_get_len<
1314 T: ?Sized + KnownLayout + FromBytes + Immutable,
1315 >(
1316 slf: Ptr<'_, T, (Shared, Aligned, Initialized)>,
1317 ) -> usize {
1318 let t = slf.recall_validity().as_ref();
1319
1320 let bytes = {
1321 let len = mem::size_of_val(t);
1322 let t: *const T = t;
1323 // SAFETY:
1324 // - We know `t`'s bytes are all initialized
1325 // because we just read it from `slf`, which
1326 // points to an initialized range of bytes. If
1327 // there's a bug and this doesn't hold, then
1328 // that's exactly what we're hoping Miri will
1329 // catch!
1330 // - Since `T: FromBytes`, `T` doesn't contain
1331 // any `UnsafeCell`s, so it's okay for `t: T`
1332 // and a `&[u8]` to the same memory to be
1333 // alive concurrently.
1334 unsafe { core::slice::from_raw_parts(t.cast::<u8>(), len) }
1335 };
1336
1337 // This assertion ensures that `t`'s bytes are read
1338 // and compared to another value, which in turn
1339 // ensures that Miri gets a chance to notice if any
1340 // of `t`'s bytes are uninitialized, which they
1341 // shouldn't be (see the comment above).
1342 assert_eq!(bytes, vec![0u8; bytes.len()]);
1343
1344 mem::size_of_val(t)
1345 }
1346
1347 for meta in metas.clone().into_iter() {
1348 for cast_type in [CastType::Prefix, CastType::Suffix] {
1349 if let Ok((slf, remaining)) = Ptr::from_ref(bytes)
1350 .try_cast_into::<T, BecauseImmutable>(cast_type, meta)
1351 {
1352 // SAFETY: All bytes in `bytes` have been
1353 // initialized.
1354 let len = unsafe { validate_and_get_len(slf) };
1355 assert_eq!(remaining.len(), bytes.len() - len);
1356 #[allow(unstable_name_collisions)]
1357 let bytes_addr = bytes.as_ptr().addr();
1358 #[allow(unstable_name_collisions)]
1359 let remaining_addr = remaining.as_inner().as_ptr().addr();
1360 match cast_type {
1361 CastType::Prefix => {
1362 assert_eq!(remaining_addr, bytes_addr + len)
1363 }
1364 CastType::Suffix => assert_eq!(remaining_addr, bytes_addr),
1365 }
1366
1367 if let Some(want) = meta {
1368 let got =
1369 KnownLayout::pointer_to_metadata(slf.as_inner().as_ptr());
1370 assert_eq!(got, want);
1371 }
1372 }
1373 }
1374
1375 if let Ok(slf) = Ptr::from_ref(bytes)
1376 .try_cast_into_no_leftover::<T, BecauseImmutable>(meta)
1377 {
1378 // SAFETY: All bytes in `bytes` have been
1379 // initialized.
1380 let len = unsafe { validate_and_get_len(slf) };
1381 assert_eq!(len, bytes.len());
1382
1383 if let Some(want) = meta {
1384 let got = KnownLayout::pointer_to_metadata(slf.as_inner().as_ptr());
1385 assert_eq!(got, want);
1386 }
1387 }
1388 }
1389 }
1390 }
1391 }
1392
1393 #[derive(FromBytes, KnownLayout, Immutable)]
1394 #[repr(C)]
1395 struct SliceDst<T> {
1396 a: u8,
1397 trailing: [T],
1398 }
1399
1400 // Each test case becomes its own `#[test]` function. We do this because
1401 // this test in particular takes far, far longer to execute under Miri
1402 // than all of our other tests combined. Previously, we had these
1403 // execute sequentially in a single test function. We run Miri tests in
1404 // parallel in CI, but this test being sequential meant that most of
1405 // that parallelism was wasted, as all other tests would finish in a
1406 // fraction of the total execution time, leaving this test to execute on
1407 // a single thread for the remainder of the test. By putting each test
1408 // case in its own function, we permit better use of available
1409 // parallelism.
1410 macro_rules! test {
1411 ($test_name:ident: $ty:ty) => {
1412 #[test]
1413 #[allow(non_snake_case)]
1414 fn $test_name() {
1415 const S: usize = core::mem::size_of::<$ty>();
1416 const N: usize = if S == 0 { 4 } else { S * 4 };
1417 test::<$ty, _, N>([None]);
1418
1419 // If `$ty` is a ZST, then we can't pass `None` as the
1420 // pointer metadata, or else computing the correct trailing
1421 // slice length will panic.
1422 if S == 0 {
1423 test::<[$ty], _, N>([Some(0), Some(1), Some(2), Some(3)]);
1424 test::<SliceDst<$ty>, _, N>([Some(0), Some(1), Some(2), Some(3)]);
1425 } else {
1426 test::<[$ty], _, N>([None, Some(0), Some(1), Some(2), Some(3)]);
1427 test::<SliceDst<$ty>, _, N>([None, Some(0), Some(1), Some(2), Some(3)]);
1428 }
1429 }
1430 };
1431 ($ty:ident) => {
1432 test!($ty: $ty);
1433 };
1434 ($($ty:ident),*) => { $(test!($ty);)* }
1435 }
1436
1437 test!(empty_tuple: ());
1438 test!(u8, u16, u32, u64, u128, usize, AU64);
1439 test!(i8, i16, i32, i64, i128, isize);
1440 test!(f32, f64);
1441 }
1442
1443 #[test]
1444 fn test_try_cast_into_explicit_count() {
1445 macro_rules! test {
1446 ($ty:ty, $bytes:expr, $elems:expr, $expect:expr) => {{
1447 let bytes = [0u8; $bytes];
1448 let ptr = Ptr::from_ref(&bytes[..]);
1449 let res =
1450 ptr.try_cast_into::<$ty, BecauseImmutable>(CastType::Prefix, Some($elems));
1451 if let Some(expect) = $expect {
1452 let (ptr, _) = res.unwrap();
1453 assert_eq!(KnownLayout::pointer_to_metadata(ptr.as_inner().as_ptr()), expect);
1454 } else {
1455 let _ = res.unwrap_err();
1456 }
1457 }};
1458 }
1459
1460 #[derive(KnownLayout, Immutable)]
1461 #[repr(C)]
1462 struct ZstDst {
1463 u: [u8; 8],
1464 slc: [()],
1465 }
1466
1467 test!(ZstDst, 8, 0, Some(0));
1468 test!(ZstDst, 7, 0, None);
1469
1470 test!(ZstDst, 8, usize::MAX, Some(usize::MAX));
1471 test!(ZstDst, 7, usize::MAX, None);
1472
1473 #[derive(KnownLayout, Immutable)]
1474 #[repr(C)]
1475 struct Dst {
1476 u: [u8; 8],
1477 slc: [u8],
1478 }
1479
1480 test!(Dst, 8, 0, Some(0));
1481 test!(Dst, 7, 0, None);
1482
1483 test!(Dst, 9, 1, Some(1));
1484 test!(Dst, 8, 1, None);
1485
1486 // If we didn't properly check for overflow, this would cause the
1487 // metadata to overflow to 0, and thus the cast would spuriously
1488 // succeed.
1489 test!(Dst, 8, usize::MAX - 8 + 1, None);
1490 }
1491}