-
Notifications
You must be signed in to change notification settings - Fork 105
/
ptr.rs
1760 lines (1624 loc) · 75.6 KB
/
ptr.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2023 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
use core::ptr::NonNull;
use crate::{util::AsAddress, CastType, KnownLayout};
/// Module used to gate access to [`Ptr`]'s fields.
mod def {
#[cfg(doc)]
use super::invariant;
use super::Invariants;
use core::{marker::PhantomData, ptr::NonNull};
/// A raw pointer with more restrictions.
///
/// `Ptr<T>` is similar to [`NonNull<T>`], but it is more restrictive in the
/// following ways:
/// - It must derive from a valid allocation.
/// - It must reference a byte range which is contained inside the
/// allocation from which it derives.
/// - As a consequence, the byte range it references must have a size
/// which does not overflow `isize`.
///
/// Depending on how `Ptr` is parameterized, it may have additional
/// invariants:
/// - `ptr` conforms to the aliasing invariant of
/// [`I::Aliasing`](invariant::Aliasing).
/// - `ptr` conforms to the alignment invariant of
/// [`I::Alignment`](invariant::Alignment).
/// - `ptr` conforms to the validity invariant of
/// [`I::Validity`](invariant::Validity).
///
/// `Ptr<'a, T>` is [covariant] in `'a` and `T`.
///
/// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
pub struct Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
/// # Invariants
///
/// 0. `ptr` is derived from some valid Rust allocation, `A`.
/// 1. `ptr` has valid provenance for `A`.
/// 2. `ptr` addresses a byte range which is entirely contained in `A`.
/// 3. `ptr` addresses a byte range whose length fits in an `isize`.
/// 4. `ptr` addresses a byte range which does not wrap around the
/// address space.
/// 5. `A` is guaranteed to live for at least `'a`.
/// 6. `T: 'a`.
/// 7. `ptr` conforms to the aliasing invariant of
/// [`I::Aliasing`](invariant::Aliasing).
/// 8. `ptr` conforms to the alignment invariant of
/// [`I::Alignment`](invariant::Alignment).
/// 9. `ptr` conforms to the validity invariant of
/// [`I::Validity`](invariant::Validity).
// SAFETY: `NonNull<T>` is covariant over `T` [1].
//
// [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html
ptr: NonNull<T>,
// SAFETY: `&'a ()` is covariant over `'a` [1].
//
// [1]: https://doc.rust-lang.org/reference/subtyping.html#variance
_invariants: PhantomData<&'a I>,
}
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
/// Constructs a `Ptr` from a [`NonNull`].
///
/// # Safety
///
/// The caller promises that:
///
/// 0. `ptr` is derived from some valid Rust allocation, `A`.
/// 1. `ptr` has valid provenance for `A`.
/// 2. `ptr` addresses a byte range which is entirely contained in `A`.
/// 3. `ptr` addresses a byte range whose length fits in an `isize`.
/// 4. `ptr` addresses a byte range which does not wrap around the
/// address space.
/// 5. `A` is guaranteed to live for at least `'a`.
/// 6. `ptr` conforms to the aliasing invariant of
/// [`I::Aliasing`](invariant::Aliasing).
/// 7. `ptr` conforms to the alignment invariant of
/// [`I::Alignment`](invariant::Alignment).
/// 8. `ptr` conforms to the validity invariant of
/// [`I::Validity`](invariant::Validity).
pub(super) unsafe fn new(ptr: NonNull<T>) -> Ptr<'a, T, I> {
// SAFETY: The caller has promised to satisfy all safety invariants
// of `Ptr`.
Self { ptr, _invariants: PhantomData }
}
/// Converts this `Ptr<T>` to a [`NonNull<T>`].
///
/// Note that this method does not consume `self`. The caller should
/// watch out for `unsafe` code which uses the returned `NonNull` in a
/// way that violates the safety invariants of `self`.
pub(crate) fn as_non_null(&self) -> NonNull<T> {
self.ptr
}
}
}
#[allow(unreachable_pub)] // This is a false positive on our MSRV toolchain.
pub use def::Ptr;
/// Used to define the system of [invariants][invariant] of `Ptr`.
macro_rules! define_system {
($(#[$system_attr:meta])* $system:ident {
$($(#[$set_attr:meta])* $set:ident {
$( $(#[$elem_attr:meta])* $elem:ident $(< $($stronger_elem:ident)|*)?,)*
})*
}) => {
/// No requirement - any invariant is allowed.
#[allow(missing_copy_implementations, missing_debug_implementations)]
pub enum Any {}
/// `Self` imposes a requirement at least as strict as `I`.
pub trait AtLeast<I> {}
mod sealed {
pub trait Sealed {}
impl<$($set,)*> Sealed for ($($set,)*)
where
$($set: super::$set,)*
{}
impl Sealed for super::Any {}
$($(
impl Sealed for super::$elem {}
)*)*
}
$(#[$system_attr])*
///
#[doc = concat!(
stringify!($system),
" are encoded as tuples of (",
)]
$(#[doc = concat!(
"[`",
stringify!($set),
"`],"
)])*
#[doc = concat!(
").",
)]
/// This trait is implemented for such tuples, and can be used to
/// project out the components of these tuples via its associated types.
pub trait $system: sealed::Sealed {
$(
$(#[$set_attr])*
type $set: $set;
)*
}
impl<$($set,)*> $system for ($($set,)*)
where
$($set: self::$set,)*
{
$(type $set = $set;)*
}
$(
$(#[$set_attr])*
pub trait $set: 'static + sealed::Sealed {
// This only exists for use in
// `into_exclusive_or_post_monomorphization_error`.
#[doc(hidden)]
const NAME: &'static str;
}
impl $set for Any {
const NAME: &'static str = stringify!(Any);
}
$(
$(#[$elem_attr])*
#[allow(missing_copy_implementations, missing_debug_implementations)]
pub enum $elem {}
$(#[$elem_attr])*
impl $set for $elem {
const NAME: &'static str = stringify!($elem);
}
)*
)*
$($(
impl AtLeast<Any> for $elem {}
impl AtLeast<$elem> for $elem {}
$($(impl AtLeast<$elem> for $stronger_elem {})*)?
)*)*
};
}
/// The parameterized invariants of a [`Ptr`].
///
/// Invariants are encoded as ([`Aliasing`], [`Alignment`], [`Validity`])
/// triples implementing the [`Invariants`] trait.
#[doc(hidden)]
pub mod invariant {
define_system! {
/// The invariants of a [`Ptr`][super::Ptr].
Invariants {
/// The aliasing invariant of a [`Ptr`][super::Ptr].
Aliasing {
/// The `Ptr<'a, T>` adheres to the aliasing rules of a `&'a T`.
///
/// The referent of a shared-aliased `Ptr` may be concurrently
/// referenced by any number of shared-aliased `Ptr` or `&T`
/// references, and may not be concurrently referenced by any
/// exclusively-aliased `Ptr`s or `&mut T` references. The
/// referent must not be mutated, except via [`UnsafeCell`]s.
///
/// [`UnsafeCell`]: core::cell::UnsafeCell
Shared < Exclusive,
/// The `Ptr<'a, T>` adheres to the aliasing rules of a `&'a mut
/// T`.
///
/// The referent of an exclusively-aliased `Ptr` may not be
/// concurrently referenced by any other `Ptr`s or references,
/// and may not be accessed (read or written) other than via
/// this `Ptr`.
Exclusive,
}
/// The alignment invariant of a [`Ptr`][super::Ptr].
Alignment {
/// The referent is aligned: for `Ptr<T>`, the referent's
/// address is a multiple of the `T`'s alignment.
Aligned,
}
/// The validity invariant of a [`Ptr`][super::Ptr].
Validity {
/// The byte ranges initialized in `T` are also initialized in
/// the referent.
///
/// Formally: uninitialized bytes may only be present in
/// `Ptr<T>`'s referent where they are guaranteed to be present
/// in `T`. This is a dynamic property: if, at a particular byte
/// offset, a valid enum discriminant is set, the subsequent
/// bytes may only have uninitialized bytes as specificed by the
/// corresponding enum.
///
/// Formally, given `len = size_of_val_raw(ptr)`, at every byte
/// offset, `b`, in the range `[0, len)`:
/// - If, in any instance `t: T` of length `len`, the byte at
/// offset `b` in `t` is initialized, then the byte at offset
/// `b` within `*ptr` must be initialized.
/// - Let `c` be the contents of the byte range `[0, b)` in
/// `*ptr`. Let `S` be the subset of valid instances of `T` of
/// length `len` which contain `c` in the offset range `[0,
/// b)`. If, in any instance of `t: T` in `S`, the byte at
/// offset `b` in `t` is initialized, then the byte at offset
/// `b` in `*ptr` must be initialized.
///
/// Pragmatically, this means that if `*ptr` is guaranteed to
/// contain an enum type at a particular offset, and the enum
/// discriminant stored in `*ptr` corresponds to a valid
/// variant of that enum type, then it is guaranteed that the
/// appropriate bytes of `*ptr` are initialized as defined by
/// that variant's bit validity (although note that the
/// variant may contain another enum type, in which case the
/// same rules apply depending on the state of its
/// discriminant, and so on recursively).
AsInitialized < Initialized | Valid,
/// The byte ranges in the referent are fully initialized. In
/// other words, if the referent is `N` bytes long, then it
/// contains a bit-valid `[u8; N]`.
Initialized,
/// The referent is bit-valid for `T`.
Valid,
}
}
}
}
pub(crate) use invariant::*;
/// External trait implementations on [`Ptr`].
mod _external {
use super::*;
use core::fmt::{Debug, Formatter};
/// SAFETY: Shared pointers are safely `Copy`. We do not implement `Copy`
/// for exclusive pointers, since at most one may exist at a time. `Ptr`'s
/// other invariants are unaffected by the number of references that exist
/// to `Ptr`'s referent.
impl<'a, T, I> Copy for Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
Shared: AtLeast<I::Aliasing>,
{
}
/// SAFETY: Shared pointers are safely `Clone`. We do not implement `Clone`
/// for exclusive pointers, since at most one may exist at a time. `Ptr`'s
/// other invariants are unaffected by the number of references that exist
/// to `Ptr`'s referent.
impl<'a, T, I> Clone for Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
Shared: AtLeast<I::Aliasing>,
{
#[inline]
fn clone(&self) -> Self {
*self
}
}
impl<'a, T, I> Debug for Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
self.as_non_null().fmt(f)
}
}
}
/// Methods for converting to and from `Ptr` and Rust's safe reference types.
mod _conversions {
use super::*;
use crate::util::{AlignmentVariance, Covariant, TransparentWrapper, ValidityVariance};
/// `&'a T` → `Ptr<'a, T>`
impl<'a, T> Ptr<'a, T, (Shared, Aligned, Valid)>
where
T: 'a + ?Sized,
{
/// Constructs a `Ptr` from a shared reference.
#[doc(hidden)]
#[inline]
pub fn from_ref(ptr: &'a T) -> Self {
let ptr = NonNull::from(ptr);
// SAFETY:
// 0. `ptr`, by invariant on `&'a T`, is derived from some valid
// Rust allocation, `A`.
// 1. `ptr`, by invariant on `&'a T`, has valid provenance for `A`.
// 2. `ptr`, by invariant on `&'a T`, addresses a byte range which
// is entirely contained in `A`.
// 3. `ptr`, by invariant on `&'a T`, addresses a byte range whose
// length fits in an `isize`.
// 4. `ptr`, by invariant on `&'a T`, addresses a byte range which
// does not wrap around the address space.
// 5. `A`, by invariant on `&'a T`, is guaranteed to live for at
// least `'a`.
// 6. `T: 'a`.
// 7. `ptr`, by invariant on `&'a T`, conforms to the aliasing
// invariant of `Shared`.
// 8. `ptr`, by invariant on `&'a T`, conforms to the alignment
// invariant of `Aligned`.
// 9. `ptr`, by invariant on `&'a T`, conforms to the validity
// invariant of `Valid`.
unsafe { Self::new(ptr) }
}
}
/// `&'a mut T` → `Ptr<'a, T>`
impl<'a, T> Ptr<'a, T, (Exclusive, Aligned, Valid)>
where
T: 'a + ?Sized,
{
/// Constructs a `Ptr` from an exclusive reference.
#[inline]
pub(crate) fn from_mut(ptr: &'a mut T) -> Self {
let ptr = NonNull::from(ptr);
// SAFETY:
// 0. `ptr`, by invariant on `&'a mut T`, is derived from some valid
// Rust allocation, `A`.
// 1. `ptr`, by invariant on `&'a mut T`, has valid provenance for
// `A`.
// 2. `ptr`, by invariant on `&'a mut T`, addresses a byte range
// which is entirely contained in `A`.
// 3. `ptr`, by invariant on `&'a mut T`, addresses a byte range
// whose length fits in an `isize`.
// 4. `ptr`, by invariant on `&'a mut T`, addresses a byte range
// which does not wrap around the address space.
// 5. `A`, by invariant on `&'a mut T`, is guaranteed to live for at
// least `'a`.
// 6. `ptr`, by invariant on `&'a mut T`, conforms to the aliasing
// invariant of `Exclusive`.
// 7. `ptr`, by invariant on `&'a mut T`, conforms to the alignment
// invariant of `Aligned`.
// 8. `ptr`, by invariant on `&'a mut T`, conforms to the validity
// invariant of `Valid`.
unsafe { Self::new(ptr) }
}
}
/// `Ptr<'a, T>` → `&'a T`
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants<Alignment = Aligned, Validity = Valid>,
I::Aliasing: AtLeast<Shared>,
{
/// Converts `self` to a shared reference.
// This consumes `self`, not `&self`, because `self` is, logically, a
// pointer. For `I::Aliasing = invariant::Shared`, `Self: Copy`, and so
// this doesn't prevent the caller from still using the pointer after
// calling `as_ref`.
#[allow(clippy::wrong_self_convention)]
pub(crate) fn as_ref(self) -> &'a T {
let raw = self.as_non_null();
// SAFETY: This invocation of `NonNull::as_ref` satisfies its
// documented safety preconditions:
//
// 1. The pointer is properly aligned. This is ensured by-contract
// on `Ptr`, because the `I::Alignment` is `Aligned`.
//
// 2. It must be “dereferenceable” in the sense defined in the
// module documentation; i.e.:
//
// > The memory range of the given size starting at the pointer
// > must all be within the bounds of a single allocated object.
// > [2]
//
// This is ensured by contract on all `Ptr`s.
//
// 3. The pointer must point to an initialized instance of `T`. This
// is ensured by-contract on `Ptr`, because the `I::Validity` is
// `Valid`.
//
// 4. You must enforce Rust’s aliasing rules. This is ensured by
// contract on `Ptr`, because the `I::Aliasing` is
// `AtLeast<Shared>`. Either it is `Shared` or `Exclusive`. If it
// is `Shared`, other references may not mutate the referent
// outside of `UnsafeCell`s.
//
// [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_ref
// [2]: https://doc.rust-lang.org/std/ptr/index.html#safety
unsafe { raw.as_ref() }
}
}
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
I::Aliasing: AtLeast<Shared>,
{
/// Reborrows `self`, producing another `Ptr`.
///
/// Since `self` is borrowed immutably, this prevents any mutable
/// methods from being called on `self` as long as the returned `Ptr`
/// exists.
#[doc(hidden)]
#[inline]
#[allow(clippy::needless_lifetimes)] // Allows us to name the lifetime in the safety comment below.
pub fn reborrow<'b>(&'b mut self) -> Ptr<'b, T, I>
where
'a: 'b,
{
// SAFETY: The following all hold by invariant on `self`, and thus
// hold of `ptr = self.as_non_null()`:
// 0. `ptr` is derived from some valid Rust allocation, `A`.
// 1. `ptr` has valid provenance for `A`.
// 2. `ptr` addresses a byte range which is entirely contained in
// `A`.
// 3. `ptr` addresses a byte range whose length fits in an `isize`.
// 4. `ptr` addresses a byte range which does not wrap around the
// address space.
// 5. `A` is guaranteed to live for at least `'a`.
// 6. SEE BELOW.
// 7. `ptr` conforms to the alignment invariant of
// [`I::Alignment`](invariant::Alignment).
// 8. `ptr` conforms to the validity invariant of
// [`I::Validity`](invariant::Validity).
//
// For aliasing (6 above), since `I::Aliasing: AtLeast<Shared>`,
// there are two cases for `I::Aliasing`:
// - For `invariant::Shared`: `'a` outlives `'b`, and so the
// returned `Ptr` does not permit accessing the referent any
// longer than is possible via `self`. For shared aliasing, it is
// sound for multiple `Ptr`s to exist simultaneously which
// reference the same memory, so creating a new one is not
// problematic.
// - For `invariant::Exclusive`: Since `self` is `&'b mut` and we
// return a `Ptr` with lifetime `'b`, `self` is inaccessible to
// the caller for the lifetime `'b` - in other words, `self` is
// inaccessible to the caller as long as the returned `Ptr`
// exists. Since `self` is an exclusive `Ptr`, no other live
// references or `Ptr`s may exist which refer to the same memory
// while `self` is live. Thus, as long as the returned `Ptr`
// exists, no other references or `Ptr`s which refer to the same
// memory may be live.
unsafe { Ptr::new(self.as_non_null()) }
}
}
/// `Ptr<'a, T>` → `&'a mut T`
impl<'a, T> Ptr<'a, T, (Exclusive, Aligned, Valid)>
where
T: 'a + ?Sized,
{
/// Converts `self` to a mutable reference.
#[allow(clippy::wrong_self_convention)]
pub(crate) fn as_mut(self) -> &'a mut T {
let mut raw = self.as_non_null();
// SAFETY: This invocation of `NonNull::as_mut` satisfies its
// documented safety preconditions:
//
// 1. The pointer is properly aligned. This is ensured by-contract
// on `Ptr`, because the `ALIGNMENT_INVARIANT` is `Aligned`.
//
// 2. It must be “dereferenceable” in the sense defined in the
// module documentation; i.e.:
//
// > The memory range of the given size starting at the pointer
// > must all be within the bounds of a single allocated object.
// > [2]
//
// This is ensured by contract on all `Ptr`s.
//
// 3. The pointer must point to an initialized instance of `T`. This
// is ensured by-contract on `Ptr`, because the
// `VALIDITY_INVARIANT` is `Valid`.
//
// 4. You must enforce Rust’s aliasing rules. This is ensured by
// contract on `Ptr`, because the `ALIASING_INVARIANT` is
// `Exclusive`.
//
// [1]: https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.as_mut
// [2]: https://doc.rust-lang.org/std/ptr/index.html#safety
unsafe { raw.as_mut() }
}
}
/// `Ptr<'a, T = Wrapper<U>>` → `Ptr<'a, U>`
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + TransparentWrapper<I, UnsafeCellVariance = Covariant> + ?Sized,
I: Invariants,
{
/// Converts `self` to a transparent wrapper type into a `Ptr` to the
/// wrapped inner type.
pub(crate) fn transparent_wrapper_into_inner(
self,
) -> Ptr<
'a,
T::Inner,
(
I::Aliasing,
<T::AlignmentVariance as AlignmentVariance<I::Alignment>>::Applied,
<T::ValidityVariance as ValidityVariance<I::Validity>>::Applied,
),
> {
// SAFETY:
// - By invariant on `TransparentWrapper::cast_into_inner`:
// - This cast preserves address and referent size, and thus the
// returned pointer addresses the same bytes as `p`
// - This cast preserves provenance
// - By invariant on `TransparentWrapper<UnsafeCellVariance =
// Covariant>`, `T` and `T::Inner` have `UnsafeCell`s at the same
// byte ranges. Since `p` and the returned pointer address the
// same byte range, they refer to `UnsafeCell`s at the same byte
// ranges.
let c = unsafe { self.cast_unsized(|p| T::cast_into_inner(p)) };
// SAFETY: By invariant on `TransparentWrapper`, since `self`
// satisfies the alignment invariant `I::Alignment`, `c` (of type
// `T::Inner`) satisfies the given "applied" alignment invariant.
let c = unsafe {
c.assume_alignment::<<T::AlignmentVariance as AlignmentVariance<I::Alignment>>::Applied>()
};
// SAFETY: By invariant on `TransparentWrapper`, since `self`
// satisfies the validity invariant `I::Validity`, `c` (of type
// `T::Inner`) satisfies the given "applied" validity invariant.
let c = unsafe {
c.assume_validity::<<T::ValidityVariance as ValidityVariance<I::Validity>>::Applied>()
};
c
}
}
/// `Ptr<'a, T, (_, _, _)>` → `Ptr<'a, Unalign<T>, (_, Aligned, _)>`
impl<'a, T, I> Ptr<'a, T, I>
where
I: Invariants,
{
/// Converts a `Ptr` an unaligned `T` into a `Ptr` to an aligned
/// `Unalign<T>`.
pub(crate) fn into_unalign(
self,
) -> Ptr<'a, crate::Unalign<T>, (I::Aliasing, Aligned, I::Validity)> {
// SAFETY:
// - This cast preserves provenance.
// - This cast preserves address. `Unalign<T>` promises to have the
// same size as `T`, and so the cast returns a pointer addressing
// the same byte range as `p`.
// - By the same argument, the returned pointer refers to
// `UnsafeCell`s at the same locations as `p`.
let ptr = unsafe {
#[allow(clippy::as_conversions)]
self.cast_unsized(|p: *mut T| p as *mut crate::Unalign<T>)
};
// SAFETY: `Unalign<T>` promises to have the same bit validity as
// `T`.
let ptr = unsafe { ptr.assume_validity::<I::Validity>() };
// SAFETY: `Unalign<T>` promises to have alignment 1, and so it is
// trivially aligned.
let ptr = unsafe { ptr.assume_alignment::<Aligned>() };
ptr
}
}
}
/// State transitions between invariants.
mod _transitions {
use super::*;
use crate::{AlignmentError, TryFromBytes, ValidityError};
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
/// Returns a `Ptr` with [`Exclusive`] aliasing if `self` already has
/// `Exclusive` aliasing.
///
/// This allows code which is generic over aliasing to down-cast to a
/// concrete aliasing.
///
/// [`Exclusive`]: invariant::Exclusive
#[inline]
pub(crate) fn into_exclusive_or_post_monomorphization_error(
self,
) -> Ptr<'a, T, (Exclusive, I::Alignment, I::Validity)> {
trait AliasingExt: Aliasing {
const IS_EXCLUSIVE: bool;
}
impl<A: Aliasing> AliasingExt for A {
const IS_EXCLUSIVE: bool = {
let is_exclusive =
strs_are_equal(<Self as Aliasing>::NAME, <Exclusive as Aliasing>::NAME);
const_assert!(is_exclusive);
true
};
}
const fn strs_are_equal(s: &str, t: &str) -> bool {
if s.len() != t.len() {
return false;
}
let s = s.as_bytes();
let t = t.as_bytes();
let mut i = 0;
#[allow(clippy::arithmetic_side_effects)]
while i < s.len() {
#[allow(clippy::indexing_slicing)]
if s[i] != t[i] {
return false;
}
i += 1;
}
true
}
assert!(I::Aliasing::IS_EXCLUSIVE);
// SAFETY: We've confirmed that `self` already has the aliasing
// `Exclusive`. If it didn't, either the preceding assert would fail
// or evaluating `I::Aliasing::IS_EXCLUSIVE` would fail. We're
// *pretty* sure that it's guaranteed to fail const eval, but the
// `assert!` provides a backstop in case that doesn't work.
unsafe { self.assume_exclusive() }
}
/// Assumes that `self` satisfies the invariants `H`.
///
/// # Safety
///
/// The caller promises that `self` satisfies the invariants `H`.
pub(super) unsafe fn assume_invariants<H: Invariants>(self) -> Ptr<'a, T, H> {
// SAFETY: The caller has promised to satisfy all parameterized
// invariants of `Ptr`. `Ptr`'s other invariants are satisfied
// by-contract by the source `Ptr`.
unsafe { Ptr::new(self.as_non_null()) }
}
/// Assumes that `self` satisfies the aliasing requirement of `A`.
///
/// # Safety
///
/// The caller promises that `self` satisfies the aliasing requirement
/// of `A`.
#[inline]
pub(crate) unsafe fn assume_aliasing<A: Aliasing>(
self,
) -> Ptr<'a, T, (A, I::Alignment, I::Validity)> {
// SAFETY: The caller promises that `self` satisfies the aliasing
// requirements of `A`.
unsafe { self.assume_invariants() }
}
/// Assumes `self` satisfies the aliasing requirement of [`Exclusive`].
///
/// # Safety
///
/// The caller promises that `self` satisfies the aliasing requirement
/// of `Exclusive`.
///
/// [`Exclusive`]: invariant::Exclusive
#[inline]
pub(crate) unsafe fn assume_exclusive(
self,
) -> Ptr<'a, T, (Exclusive, I::Alignment, I::Validity)> {
// SAFETY: The caller promises that `self` satisfies the aliasing
// requirements of `Exclusive`.
unsafe { self.assume_aliasing::<Exclusive>() }
}
/// Assumes that `self`'s referent is validly-aligned for `T` if
/// required by `A`.
///
/// # Safety
///
/// The caller promises that `self`'s referent conforms to the alignment
/// invariant of `T` if required by `A`.
#[inline]
pub(crate) unsafe fn assume_alignment<A: Alignment>(
self,
) -> Ptr<'a, T, (I::Aliasing, A, I::Validity)> {
// SAFETY: The caller promises that `self`'s referent is
// well-aligned for `T` if required by `A` .
unsafe { self.assume_invariants() }
}
/// Checks the `self`'s alignment at runtime, returning an aligned `Ptr`
/// on success.
pub(crate) fn bikeshed_try_into_aligned(
self,
) -> Result<Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)>, AlignmentError<Self, T>>
where
T: Sized,
{
if !crate::util::aligned_to::<_, T>(self.as_non_null()) {
return Err(AlignmentError::new(self));
}
// SAFETY: We just checked the alignment.
Ok(unsafe { self.assume_alignment::<Aligned>() })
}
/// Recalls that `self`'s referent is validly-aligned for `T`.
#[inline]
// TODO(#859): Reconsider the name of this method before making it
// public.
pub(crate) fn bikeshed_recall_aligned(
self,
) -> Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)>
where
T: crate::Unaligned,
{
// SAFETY: The bound `T: Unaligned` ensures that `T` has no
// non-trivial alignment requirement.
unsafe { self.assume_alignment::<Aligned>() }
}
/// Assumes that `self`'s referent conforms to the validity requirement
/// of `V`.
///
/// # Safety
///
/// The caller promises that `self`'s referent conforms to the validity
/// requirement of `V`.
#[doc(hidden)]
#[must_use]
#[inline]
pub unsafe fn assume_validity<V: Validity>(
self,
) -> Ptr<'a, T, (I::Aliasing, I::Alignment, V)> {
// SAFETY: The caller promises that `self`'s referent conforms to
// the validity requirement of `V`.
unsafe { self.assume_invariants() }
}
/// A shorthand for `self.assume_validity<invariant::Initialized>()`.
///
/// # Safety
///
/// The caller promises to uphold the safety preconditions of
/// `self.assume_validity<invariant::Initialized>()`.
#[doc(hidden)]
#[must_use]
#[inline]
pub unsafe fn assume_initialized(
self,
) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Initialized)> {
// SAFETY: The caller has promised to uphold the safety
// preconditions.
unsafe { self.assume_validity::<Initialized>() }
}
/// A shorthand for `self.assume_validity<Valid>()`.
///
/// # Safety
///
/// The caller promises to uphold the safety preconditions of
/// `self.assume_validity<Valid>()`.
#[doc(hidden)]
#[must_use]
#[inline]
pub unsafe fn assume_valid(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)> {
// SAFETY: The caller has promised to uphold the safety
// preconditions.
unsafe { self.assume_validity::<Valid>() }
}
/// Recalls that `self`'s referent is bit-valid for `T`.
#[inline]
// TODO(#859): Reconsider the name of this method before making it
// public.
pub(crate) fn bikeshed_recall_valid(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)>
where
T: crate::FromBytes,
I: Invariants<Validity = Initialized>,
{
// SAFETY: The bound `T: FromBytes` ensures that any initialized
// sequence of bytes is bit-valid for `T`. `I: Invariants<Validity =
// invariant::Initialized>` ensures that all of the referent bytes
// are initialized.
unsafe { self.assume_valid() }
}
/// Checks that `self`'s referent is validly initialized for `T`,
/// returning a `Ptr` with `Valid` on success.
///
/// # Panics
///
/// This method will panic if
/// [`T::is_bit_valid`][TryFromBytes::is_bit_valid] panics.
///
/// # Safety
///
/// On error, unsafe code may rely on this method's returned
/// `ValidityError` containing `self`.
#[inline]
pub(crate) fn try_into_valid(
mut self,
) -> Result<Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)>, ValidityError<Self, T>>
where
T: TryFromBytes,
I::Aliasing: AtLeast<Shared>,
I: Invariants<Validity = Initialized>,
{
// This call may panic. If that happens, it doesn't cause any soundness
// issues, as we have not generated any invalid state which we need to
// fix before returning.
if T::is_bit_valid(self.reborrow().forget_aligned()) {
// SAFETY: If `T::is_bit_valid`, code may assume that `self`
// contains a bit-valid instance of `Self`.
Ok(unsafe { self.assume_valid() })
} else {
Err(ValidityError::new(self))
}
}
/// Forgets that `self`'s referent exclusively references `T`,
/// downgrading to a shared reference.
#[doc(hidden)]
#[must_use]
#[inline]
pub fn forget_exclusive(self) -> Ptr<'a, T, (Shared, I::Alignment, I::Validity)>
where
I::Aliasing: AtLeast<Shared>,
{
// SAFETY: `I::Aliasing` is at least as restrictive as `Shared`.
unsafe { self.assume_invariants() }
}
/// Forgets that `self`'s referent is validly-aligned for `T`.
#[doc(hidden)]
#[must_use]
#[inline]
pub fn forget_aligned(self) -> Ptr<'a, T, (I::Aliasing, Any, I::Validity)> {
// SAFETY: `Any` is less restrictive than `Aligned`.
unsafe { self.assume_invariants() }
}
}
}
/// Casts of the referent type.
mod _casts {
use super::*;
use crate::{
layout::{DstLayout, MetadataCastError},
pointer::aliasing_safety::*,
AlignmentError, CastError, PointerMetadata, SizeError,
};
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
/// Casts to a different (unsized) target type.
///
/// # Safety
///
/// The caller promises that `u = cast(p)` is a pointer cast with the
/// following properties:
/// - `u` addresses a subset of the bytes addressed by `p`
/// - `u` has the same provenance as `p`
/// - If `I::Aliasing` is [`Any`] or [`Shared`], `UnsafeCell`s in `*u`
/// must exist at ranges identical to those at which `UnsafeCell`s
/// exist in `*p`
#[doc(hidden)]
#[inline]
pub unsafe fn cast_unsized<U: 'a + ?Sized, F: FnOnce(*mut T) -> *mut U>(
self,
cast: F,
) -> Ptr<'a, U, (I::Aliasing, Any, Any)> {
let ptr = cast(self.as_non_null().as_ptr());
// SAFETY: Caller promises that `cast` returns a pointer whose
// address is in the range of `self.as_non_null()`'s referent. By
// invariant, none of these addresses are null.
let ptr = unsafe { NonNull::new_unchecked(ptr) };
// SAFETY:
//
// Lemma 1: `ptr` has the same provenance as `self`. The caller
// promises that `cast` preserves provenance, and we call it with
// `self.as_non_null()`.
//
// 0. By invariant, `self` is derived from some valid Rust
// allocation, `A`. By Lemma 1, `ptr` has the same provenance as
// `self`. Thus, `ptr` is derived from `A`.
// 1. By invariant, `self` has valid provenance for `A`. By Lemma 1,
// so does `ptr`.
// 2. By invariant on `self` and caller precondition, `ptr`
// addresses a byte range which is entirely contained in `A`.
// 3. By invariant on `self` and caller precondition, `ptr`
// addresses a byte range whose length fits in an `isize`.
// 4. By invariant on `self` and caller precondition, `ptr`
// addresses a byte range which does not wrap around the address
// space.
// 5. By invariant on `self`, `A` is guaranteed to live for at least
// `'a`.
// 6. `ptr` conforms to the aliasing invariant of `I::Aliasing`:
// - `Exclusive`: `self` is the only `Ptr` or reference which is
// permitted to read or modify the referent for the lifetime
// `'a`. Since we consume `self` by value, the returned pointer
// remains the only `Ptr` or reference which is permitted to
// read or modify the referent for the lifetime `'a`.
// - `Shared`: Since `self` has aliasing `Shared`, we know that
// no other code may mutate the referent during the lifetime
// `'a`, except via `UnsafeCell`s. The caller promises that
// `UnsafeCell`s cover the same byte ranges in `*self` and
// `*ptr`. For each byte in the referent, there are two cases:
// - If the byte is not covered by an `UnsafeCell` in `*ptr`,
// then it is not covered in `*self`. By invariant on `self`,
// it will not be mutated during `'a`, as required by the
// constructed pointer. Similarly, the returned pointer will
// not permit any mutations to these locations, as required
// by the invariant on `self`.
// - If the byte is covered by an `UnsafeCell` in `*ptr`, then
// the returned pointer's invariants do not assume that the
// byte will not be mutated during `'a`. While the returned
// pointer will permit mutation of this byte during `'a`, by
// invariant on `self`, no other code assumes that this will
// not happen.
// 7. `ptr`, trivially, conforms to the alignment invariant of
// `Any`.
// 8. `ptr`, trivially, conforms to the validity invariant of
// `Any`.
unsafe { Ptr::new(ptr) }
}
}
impl<'a, T, I> Ptr<'a, T, I>
where