Debian Codegraph @

third_party/rust/windows-core/src/interface.rs

raw
1 use super::*;
2 use core::any::Any;
3 use core::ffi::c_void;
4 use core::marker::PhantomData;
5 use core::mem::{forget, transmute_copy, MaybeUninit};
6 use core::ptr::NonNull;
7
8 /// Provides low-level access to an interface vtable.
9 ///
10 /// This trait is automatically implemented by the generated bindings and should not be
11 /// implemented manually.
12 ///
13 /// # Safety
14 pub unsafe trait Interface: Sized + Clone {
15 #[doc(hidden)]
16 type Vtable;
17
18 /// The `GUID` associated with the interface.
19 const IID: GUID;
20
21 #[doc(hidden)]
22 const UNKNOWN: bool = true;
23
24 /// A reference to the interface's vtable
25 #[doc(hidden)]
26 #[inline(always)]
27 fn vtable(&self) -> &Self::Vtable {
28 // SAFETY: the implementor of the trait guarantees that `Self` is castable to its vtable
29 unsafe { self.assume_vtable::<Self>() }
30 }
31
32 /// Cast this interface as a reference to the supplied interfaces `Vtable`
33 ///
34 /// # Safety
35 ///
36 /// This is safe if `T` is an equivalent interface to `Self` or a super interface.
37 /// In other words, `T::Vtable` must be equivalent to the beginning of `Self::Vtable`.
38 #[doc(hidden)]
39 #[inline(always)]
40 unsafe fn assume_vtable<T: Interface>(&self) -> &T::Vtable {
41 &**(self.as_raw() as *mut *mut T::Vtable)
42 }
43
44 /// Returns the raw COM interface pointer. The resulting pointer continues to be owned by the `Interface` implementation.
45 #[inline(always)]
46 fn as_raw(&self) -> *mut c_void {
47 // SAFETY: implementors of this trait must guarantee that the implementing type has a pointer in-memory representation
48 unsafe { transmute_copy(self) }
49 }
50
51 /// Returns the raw COM interface pointer and releases ownership. It the caller's responsibility to release the COM interface pointer.
52 #[inline(always)]
53 fn into_raw(self) -> *mut c_void {
54 // SAFETY: implementors of this trait must guarantee that the implementing type has a pointer in-memory representation
55 let raw = self.as_raw();
56 forget(self);
57 raw
58 }
59
60 /// Creates an `Interface` by taking ownership of the `raw` COM interface pointer.
61 ///
62 /// # Safety
63 ///
64 /// The `raw` pointer must be owned by the caller and represent a valid COM interface pointer. In other words,
65 /// it must point to a vtable beginning with the `IUnknown` function pointers and match the vtable of `Interface`.
66 unsafe fn from_raw(raw: *mut c_void) -> Self {
67 transmute_copy(&raw)
68 }
69
70 /// Creates an `Interface` that is valid so long as the `raw` COM interface pointer is valid.
71 ///
72 /// # Safety
73 ///
74 /// The `raw` pointer must be a valid COM interface pointer. In other words, it must point to a vtable
75 /// beginning with the `IUnknown` function pointers and match the vtable of `Interface`.
76 #[inline(always)]
77 unsafe fn from_raw_borrowed(raw: &*mut c_void) -> Option<&Self> {
78 if raw.is_null() {
79 None
80 } else {
81 Some(transmute_copy(&raw))
82 }
83 }
84
85 /// Attempts to cast the current interface to another interface using `QueryInterface`.
86 ///
87 /// The name `cast` is preferred to `query` because there is a WinRT method named query but not one
88 /// named cast.
89 #[inline(always)]
90 fn cast<T: Interface>(&self) -> Result<T> {
91 // SAFETY: `result` is valid for writing an interface pointer and it is safe
92 // to cast the `result` pointer as `T` on success because we are using the `IID` tied
93 // to `T` which the implementor of `Interface` has guaranteed is correct
94 unsafe {
95 // If query() returns a failure code then we propagate that failure code to the caller.
96 // In that case, we ignore the contents of 'result' (which will _not_ be dropped,
97 // because MaybeUninit intentionally does not drop its contents).
98 //
99 // This guards against implementations of COM interfaces which may store non-null values
100 // in 'result' but still return E_NOINTERFACE.
101 let mut result = MaybeUninit::<Option<T>>::zeroed();
102 self.query(&T::IID, result.as_mut_ptr() as _).ok()?;
103
104 // If we get here, then query() has succeeded, but we still need to double-check
105 // that the output pointer is non-null.
106 if let Some(obj) = result.assume_init() {
107 Ok(obj)
108 } else {
109 Err(imp::E_POINTER.into())
110 }
111 }
112 }
113
114 /// This casts the given COM interface to [`&dyn Any`].
115 ///
116 /// Applications should generally _not_ call this method directly. Instead, use the
117 /// [`Interface::cast_object_ref`] or [`Interface::cast_object`] methods.
118 ///
119 /// `T` must be a type that has been annotated with `#[implement]`; this is checked at
120 /// compile-time by the generic constraints of this method. However, note that the
121 /// returned `&dyn Any` refers to the _outer_ implementation object that was generated by
122 /// `#[implement]`, i.e. the `MyApp_Impl` type, not the inner `MyApp` type.
123 ///
124 /// If the given object is not a Rust object, or is a Rust object but not `T`, or is a Rust
125 /// object that contains non-static lifetimes, then this function will return `Err(E_NOINTERFACE)`.
126 ///
127 /// # Safety
128 ///
129 /// **IMPORTANT!!** This uses a non-standard protocol for QueryInterface! The `DYNAMIC_CAST_IID`
130 /// IID identifies this protocol, but there is no `IDynamicCast` interface. Instead, objects
131 /// that recognize `DYNAMIC_CAST_IID` simply store their `&dyn Any` directly at the interface
132 /// pointer that was passed to `QueryInterface. This means that the returned value has a
133 /// size that is twice as large (`size_of::<&dyn Any>() == 2 * size_of::<*const c_void>()`).
134 ///
135 /// This means that callers that use this protocol cannot simply pass `&mut ptr` for
136 /// an ordinary single-pointer-sized pointer. Only this method understands this protocol.
137 ///
138 /// Another part of this protocol is that the implementation of `QueryInterface` _does not_
139 /// AddRef the object. The caller must guarantee the liveness of the COM object. In Rust,
140 /// this means tying the lifetime of the IUnknown* that we used for the QueryInterface
141 /// call to the lifetime of the returned `&dyn Any` value.
142 ///
143 /// This method preserves type safety and relies on these invariants:
144 ///
145 /// * All `QueryInterface` implementations that recognize `DYNAMIC_CAST_IID` are generated by
146 /// the `#[implement]` macro and respect the rules described here.
147 #[inline(always)]
148 fn cast_to_any<T>(&self) -> Result<&dyn Any>
149 where
150 T: ComObjectInner,
151 T::Outer: Any + 'static + IUnknownImpl<Impl = T>,
152 {
153 unsafe {
154 let mut any_ref_arg: MaybeUninit<&dyn Any> = MaybeUninit::zeroed();
155 self.query(
156 &DYNAMIC_CAST_IID,
157 any_ref_arg.as_mut_ptr() as *mut *mut c_void,
158 )
159 .ok()?;
160 Ok(any_ref_arg.assume_init())
161 }
162 }
163
164 /// Returns `true` if the given COM interface refers to an implementation of `T`.
165 ///
166 /// `T` must be a type that has been annotated with `#[implement]`; this is checked at
167 /// compile-time by the generic constraints of this method.
168 ///
169 /// If the given object is not a Rust object, or is a Rust object but not `T`, or is a Rust
170 /// object that contains non-static lifetimes, then this function will return `false`.
171 #[inline(always)]
172 fn is_object<T>(&self) -> bool
173 where
174 T: ComObjectInner,
175 T::Outer: Any + 'static + IUnknownImpl<Impl = T>,
176 {
177 if let Ok(any) = self.cast_to_any::<T>() {
178 any.is::<T::Outer>()
179 } else {
180 false
181 }
182 }
183
184 /// This casts the given COM interface to [`&dyn Any`]. It returns a reference to the "outer"
185 /// object, e.g. `&MyApp_Impl`, not the inner `&MyApp` object.
186 ///
187 /// `T` must be a type that has been annotated with `#[implement]`; this is checked at
188 /// compile-time by the generic constraints of this method. However, note that the
189 /// returned `&dyn Any` refers to the _outer_ implementation object that was generated by
190 /// `#[implement]`, i.e. the `MyApp_Impl` type, not the inner `MyApp` type.
191 ///
192 /// If the given object is not a Rust object, or is a Rust object but not `T`, or is a Rust
193 /// object that contains non-static lifetimes, then this function will return `Err(E_NOINTERFACE)`.
194 ///
195 /// The returned value is borrowed. If you need an owned (counted) reference, then use
196 /// [`Interface::cast_object`].
197 #[inline(always)]
198 fn cast_object_ref<T>(&self) -> Result<&T::Outer>
199 where
200 T: ComObjectInner,
201 T::Outer: Any + 'static + IUnknownImpl<Impl = T>,
202 {
203 let any: &dyn Any = self.cast_to_any::<T>()?;
204 if let Some(outer) = any.downcast_ref::<T::Outer>() {
205 Ok(outer)
206 } else {
207 Err(imp::E_NOINTERFACE.into())
208 }
209 }
210
211 /// This casts the given COM interface to [`&dyn Any`]. It returns a reference to the "outer"
212 /// object, e.g. `MyApp_Impl`, not the inner `MyApp` object.
213 ///
214 /// `T` must be a type that has been annotated with `#[implement]`; this is checked at
215 /// compile-time by the generic constraints of this method. However, note that the
216 /// returned `&dyn Any` refers to the _outer_ implementation object that was generated by
217 /// `#[implement]`, i.e. the `MyApp_Impl` type, not the inner `MyApp` type.
218 ///
219 /// If the given object is not a Rust object, or is a Rust object but not `T`, or is a Rust
220 /// object that contains non-static lifetimes, then this function will return `Err(E_NOINTERFACE)`.
221 ///
222 /// The returned value is an owned (counted) reference; this function calls `AddRef` on the
223 /// underlying COM object. If you do not need an owned reference, then you can use the
224 /// [`Interface::cast_object_ref`] method instead, and avoid the cost of `AddRef` / `Release`.
225 #[inline(always)]
226 fn cast_object<T>(&self) -> Result<ComObject<T>>
227 where
228 T: ComObjectInner,
229 T::Outer: Any + 'static + IUnknownImpl<Impl = T>,
230 {
231 let object_ref = self.cast_object_ref::<T>()?;
232 Ok(object_ref.to_object())
233 }
234
235 /// Attempts to create a [`Weak`] reference to this object.
236 fn downgrade(&self) -> Result<Weak<Self>> {
237 self.cast::<imp::IWeakReferenceSource>()
238 .and_then(|source| Weak::downgrade(&source))
239 }
240
241 /// Call `QueryInterface` on this interface
242 ///
243 /// # Safety
244 ///
245 /// `interface` must be a non-null, valid pointer for writing an interface pointer.
246 #[inline(always)]
247 unsafe fn query(&self, iid: *const GUID, interface: *mut *mut c_void) -> HRESULT {
248 if Self::UNKNOWN {
249 (self.assume_vtable::<IUnknown>().QueryInterface)(self.as_raw(), iid, interface)
250 } else {
251 panic!("Non-COM interfaces cannot be queried.")
252 }
253 }
254
255 /// Creates an `InterfaceRef` for this reference. The `InterfaceRef` tracks lifetimes statically,
256 /// and eliminates the need for dynamic reference count adjustments (AddRef/Release).
257 fn to_ref(&self) -> InterfaceRef<'_, Self> {
258 InterfaceRef::from_interface(self)
259 }
260 }
261
262 /// # Safety
263 #[doc(hidden)]
264 pub unsafe fn from_raw_borrowed<T: Interface>(raw: &*mut c_void) -> Option<&T> {
265 T::from_raw_borrowed(raw)
266 }
267
268 /// This has the same memory representation as `IFoo`, but represents a borrowed interface pointer.
269 ///
270 /// This type has no `Drop` impl; it does not AddRef/Release the given interface. However, because
271 /// it has a lifetime parameter, it always represents a non-null pointer to an interface.
272 #[repr(transparent)]
273 pub struct InterfaceRef<'a, I>(NonNull<c_void>, PhantomData<&'a I>);
274
275 impl<'a, I> Copy for InterfaceRef<'a, I> {}
276
277 impl<'a, I> Clone for InterfaceRef<'a, I> {
278 fn clone(&self) -> Self {
279 *self
280 }
281 }
282
283 impl<'a, I: core::fmt::Debug + Interface> core::fmt::Debug for InterfaceRef<'a, I> {
284 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
285 <I as core::fmt::Debug>::fmt(&**self, f)
286 }
287 }
288
289 impl<'a, I: Interface> InterfaceRef<'a, I> {
290 /// Creates an `InterfaceRef` from a raw pointer. _This is extremely dangerous, since there
291 /// is no lifetime tracking at all!_
292 ///
293 /// # Safety
294 /// The caller must guarantee that the `'a` lifetime parameter is bound by context to a correct
295 /// lifetime.
296 #[inline(always)]
297 pub unsafe fn from_raw(ptr: NonNull<c_void>) -> Self {
298 Self(ptr, PhantomData)
299 }
300
301 /// Creates an `InterfaceRef` from an interface reference. This safely associates the lifetime
302 /// of the interface reference with the `'a` parameter of `InterfaceRef`. This allows for
303 /// lifetime checking _without_ calling AddRef/Release on the underlying lifetime, which can
304 /// improve efficiency.
305 #[inline(always)]
306 pub fn from_interface(interface: &I) -> Self {
307 unsafe {
308 // SAFETY: new_unchecked() should be valid because Interface::as_raw should always
309 // return a non-null pointer.
310 Self(NonNull::new_unchecked(interface.as_raw()), PhantomData)
311 }
312 }
313
314 /// Calls AddRef on the underlying COM interface and returns an "owned" (counted) reference.
315 #[inline(always)]
316 pub fn to_owned(self) -> I {
317 (*self).clone()
318 }
319 }
320
321 impl<'a, 'i: 'a, I: Interface> From<&'i I> for InterfaceRef<'a, I> {
322 #[inline(always)]
323 fn from(interface: &'a I) -> InterfaceRef<'a, I> {
324 InterfaceRef::from_interface(interface)
325 }
326 }
327
328 impl<'a, I: Interface> core::ops::Deref for InterfaceRef<'a, I> {
329 type Target = I;
330
331 #[inline(always)]
332 fn deref(&self) -> &I {
333 unsafe { core::mem::transmute(self) }
334 }
335 }
336
337 /// This IID identifies a special protocol, used by [`Interface::cast_to_any`]. This is _not_
338 /// an ordinary COM interface; it uses special lifetime rules and a larger interface pointer.
339 /// See the comments on [`Interface::cast_to_any`].
340 #[doc(hidden)]
341 pub const DYNAMIC_CAST_IID: GUID = GUID::from_u128(0xae49d5cb_143f_431c_874c_2729336e4eca);