Debian Codegraph @

third_party/rust/windows-core/src/imp/weak_ref_count.rs

raw
1 use super::*;
2 use crate::Interface;
3 use core::ffi::c_void;
4 use core::mem::{transmute, transmute_copy};
5 use core::ptr::null_mut;
6 use core::sync::atomic::{AtomicIsize, Ordering};
7
8 #[repr(transparent)]
9 #[derive(Default)]
10 pub struct WeakRefCount(AtomicIsize);
11
12 impl WeakRefCount {
13 pub fn new() -> Self {
14 Self(AtomicIsize::new(1))
15 }
16
17 pub fn add_ref(&self) -> u32 {
18 self.0
19 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |count_or_pointer| {
20 bool::then_some(!is_weak_ref(count_or_pointer), count_or_pointer + 1)
21 })
22 .map(|u| u as u32 + 1)
23 .unwrap_or_else(|pointer| unsafe { TearOff::decode(pointer).strong_count.add_ref() })
24 }
25
26 #[inline(always)]
27 pub fn is_one(&self) -> bool {
28 self.0.load(Ordering::Acquire) == 1
29 }
30
31 pub fn release(&self) -> u32 {
32 self.0
33 .fetch_update(Ordering::Release, Ordering::Relaxed, |count_or_pointer| {
34 bool::then_some(!is_weak_ref(count_or_pointer), count_or_pointer - 1)
35 })
36 .map(|u| u as u32 - 1)
37 .unwrap_or_else(|pointer| unsafe {
38 let tear_off = TearOff::decode(pointer);
39 let remaining = tear_off.strong_count.release();
40
41 // If this is the last strong reference, we can release the weak reference implied by the strong reference.
42 // There may still be weak references, so the WeakRelease is called to handle such possibilities.
43 if remaining == 0 {
44 TearOff::WeakRelease(&mut tear_off.weak_vtable as *mut _ as _);
45 }
46
47 remaining
48 })
49 }
50
51 /// # Safety
52 pub unsafe fn query(&self, iid: &crate::GUID, object: *mut c_void) -> *mut c_void {
53 if iid != &IWeakReferenceSource::IID {
54 return null_mut();
55 }
56
57 let mut count_or_pointer = self.0.load(Ordering::Relaxed);
58
59 if is_weak_ref(count_or_pointer) {
60 return TearOff::from_encoding(count_or_pointer);
61 }
62
63 let tear_off = TearOff::new(object, count_or_pointer as u32);
64 let tear_off_ptr: *mut c_void = transmute_copy(&tear_off);
65 let encoding: usize = ((tear_off_ptr as usize) >> 1) | (1 << (usize::BITS - 1));
66
67 loop {
68 match self.0.compare_exchange_weak(
69 count_or_pointer,
70 encoding as isize,
71 Ordering::AcqRel,
72 Ordering::Relaxed,
73 ) {
74 Ok(_) => {
75 let result: *mut c_void = transmute(tear_off);
76 TearOff::from_strong_ptr(result).strong_count.add_ref();
77 return result;
78 }
79 Err(pointer) => count_or_pointer = pointer,
80 }
81
82 if is_weak_ref(count_or_pointer) {
83 return TearOff::from_encoding(count_or_pointer);
84 }
85
86 TearOff::from_strong_ptr(tear_off_ptr)
87 .strong_count
88 .0
89 .store(count_or_pointer as i32, Ordering::SeqCst);
90 }
91 }
92 }
93
94 fn is_weak_ref(value: isize) -> bool {
95 value < 0
96 }
97
98 #[repr(C)]
99 struct TearOff {
100 strong_vtable: *const IWeakReferenceSource_Vtbl,
101 weak_vtable: *const IWeakReference_Vtbl,
102 object: *mut c_void,
103 strong_count: RefCount,
104 weak_count: RefCount,
105 }
106
107 impl TearOff {
108 #[allow(clippy::new_ret_no_self)]
109 unsafe fn new(object: *mut c_void, strong_count: u32) -> IWeakReferenceSource {
110 transmute(Box::new(TearOff {
111 strong_vtable: &Self::STRONG_VTABLE,
112 weak_vtable: &Self::WEAK_VTABLE,
113 object,
114 strong_count: RefCount::new(strong_count),
115 weak_count: RefCount::new(1),
116 }))
117 }
118
119 unsafe fn from_encoding(encoding: isize) -> *mut c_void {
120 let tear_off = TearOff::decode(encoding);
121 tear_off.strong_count.add_ref();
122 tear_off as *mut _ as *mut _
123 }
124
125 const STRONG_VTABLE: IWeakReferenceSource_Vtbl = IWeakReferenceSource_Vtbl {
126 base__: crate::IUnknown_Vtbl {
127 QueryInterface: Self::StrongQueryInterface,
128 AddRef: Self::StrongAddRef,
129 Release: Self::StrongRelease,
130 },
131 GetWeakReference: Self::StrongDowngrade,
132 };
133
134 const WEAK_VTABLE: IWeakReference_Vtbl = IWeakReference_Vtbl {
135 base__: crate::IUnknown_Vtbl {
136 QueryInterface: Self::WeakQueryInterface,
137 AddRef: Self::WeakAddRef,
138 Release: Self::WeakRelease,
139 },
140 Resolve: Self::WeakUpgrade,
141 };
142
143 unsafe fn from_strong_ptr<'a>(this: *mut c_void) -> &'a mut Self {
144 &mut *(this as *mut *mut c_void as *mut Self)
145 }
146
147 unsafe fn from_weak_ptr<'a>(this: *mut c_void) -> &'a mut Self {
148 &mut *((this as *mut *mut c_void).sub(1) as *mut Self)
149 }
150
151 unsafe fn decode<'a>(value: isize) -> &'a mut Self {
152 transmute(value << 1)
153 }
154
155 unsafe fn query_interface(
156 &self,
157 iid: *const crate::GUID,
158 interface: *mut *mut c_void,
159 ) -> crate::HRESULT {
160 ((*(*(self.object as *mut *mut crate::IUnknown_Vtbl))).QueryInterface)(
161 self.object,
162 iid,
163 interface,
164 )
165 }
166
167 unsafe extern "system" fn StrongQueryInterface(
168 ptr: *mut c_void,
169 iid: *const crate::GUID,
170 interface: *mut *mut c_void,
171 ) -> crate::HRESULT {
172 let this = Self::from_strong_ptr(ptr);
173
174 if iid.is_null() || interface.is_null() {
175 return E_POINTER;
176 }
177
178 // Only directly respond to queries for the the tear-off's strong interface. This is
179 // effectively a self-query.
180 if *iid == IWeakReferenceSource::IID {
181 *interface = ptr;
182 this.strong_count.add_ref();
183 return crate::HRESULT(0);
184 }
185
186 // As the tear-off is sharing the identity of the object, simply delegate any remaining
187 // queries to the object.
188 this.query_interface(iid, interface)
189 }
190
191 unsafe extern "system" fn WeakQueryInterface(
192 ptr: *mut c_void,
193 iid: *const crate::GUID,
194 interface: *mut *mut c_void,
195 ) -> crate::HRESULT {
196 let this = Self::from_weak_ptr(ptr);
197
198 if iid.is_null() || interface.is_null() {
199 return E_POINTER;
200 }
201
202 // While the weak vtable is packed into the same allocation as the strong vtable and
203 // tear-off, it represents a distinct COM identity and thus does not share or delegate to
204 // the object.
205
206 *interface = if *iid == IWeakReference::IID
207 || *iid == crate::IUnknown::IID
208 || *iid == IAgileObject::IID
209 {
210 ptr
211 } else {
212 null_mut()
213 };
214
215 // TODO: implement IMarshal
216
217 if (*interface).is_null() {
218 E_NOINTERFACE
219 } else {
220 this.weak_count.add_ref();
221 crate::HRESULT(0)
222 }
223 }
224
225 unsafe extern "system" fn StrongAddRef(ptr: *mut c_void) -> u32 {
226 let this = Self::from_strong_ptr(ptr);
227
228 // Implement `AddRef` directly as we own the strong reference.
229 this.strong_count.add_ref()
230 }
231
232 unsafe extern "system" fn WeakAddRef(ptr: *mut c_void) -> u32 {
233 let this = Self::from_weak_ptr(ptr);
234
235 // Implement `AddRef` directly as we own the weak reference.
236 this.weak_count.add_ref()
237 }
238
239 unsafe extern "system" fn StrongRelease(ptr: *mut c_void) -> u32 {
240 let this = Self::from_strong_ptr(ptr);
241
242 // Forward strong `Release` to the object so that it can destroy itself. It will then
243 // decrement its weak reference and allow the tear-off to be released as needed.
244 ((*(*(this.object as *mut *mut crate::IUnknown_Vtbl))).Release)(this.object)
245 }
246
247 unsafe extern "system" fn WeakRelease(ptr: *mut c_void) -> u32 {
248 let this = Self::from_weak_ptr(ptr);
249
250 // Implement `Release` directly as we own the weak reference.
251 let remaining = this.weak_count.release();
252
253 // If there are no remaining references, it means that the object has already been
254 // destroyed. Go ahead and destroy the tear-off.
255 if remaining == 0 {
256 let _ = Box::from_raw(this);
257 }
258
259 remaining
260 }
261
262 unsafe extern "system" fn StrongDowngrade(
263 ptr: *mut c_void,
264 interface: *mut *mut c_void,
265 ) -> crate::HRESULT {
266 let this = Self::from_strong_ptr(ptr);
267
268 // The strong vtable hands out a reference to the weak vtable. This is always safe and
269 // straightforward since a strong reference guarantees there is at least one weak
270 // reference.
271 *interface = &mut this.weak_vtable as *mut _ as _;
272 this.weak_count.add_ref();
273 crate::HRESULT(0)
274 }
275
276 unsafe extern "system" fn WeakUpgrade(
277 ptr: *mut c_void,
278 iid: *const crate::GUID,
279 interface: *mut *mut c_void,
280 ) -> crate::HRESULT {
281 let this = Self::from_weak_ptr(ptr);
282
283 this.strong_count
284 .0
285 .fetch_update(Ordering::Acquire, Ordering::Relaxed, |count| {
286 // Attempt to acquire a strong reference count to stabilize the object for the duration
287 // of the `QueryInterface` call.
288 bool::then_some(count != 0, count + 1)
289 })
290 .map(|_| {
291 // Let the object respond to the upgrade query.
292 let result = this.query_interface(iid, interface);
293 // Decrement the temporary reference account used to stabilize the object.
294 this.strong_count.0.fetch_sub(1, Ordering::Relaxed);
295 // Return the result of the query.
296 result
297 })
298 .unwrap_or_else(|_| {
299 *interface = null_mut();
300 crate::HRESULT(0)
301 })
302 }
303 }