Debian Codegraph @

third_party/rust/self_cell/src/unsafe_self_cell.rs

raw
1 use core::marker::PhantomData;
2 use core::mem::{self, transmute};
3 use core::ptr::{drop_in_place, read, NonNull};
4
5 extern crate alloc;
6
7 use alloc::alloc::{dealloc, Layout};
8
9 // Self referential structs are currently not supported with safe vanilla Rust.
10 // The only reasonable safe alternative is to expect the user to juggle 2 separate
11 // data structures which is a mess. The library solution rental is both no longer
12 // maintained and really heavy to compile. So begrudgingly I rolled my own version.
13 // These are some of the core invariants we require for this to be safe to use.
14 //
15 // 1. owner is initialized when UnsafeSelfCell is constructed.
16 // 2. owner is NEVER changed again.
17 // 3. The pointer to owner and dependent never changes, even when moved.
18 // 4. The only access to owner and dependent is as immutable reference.
19 // 5. owner lives longer than dependent.
20
21 #[doc(hidden)]
22 pub struct JoinedCell<Owner, Dependent> {
23 pub owner: Owner,
24 pub dependent: Dependent,
25 }
26
27 // Library controlled struct that marks all accesses as unsafe.
28 // Because the macro generated struct impl can be extended, could be unsafe.
29 #[doc(hidden)]
30 pub struct UnsafeSelfCell<ContainedIn, Owner, DependentStatic: 'static> {
31 joined_void_ptr: NonNull<u8>,
32
33 // ContainedIn is necessary for type safety since we don't fully
34 // prohibit access to the UnsafeSelfCell; swapping between different
35 // structs can be unsafe otherwise, see Issue #17.
36 contained_in_marker: PhantomData<ContainedIn>,
37
38 owner_marker: PhantomData<Owner>,
39 // DependentStatic is only used to correctly derive Send and Sync.
40 dependent_marker: PhantomData<DependentStatic>,
41 }
42
43 impl<ContainedIn, Owner, DependentStatic> UnsafeSelfCell<ContainedIn, Owner, DependentStatic> {
44 pub unsafe fn new(joined_void_ptr: NonNull<u8>) -> Self {
45 Self {
46 joined_void_ptr,
47 contained_in_marker: PhantomData,
48 owner_marker: PhantomData,
49 dependent_marker: PhantomData,
50 }
51 }
52
53 // Calling any of these *unsafe* functions with the wrong Dependent type is UB.
54
55 pub unsafe fn borrow_owner<'a, Dependent>(&'a self) -> &'a Owner {
56 let joined_ptr =
57 transmute::<NonNull<u8>, NonNull<JoinedCell<Owner, Dependent>>>(self.joined_void_ptr);
58
59 &(*joined_ptr.as_ptr()).owner
60 }
61
62 pub unsafe fn borrow_dependent<'a, Dependent>(&'a self) -> &'a Dependent {
63 let joined_ptr =
64 transmute::<NonNull<u8>, NonNull<JoinedCell<Owner, Dependent>>>(self.joined_void_ptr);
65
66 &(*joined_ptr.as_ptr()).dependent
67 }
68
69 pub unsafe fn borrow_mut<'a, Dependent>(&'a mut self) -> (&'a Owner, &'a mut Dependent) {
70 let joined_ptr =
71 transmute::<NonNull<u8>, NonNull<JoinedCell<Owner, Dependent>>>(self.joined_void_ptr);
72
73 // This function used to return `&'a mut JoinedCell<Owner, Dependent>`.
74 // It now creates two references to the fields instead to avoid claiming mutable access
75 // to the whole `JoinedCell` (including the owner!) here.
76 (
77 &(*joined_ptr.as_ptr()).owner,
78 &mut (*joined_ptr.as_ptr()).dependent,
79 )
80 }
81
82 // Any subsequent use of this struct other than dropping it is UB.
83 pub unsafe fn drop_joined<Dependent>(&mut self) {
84 let joined_ptr =
85 transmute::<NonNull<u8>, NonNull<JoinedCell<Owner, Dependent>>>(self.joined_void_ptr);
86
87 // Also used in case drop_in_place(...dependent) fails
88 let _guard = OwnerAndCellDropGuard { joined_ptr };
89
90 // IMPORTANT dependent must be dropped before owner.
91 // We don't want to rely on an implicit order of struct fields.
92 // So we drop the struct, field by field manually.
93 drop_in_place(&mut (*joined_ptr.as_ptr()).dependent);
94
95 // Dropping owner
96 // and deallocating
97 // due to _guard at end of scope.
98 }
99
100 pub unsafe fn into_owner<Dependent>(self) -> Owner {
101 let joined_ptr =
102 transmute::<NonNull<u8>, NonNull<JoinedCell<Owner, Dependent>>>(self.joined_void_ptr);
103
104 // In case drop_in_place(...dependent) fails
105 let drop_guard = OwnerAndCellDropGuard::new(joined_ptr);
106
107 // Drop dependent
108 drop_in_place(&mut (*joined_ptr.as_ptr()).dependent);
109
110 mem::forget(drop_guard);
111
112 let owner_ptr: *const Owner = &(*joined_ptr.as_ptr()).owner;
113
114 // Move owner out so it can be returned.
115 // Must not read before dropping dependent!! (Which happened above.)
116 let owner = read(owner_ptr);
117
118 // Deallocate JoinedCell
119 let layout = Layout::new::<JoinedCell<Owner, Dependent>>();
120 dealloc(self.joined_void_ptr.as_ptr(), layout);
121
122 owner
123 }
124 }
125
126 unsafe impl<ContainedIn, Owner, DependentStatic> Send
127 for UnsafeSelfCell<ContainedIn, Owner, DependentStatic>
128 where
129 // Only derive Send if Owner and DependentStatic is also Send
130 Owner: Send,
131 DependentStatic: Send,
132 {
133 }
134
135 unsafe impl<ContainedIn, Owner, DependentStatic> Sync
136 for UnsafeSelfCell<ContainedIn, Owner, DependentStatic>
137 where
138 // Only derive Sync if Owner and DependentStatic is also Sync
139 Owner: Sync,
140 DependentStatic: Sync,
141 {
142 }
143
144 // This struct is used to safely deallocate only the owner if dependent
145 // construction fails.
146 //
147 // mem::forget it once it's no longer needed or dtor will be UB.
148 #[doc(hidden)]
149 pub struct OwnerAndCellDropGuard<Owner, Dependent> {
150 joined_ptr: NonNull<JoinedCell<Owner, Dependent>>,
151 }
152
153 impl<Owner, Dependent> OwnerAndCellDropGuard<Owner, Dependent> {
154 pub unsafe fn new(joined_ptr: NonNull<JoinedCell<Owner, Dependent>>) -> Self {
155 Self { joined_ptr }
156 }
157 }
158
159 impl<Owner, Dependent> Drop for OwnerAndCellDropGuard<Owner, Dependent> {
160 fn drop(&mut self) {
161 struct DeallocGuard {
162 ptr: *mut u8,
163 layout: Layout,
164 }
165 impl Drop for DeallocGuard {
166 fn drop(&mut self) {
167 unsafe { dealloc(self.ptr, self.layout) }
168 }
169 }
170
171 // Deallocate even when the drop_in_place(...owner) panics
172 let _guard = DeallocGuard {
173 ptr: unsafe {
174 transmute::<*mut JoinedCell<Owner, Dependent>, *mut u8>(self.joined_ptr.as_ptr())
175 },
176 layout: Layout::new::<JoinedCell<Owner, Dependent>>(),
177 };
178
179 unsafe {
180 // We must only drop owner and the struct itself,
181 // The whole point of this drop guard is to clean up the partially
182 // initialized struct should building the dependent fail.
183 drop_in_place(&mut (*self.joined_ptr.as_ptr()).owner);
184 }
185
186 // Deallocation happens at end of scope
187 }
188 }
189
190 // Older versions of rust do not support addr_of_mut!. What we want to do here
191 // is to emulate the behavior of that macro by going (incorrectly) via a
192 // reference cast. Technically this is UB, but testing does not show the older
193 // compiler versions (ab)using this. For discussions about this behavior see
194 // https://github.com/Voultapher/self_cell/pull/31 and
195 // https://github.com/Voultapher/self_cell/issues/30 and
196 // https://github.com/Voultapher/self_cell/pull/33
197 //
198 // Because of 'procedural macros cannot expand to macro definitions'
199 // we have wrap this in functions.
200 impl<Owner, Dependent> JoinedCell<Owner, Dependent> {
201 #[doc(hidden)]
202 #[cfg(not(feature = "old_rust"))]
203 pub unsafe fn _field_pointers(this: *mut Self) -> (*mut Owner, *mut Dependent) {
204 let owner_ptr = core::ptr::addr_of_mut!((*this).owner);
205 let dependent_ptr = core::ptr::addr_of_mut!((*this).dependent);
206
207 (owner_ptr, dependent_ptr)
208 }
209
210 #[doc(hidden)]
211 #[cfg(feature = "old_rust")]
212 #[rustversion::since(1.51)]
213 pub unsafe fn _field_pointers(this: *mut Self) -> (*mut Owner, *mut Dependent) {
214 let owner_ptr = core::ptr::addr_of_mut!((*this).owner);
215 let dependent_ptr = core::ptr::addr_of_mut!((*this).dependent);
216
217 (owner_ptr, dependent_ptr)
218 }
219
220 #[doc(hidden)]
221 #[cfg(feature = "old_rust")]
222 #[rustversion::before(1.51)]
223 pub unsafe fn _field_pointers(this: *mut Self) -> (*mut Owner, *mut Dependent) {
224 // See comment above, technically this is UB.
225 let owner_ptr = &mut (*this).owner as *mut Owner;
226 let dependent_ptr = &mut (*this).dependent as *mut Dependent;
227
228 (owner_ptr, dependent_ptr)
229 }
230 }