-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathptr.rs
More file actions
1496 lines (1406 loc) · 63.8 KB
/
ptr.rs
File metadata and controls
1496 lines (1406 loc) · 63.8 KB
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::{
fmt::{Debug, Formatter},
marker::PhantomData,
};
use crate::{
pointer::{
inner::PtrInner,
invariant::*,
transmute::{MutationCompatible, SizeEq, TransmuteFromPtr},
},
AlignmentError, CastError, CastType, KnownLayout, SizeError, TryFromBytes, ValidityError,
};
/// Module used to gate access to [`Ptr`]'s fields.
mod def {
#[cfg(doc)]
use super::super::invariant;
use super::*;
/// A raw pointer with more restrictions.
///
/// `Ptr<T>` is similar to [`NonNull<T>`], but it is more restrictive in the
/// following ways (note that these requirements only hold of non-zero-sized
/// referents):
/// - 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 invariant in `T`.
///
/// [`NonNull<T>`]: core::ptr::NonNull
/// [covariant]: https://doc.rust-lang.org/reference/subtyping.html
pub struct Ptr<'a, T, I>
where
T: ?Sized,
I: Invariants,
{
/// # Invariants
///
/// 0. `ptr` conforms to the aliasing invariant of
/// [`I::Aliasing`](invariant::Aliasing).
/// 1. `ptr` conforms to the alignment invariant of
/// [`I::Alignment`](invariant::Alignment).
/// 2. `ptr` conforms to the validity invariant of
/// [`I::Validity`](invariant::Validity).
// SAFETY: `PtrInner<'a, T>` is covariant in `'a` and invariant in `T`.
ptr: PtrInner<'a, T>,
_invariants: PhantomData<I>,
}
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
/// Constructs a new `Ptr` from a [`PtrInner`].
///
/// # Safety
///
/// The caller promises that:
///
/// 0. `ptr` conforms to the aliasing invariant of
/// [`I::Aliasing`](invariant::Aliasing).
/// 1. `ptr` conforms to the alignment invariant of
/// [`I::Alignment`](invariant::Alignment).
/// 2. `ptr` conforms to the validity invariant of
/// [`I::Validity`](invariant::Validity).
pub(crate) unsafe fn from_inner(ptr: PtrInner<'a, 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 [`PtrInner<T>`].
///
/// Note that this method does not consume `self`. The caller should
/// watch out for `unsafe` code which uses the returned value in a way
/// that violates the safety invariants of `self`.
pub(crate) fn as_inner(&self) -> PtrInner<'a, T> {
self.ptr
}
}
}
#[allow(unreachable_pub)] // This is a false positive on our MSRV toolchain.
pub use def::Ptr;
/// External trait implementations on [`Ptr`].
mod _external {
use super::*;
/// SAFETY: Shared pointers are safely `Copy`. `Ptr`'s other invariants
/// (besides aliasing) are unaffected by the number of references that exist
/// to `Ptr`'s referent. The notable cases are:
/// - Alignment is a property of the referent type (`T`) and the address,
/// both of which are unchanged
/// - Let `S(T, V)` be the set of bit values permitted to appear in the
/// referent of a `Ptr<T, I: Invariants<Validity = V>>`. Since this copy
/// does not change `I::Validity` or `T`, `S(T, I::Validity)` is also
/// unchanged.
///
/// We are required to guarantee that the referents of the original `Ptr`
/// and of the copy (which, of course, are actually the same since they
/// live in the same byte address range) both remain in the set `S(T,
/// I::Validity)`. Since this invariant holds on the original `Ptr`, it
/// cannot be violated by the original `Ptr`, and thus the original `Ptr`
/// cannot be used to violate this invariant on the copy. The inverse
/// holds as well.
impl<'a, T, I> Copy for Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants<Aliasing = Shared>,
{
}
/// SAFETY: See the safety comment on `Copy`.
impl<'a, T, I> Clone for Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants<Aliasing = Shared>,
{
#[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_inner().as_non_null().fmt(f)
}
}
}
/// Methods for converting to and from `Ptr` and Rust's safe reference types.
mod _conversions {
use super::*;
use crate::pointer::cast::CastSized;
/// `&'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(always)]
pub fn from_ref(ptr: &'a T) -> Self {
let inner = PtrInner::from_ref(ptr);
// SAFETY:
// 0. `ptr`, by invariant on `&'a T`, conforms to the aliasing
// invariant of `Shared`.
// 1. `ptr`, by invariant on `&'a T`, conforms to the alignment
// invariant of `Aligned`.
// 2. `ptr`'s referent, by invariant on `&'a T`, is a bit-valid `T`.
// This satisfies the requirement that a `Ptr<T, (_, _, Valid)>`
// point to a bit-valid `T`. Even if `T` permits interior
// mutation, this invariant guarantees that the returned `Ptr`
// can only ever be used to modify the referent to store
// bit-valid `T`s, which ensures that the returned `Ptr` cannot
// be used to violate the soundness of the original `ptr: &'a T`
// or of any other references that may exist to the same
// referent.
unsafe { Self::from_inner(inner) }
}
}
/// `&'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.
#[doc(hidden)]
#[inline(always)]
pub fn from_mut(ptr: &'a mut T) -> Self {
let inner = PtrInner::from_mut(ptr);
// SAFETY:
// 0. `ptr`, by invariant on `&'a mut T`, conforms to the aliasing
// invariant of `Exclusive`.
// 1. `ptr`, by invariant on `&'a mut T`, conforms to the alignment
// invariant of `Aligned`.
// 2. `ptr`'s referent, by invariant on `&'a mut T`, is a bit-valid
// `T`. This satisfies the requirement that a `Ptr<T, (_, _,
// Valid)>` point to a bit-valid `T`. This invariant guarantees
// that the returned `Ptr` can only ever be used to modify the
// referent to store bit-valid `T`s, which ensures that the
// returned `Ptr` cannot be used to violate the soundness of the
// original `ptr: &'a mut T`.
unsafe { Self::from_inner(inner) }
}
}
/// `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: Reference,
{
/// 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_inner().as_non_null();
// SAFETY: `self` satisfies the `Aligned` invariant, so we know that
// `raw` is validly-aligned for `T`.
#[cfg(miri)]
unsafe {
crate::util::miri_promise_symbolic_alignment(
raw.as_ptr().cast(),
core::mem::align_of_val_raw(raw.as_ptr()),
);
}
// 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. If the pointer's referent is not zero-sized, then the pointer
// 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 `PtrInner`s.
//
// 3. The pointer must point to a validly-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 `I::Aliasing: Reference`. 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: Reference,
{
/// 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_inner()`:
// 0. SEE BELOW.
// 1. `ptr` conforms to the alignment invariant of
// [`I::Alignment`](invariant::Alignment).
// 2. `ptr` conforms to the validity invariant of
// [`I::Validity`](invariant::Validity). `self` and the returned
// `Ptr` permit the same bit values in their referents since they
// have the same referent type (`T`) and the same validity
// (`I::Validity`). Thus, regardless of what mutation is
// permitted (`Exclusive` aliasing or `Shared`-aliased interior
// mutation), neither can be used to write a value to the
// referent which violates the other's validity invariant.
//
// For aliasing (0 above), since `I::Aliasing: Reference`,
// 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::from_inner(self.as_inner()) }
}
}
/// `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_inner().as_non_null();
// SAFETY: `self` satisfies the `Aligned` invariant, so we know that
// `raw` is validly-aligned for `T`.
#[cfg(miri)]
unsafe {
crate::util::miri_promise_symbolic_alignment(
raw.as_ptr().cast(),
core::mem::align_of_val_raw(raw.as_ptr()),
);
}
// 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. If the pointer's referent is not zero-sized, then the pointer
// 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 `PtrInner`s.
//
// 3. The pointer must point to a validly-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>` → `Ptr<'a, U>`
impl<'a, T: ?Sized, I> Ptr<'a, T, I>
where
I: Invariants,
{
pub(crate) fn transmute<U, V, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)>
where
V: Validity,
U: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, R> + SizeEq<T> + ?Sized,
{
// SAFETY:
// - By `SizeEq::CastFrom: Cast`, `SizeEq::CastFrom` preserves
// referent address, and so we don't need to consider projections
// in the following safety arguments.
// - If aliasing is `Shared`, then by `U: TransmuteFromPtr<T>`, at
// least one of the following holds:
// - `T: Immutable` and `U: Immutable`, in which case it is
// trivially sound for shared code to operate on a `&T` and `&U`
// at the same time, as neither can perform interior mutation
// - It is directly guaranteed that it is sound for shared code to
// operate on these references simultaneously
// - By `U: TransmuteFromPtr<T, I::Aliasing, I::Validity, V>`, it is
// sound to perform this transmute.
unsafe { self.project_transmute_unchecked::<_, _, <U as SizeEq<T>>::CastFrom>() }
}
#[doc(hidden)]
#[inline(always)]
#[must_use]
pub fn recall_validity<V, R>(self) -> Ptr<'a, T, (I::Aliasing, I::Alignment, V)>
where
V: Validity,
T: TransmuteFromPtr<T, I::Aliasing, I::Validity, V, R>,
{
// SAFETY:
// - By `SizeEq::CastFrom: Cast`, `SizeEq::CastFrom` preserves
// referent address, and so we don't need to consider projections
// in the following safety arguments.
// - It is trivially sound to have multiple `&T` referencing the
// same referent simultaneously
// - By `T: TransmuteFromPtr<T, I::Aliasing, I::Validity, V>`, it is
// sound to perform this transmute.
let ptr =
unsafe { self.project_transmute_unchecked::<_, _, <T as SizeEq<T>>::CastFrom>() };
// SAFETY: `self` and `ptr` have the same address and referent type.
// Therefore, if `self` satisfies `I::Alignment`, then so does
// `ptr`.
unsafe { ptr.assume_alignment::<I::Alignment>() }
}
/// Projects and/or transmutes to a different (unsized) referent type
/// without checking interior mutability.
///
/// Callers should prefer [`cast`] or [`project`] where possible.
///
/// [`cast`]: Ptr::cast
/// [`project`]: Ptr::project
///
/// # Safety
///
/// The caller promises that:
/// - If `I::Aliasing` is [`Shared`], it must not be possible for safe
/// code, operating on a `&T` and `&U`, with the referents of `self`
/// and `self.project_transmute_unchecked()`, respectively, to cause
/// undefined behavior.
/// - It is sound to project and/or transmute a pointer of type `T` with
/// aliasing `I::Aliasing` and validity `I::Validity` to a pointer of
/// type `U` with aliasing `I::Aliasing` and validity `V`. This is a
/// subtle soundness requirement that is a function of `T`, `U`,
/// `I::Aliasing`, `I::Validity`, and `V`, and may depend upon the
/// presence, absence, or specific location of `UnsafeCell`s in `T`
/// and/or `U`. See [`Validity`] for more details.
#[doc(hidden)]
#[inline(always)]
#[must_use]
pub unsafe fn project_transmute_unchecked<U: ?Sized, V, P>(
self,
) -> Ptr<'a, U, (I::Aliasing, Unaligned, V)>
where
V: Validity,
P: crate::pointer::cast::Project<T, U>,
{
let ptr = self.as_inner().project::<_, P>();
// SAFETY:
//
// The following safety arguments rely on the fact that `P: Project`
// guarantees that `P` is a referent-preserving or -shrinking
// projection. Thus, `ptr` addresses a subset of the bytes of
// `*self`, and so certain properties that hold of `*self` also hold
// of `*ptr`.
//
// 0. `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, and except as permitted by
// `T`'s library safety invariants. The caller promises that
// any safe operations which can be permitted on a `&T` and a
// `&U` simultaneously must be sound. Thus, no operations on a
// `&U` could violate `&T`'s library safety invariants, and
// vice-versa. Since any mutation via shared references outside
// of `UnsafeCell`s is unsound, this must be impossible using
// `&T` and `&U`.
// - `Inaccessible`: There are no restrictions we need to uphold.
// 1. `ptr` trivially satisfies the alignment invariant `Unaligned`.
// 2. The caller promises that the returned pointer satisfies the
// validity invariant `V` with respect to its referent type, `U`.
unsafe { Ptr::from_inner(ptr) }
}
}
/// `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:
// - By `CastSized: Cast`, `CastSized` preserves referent address,
// and so we don't need to consider projections in the following
// safety arguments.
// - Since `Unalign<T>` has the same layout as `T`, the returned
// pointer refers to `UnsafeCell`s at the same locations as
// `self`.
// - `Unalign<T>` promises to have the same bit validity as `T`. By
// invariant on `Validity`, the set of bit patterns allowed in the
// referent of a `Ptr<X, (_, _, V)>` is only a function of the
// validity of `X` and of `V`. Thus, the set of bit patterns
// allowed in the referent of a `Ptr<T, (_, _, I::Validity)>` is
// the same as the set of bit patterns allowed in the referent of
// a `Ptr<Unalign<T>, (_, _, I::Validity)>`. As a result, `self`
// and the returned `Ptr` permit the same set of bit patterns in
// their referents, and so neither can be used to violate the
// validity of the other.
let ptr = unsafe { self.project_transmute_unchecked::<_, _, CastSized>() };
ptr.bikeshed_recall_aligned()
}
}
impl<'a, T, I> Ptr<'a, T, I>
where
T: ?Sized,
I: Invariants<Validity = Valid>,
I::Aliasing: Reference,
{
/// Reads the referent.
#[must_use]
#[inline]
pub fn read_unaligned<R>(self) -> T
where
T: Copy,
T: Read<I::Aliasing, R>,
{
(*self.into_unalign().as_ref()).into_inner()
}
/// Views the value as an aligned reference.
///
/// This is only available if `T` is [`Unaligned`].
#[must_use]
#[inline]
pub fn unaligned_as_ref(self) -> &'a T
where
T: crate::Unaligned,
{
self.bikeshed_recall_aligned().as_ref()
}
}
}
/// State transitions between invariants.
mod _transitions {
use super::*;
use crate::pointer::transmute::TryTransmuteFromPtr;
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, or generates a compile-time assertion failure.
///
/// This allows code which is generic over aliasing to down-cast to a
/// concrete aliasing.
///
/// [`Exclusive`]: crate::pointer::invariant::Exclusive
#[inline]
pub(crate) fn into_exclusive_or_pme(
self,
) -> Ptr<'a, T, (Exclusive, I::Alignment, I::Validity)> {
// NOTE(https://github.com/rust-lang/rust/issues/131625): We do this
// rather than just having `Aliasing::IS_EXCLUSIVE` have the panic
// behavior because doing it that way causes rustdoc to fail while
// attempting to document hidden items (since it evaluates the
// constant - and thus panics).
trait AliasingExt: Aliasing {
const IS_EXCL: bool;
}
impl<A: Aliasing> AliasingExt for A {
const IS_EXCL: bool = {
const_assert!(Self::IS_EXCLUSIVE);
true
};
}
assert!(I::Aliasing::IS_EXCL);
// 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_EXCL` 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`.
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::from_inner(self.as_inner()) }
}
/// Helps the type system unify two distinct invariant types which are
/// actually the same.
pub(crate) fn unify_invariants<
H: Invariants<Aliasing = I::Aliasing, Alignment = I::Alignment, Validity = I::Validity>,
>(
self,
) -> Ptr<'a, T, H> {
// SAFETY: The associated type bounds on `H` ensure that the
// invariants are unchanged.
unsafe { self.assume_invariants::<H>() }
}
/// 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`]: crate::pointer::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 try_into_aligned(
self,
) -> Result<Ptr<'a, T, (I::Aliasing, Aligned, I::Validity)>, AlignmentError<Self, T>>
where
T: Sized,
{
if let Err(err) =
crate::util::validate_aligned_to::<_, T>(self.as_inner().as_non_null())
{
return Err(err.with_src(self));
}
// SAFETY: We just checked the alignment.
Ok(unsafe { self.assume_alignment::<Aligned>() })
}
/// Recalls that `self`'s referent is validly-aligned for `T`.
#[inline]
// FIXME(#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 initialized.
#[doc(hidden)]
#[must_use]
#[inline]
// FIXME(#859): Reconsider the name of this method before making it
// public.
pub fn bikeshed_recall_initialized_from_bytes(
self,
) -> Ptr<'a, T, (I::Aliasing, I::Alignment, Initialized)>
where
T: crate::IntoBytes + crate::FromBytes,
I: Invariants<Validity = Valid>,
{
// SAFETY: The `T: IntoBytes + FromBytes` bound ensures that `T`'s
// bit validity is equivalent to `[u8]`. In other words, the set of
// allowed referents for a `Ptr<T, (_, _, Valid)>` is the set of
// initialized bit patterns. The same is true of the set of allowed
// referents for any `Ptr<_, (_, _, Initialized)>`. Thus, this call
// does not change the set of allowed values in the referent.
unsafe { self.assume_initialized() }
}
/// Recalls that `self`'s referent is initialized.
#[doc(hidden)]
#[must_use]
#[inline]
// FIXME(#859): Reconsider the name of this method before making it
// public.
pub fn bikeshed_recall_initialized_immutable(
self,
) -> Ptr<'a, T, (Shared, I::Alignment, Initialized)>
where
T: crate::IntoBytes + crate::Immutable,
I: Invariants<Aliasing = Shared, Validity = Valid>,
{
// SAFETY: Let `O` (for "old") be the set of allowed bit patterns in
// `self`'s referent, and let `N` (for "new") be the set of allowed
// bit patterns in the referent of the returned `Ptr`. `T:
// IntoBytes` and `I: Invariants<Validity = Valid>` ensures that `O`
// cannot contain any uninitialized bit patterns. Since the returned
// `Ptr` has validity `Initialized`, `N` is equal to the set of all
// initialized bit patterns. Thus, `O` is a subset of `N`, and so
// the returned `Ptr`'s validity invariant is upheld.
//
// Since `T: Immutable` and aliasing is `Shared`, the returned `Ptr`
// cannot be used to modify the referent. Before this call, `self`'s
// referent is guaranteed by invariant on `Ptr` to satisfy `self`'s
// validity invariant. Since the returned `Ptr` cannot be used to
// modify the referent, this guarantee cannot be violated by the
// returned `Ptr` (even if `O` is a strict subset of `N`).
unsafe { self.assume_initialized() }
}
/// 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<R, S>(
mut self,
) -> Result<Ptr<'a, T, (I::Aliasing, I::Alignment, Valid)>, ValidityError<Self, T>>
where
T: TryFromBytes
+ Read<I::Aliasing, R>
+ TryTransmuteFromPtr<T, I::Aliasing, I::Validity, Valid, S>,
I::Aliasing: Reference,
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 `T`. By `T:
// TryTransmuteFromPtr<T, I::Aliasing, I::Validity, Valid>`, so
// long as `self`'s referent conforms to the `Valid` validity
// for `T` (which we just confirmed), then this transmute is
// sound.
Ok(unsafe { self.assume_valid() })
} else {
Err(ValidityError::new(self))
}
}
/// 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, Unaligned, I::Validity)> {
// SAFETY: `Unaligned` is less restrictive than `Aligned`.
unsafe { self.assume_invariants() }
}
}
}
/// Casts of the referent type.
mod _casts {
use core::cell::UnsafeCell;
use super::*;
use crate::{
pointer::cast::{AsBytesCast, Cast},
HasField,
};
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + ?Sized,
I: Invariants,
{
/// Casts to a different referent type without checking interior
/// mutability.
///
/// Callers should prefer [`cast`][Ptr::cast] where possible.
///
/// # Safety
///
/// If `I::Aliasing` is [`Shared`], it must not be possible for safe
/// code, operating on a `&T` and `&U` with the same referent
/// simultaneously, to cause undefined behavior.
#[doc(hidden)]
#[inline(always)]
#[must_use]
pub unsafe fn cast_unchecked<U, C: Cast<T, U>>(
self,
) -> Ptr<'a, U, (I::Aliasing, Unaligned, I::Validity)>
where
U: 'a + CastableFrom<T, I::Validity, I::Validity> + ?Sized,
{
// SAFETY:
// - By `C: Cast`, `C` preserves the address of the referent.
// - If `I::Aliasing` is [`Shared`], the caller promises that it
// is not possible for safe code, operating on a `&T` and `&U`
// with the same referent simultaneously, to cause undefined
// behavior.
// - By `U: CastableFrom<T, I::Validity, I::Validity>`,
// `I::Validity` is either `Uninit` or `Initialized`. In both
// cases, the bit validity `I::Validity` has the same semantics
// regardless of referent type. In other words, the set of allowed
// referent values for `Ptr<T, (_, _, I::Validity)>` and `Ptr<U,
// (_, _, I::Validity)>` are identical. As a consequence, neither
// `self` nor the returned `Ptr` can be used to write values which
// are invalid for the other.
unsafe { self.project_transmute_unchecked::<_, _, C>() }
}
/// Casts to a different referent type.
#[doc(hidden)]
#[inline(always)]
#[must_use]
pub fn cast<U, C, R>(self) -> Ptr<'a, U, (I::Aliasing, Unaligned, I::Validity)>
where
T: MutationCompatible<U, I::Aliasing, I::Validity, I::Validity, R>,
U: 'a + ?Sized + CastableFrom<T, I::Validity, I::Validity>,
C: Cast<T, U>,
{
// SAFETY: Because `T: MutationCompatible<U, I::Aliasing, R>`, one
// of the following holds:
// - `T: Read<I::Aliasing>` and `U: Read<I::Aliasing>`, in which
// case one of the following holds:
// - `I::Aliasing` is `Exclusive`
// - `T` and `U` are both `Immutable`
// - It is sound for safe code to operate on `&T` and `&U` with the
// same referent simultaneously.
unsafe { self.cast_unchecked::<_, C>() }
}
// FIXME(#196): Support all validity invariants (not just those that are
// `CastableFrom`).
#[must_use]
#[inline(always)]
pub fn project<F, const FIELD_ID: i128>(
self,
) -> Ptr<'a, T::Type, (I::Aliasing, Unaligned, I::Validity)>
where
T: HasField<F, { crate::STRUCT_VARIANT_ID }, FIELD_ID>,
T::Type: 'a + CastableFrom<T, I::Validity, I::Validity>,
{
let ptr = self.as_inner().project::<_, crate::pointer::cast::Projection<
F,
{ crate::STRUCT_VARIANT_ID },
FIELD_ID,
>>();
// SAFETY:
// 0. `PtrInner::project` promises that it produces a pointer which
// references a subset of its argument's referent. Since, by
// invariant on `Ptr`, its argument (`self.as_inner()`) satisfies
// the aliasing invariant `I::Aliasing`, so does `ptr`.
// 1. The `Ptr` has alignment `Unaligned`, which is trivially
// satisfied.
// 2. By `CastableFrom<T, I::Validity, I::Validity>`, `I::Validity`
// is `Uninit` or `Initialized`. In either case, if `I::Validity`
// holds of `self`'s referent, then it holds any subset of its
// referent.
unsafe { Ptr::from_inner(ptr) }
}
}
impl<'a, T, I> Ptr<'a, T, I>
where
T: 'a + KnownLayout + ?Sized,
I: Invariants<Validity = Initialized>,
{
// FIXME: Is there any way to teach Rust that, for all `T, A, R`, `T:
// Read<A, R>` implies `[u8]: Read<A, R>`?
/// Casts this pointer-to-initialized into a pointer-to-bytes.
#[allow(clippy::wrong_self_convention)]
#[must_use]
#[inline]
pub fn as_bytes<R>(self) -> Ptr<'a, [u8], (I::Aliasing, Aligned, Valid)>
where
T: Read<I::Aliasing, R>,
[u8]: Read<I::Aliasing, R>,
I::Aliasing: Reference,
{
let ptr = self.cast::<_, AsBytesCast, _>();
ptr.bikeshed_recall_aligned().recall_validity::<Valid, (_, (_, _))>()
}
}
impl<'a, T, I, const N: usize> Ptr<'a, [T; N], I>
where
T: 'a,
I: Invariants,
{
/// Casts this pointer-to-array into a slice.
#[allow(clippy::wrong_self_convention)]
pub(crate) fn as_slice(self) -> Ptr<'a, [T], I> {
let slice = self.as_inner().as_slice();
// SAFETY: Note that, by post-condition on `PtrInner::as_slice`,
// `slice` refers to the same byte range as `self.as_inner()`.
//
// 0. Thus, `slice` conforms to the aliasing invariant of
// `I::Aliasing` because `self` does.