Debian Codegraph @

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

raw
1 use super::*;
2 use crate::Interface;
3 use core::ffi::c_void;
4 use core::marker::PhantomData;
5 use core::mem::{forget, transmute, transmute_copy};
6 use core::ptr::null_mut;
7 use core::sync::atomic::{AtomicPtr, Ordering};
8
9 pub struct FactoryCache<C, I> {
10 shared: AtomicPtr<c_void>,
11 _c: PhantomData<C>,
12 _i: PhantomData<I>,
13 }
14
15 impl<C, I> FactoryCache<C, I> {
16 pub const fn new() -> Self {
17 Self {
18 shared: AtomicPtr::new(null_mut()),
19 _c: PhantomData,
20 _i: PhantomData,
21 }
22 }
23 }
24
25 impl<C, I> Default for FactoryCache<C, I> {
26 fn default() -> Self {
27 Self::new()
28 }
29 }
30
31 impl<C: crate::RuntimeName, I: Interface> FactoryCache<C, I> {
32 pub fn call<R, F: FnOnce(&I) -> crate::Result<R>>(&self, callback: F) -> crate::Result<R> {
33 loop {
34 // Attempt to load a previously cached factory pointer.
35 let ptr = self.shared.load(Ordering::Relaxed);
36
37 // If a pointer is found, the cache is primed and we're good to go.
38 if !ptr.is_null() {
39 return callback(unsafe { transmute::<&*mut c_void, &I>(&ptr) });
40 }
41
42 // Otherwise, we load the factory the usual way.
43 let factory = factory::<C, I>()?;
44
45 // If the factory is agile, we can safely cache it.
46 if factory.cast::<IAgileObject>().is_ok() {
47 if self
48 .shared
49 .compare_exchange_weak(
50 null_mut(),
51 factory.as_raw(),
52 Ordering::Relaxed,
53 Ordering::Relaxed,
54 )
55 .is_ok()
56 {
57 forget(factory);
58 }
59 } else {
60 // Otherwise, for non-agile factories we simply use the factory
61 // and discard after use as it is not safe to cache.
62 return callback(&factory);
63 }
64 }
65 }
66 }
67
68 // This is safe because `FactoryCache` only holds agile factory pointers, which are safe to cache and share between threads.
69 unsafe impl<C, I> Sync for FactoryCache<C, I> {}
70
71 /// Attempts to load the factory object for the given WinRT class.
72 /// This can be used to access COM interfaces implemented on a Windows Runtime class factory.
73 pub fn factory<C: crate::RuntimeName, I: Interface>() -> crate::Result<I> {
74 let mut factory: Option<I> = None;
75 let name = crate::HSTRING::from(C::NAME);
76
77 let code = unsafe {
78 let mut get_com_factory = || {
79 crate::HRESULT(RoGetActivationFactory(
80 transmute_copy(&name),
81 &I::IID as *const _ as _,
82 &mut factory as *mut _ as *mut _,
83 ))
84 };
85 let mut code = get_com_factory();
86
87 // If RoGetActivationFactory fails because combase hasn't been loaded yet then load combase
88 // automatically so that it "just works" for apartment-agnostic code.
89 if code == CO_E_NOTINITIALIZED {
90 let mut cookie = core::ptr::null_mut();
91 CoIncrementMTAUsage(&mut cookie);
92
93 // Now try a second time to get the activation factory via the OS.
94 code = get_com_factory();
95 }
96
97 code
98 };
99
100 // If this succeeded then return the resulting factory interface.
101 if let Some(factory) = factory {
102 return Ok(factory);
103 }
104
105 // If not, first capture the error information from the failure above so that we
106 // can ultimately return this error information if all else fails.
107 let original: crate::Error = code.into();
108
109 // Now attempt to find the factory's implementation heuristically.
110 if let Some(i) = search_path(C::NAME, |library| unsafe {
111 get_activation_factory(library, &name)
112 }) {
113 i.cast()
114 } else {
115 Err(original)
116 }
117 }
118
119 // Remove the suffix until a match is found appending `.dll\0` at the end
120 ///
121 /// For example, if the class name is
122 /// "A.B.TypeName" then the attempted load order will be:
123 /// 1. A.B.dll
124 /// 2. A.dll
125 fn search_path<F, R>(mut path: &str, mut callback: F) -> Option<R>
126 where
127 F: FnMut(crate::PCSTR) -> crate::Result<R>,
128 {
129 let suffix = b".dll\0";
130 let mut library = alloc::vec![0; path.len() + suffix.len()];
131 while let Some(pos) = path.rfind('.') {
132 path = &path[..pos];
133 library.truncate(path.len() + suffix.len());
134 library[..path.len()].copy_from_slice(path.as_bytes());
135 library[path.len()..].copy_from_slice(suffix);
136
137 if let Ok(r) = callback(crate::PCSTR::from_raw(library.as_ptr())) {
138 return Some(r);
139 }
140 }
141
142 None
143 }
144
145 unsafe fn get_activation_factory(
146 library: crate::PCSTR,
147 name: &crate::HSTRING,
148 ) -> crate::Result<IGenericFactory> {
149 let function =
150 delay_load::<DllGetActivationFactory>(library, crate::s!("DllGetActivationFactory"))
151 .ok_or_else(crate::Error::from_win32)?;
152 let mut abi = null_mut();
153 function(transmute_copy(name), &mut abi).and_then(|| crate::Type::from_abi(abi))
154 }
155
156 unsafe fn delay_load<T>(library: crate::PCSTR, function: crate::PCSTR) -> Option<T> {
157 let library = LoadLibraryExA(
158 library.0,
159 core::ptr::null_mut(),
160 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS,
161 );
162
163 if library.is_null() {
164 return None;
165 }
166
167 let address = GetProcAddress(library, function.0);
168
169 if address.is_some() {
170 return Some(core::mem::transmute_copy(&address));
171 }
172
173 FreeLibrary(library);
174 None
175 }
176
177 type DllGetActivationFactory =
178 extern "system" fn(name: *mut c_void, factory: *mut *mut c_void) -> crate::HRESULT;
179
180 #[cfg(test)]
181 mod tests {
182 use super::*;
183
184 #[test]
185 fn dll_search() {
186 let path = "A.B.TypeName";
187
188 // Test library successfully found
189 let mut results = Vec::new();
190 let end_result = search_path(path, |library| {
191 results.push(unsafe { library.to_string().unwrap() });
192 if unsafe { library.as_bytes() } == &b"A.dll"[..] {
193 Ok(42)
194 } else {
195 Err(crate::Error::empty())
196 }
197 });
198 assert!(matches!(end_result, Some(42)));
199 assert_eq!(results, vec!["A.B.dll", "A.dll"]);
200
201 // Test library never successfully found
202 let mut results = Vec::new();
203 let end_result = search_path(path, |library| {
204 results.push(unsafe { library.to_string().unwrap() });
205 crate::Result::<()>::Err(crate::Error::empty())
206 });
207 assert!(end_result.is_none());
208 assert_eq!(results, vec!["A.B.dll", "A.dll"]);
209 }
210 }