| 1 |
// Licensed under the Apache License, Version 2.0 |
| 2 |
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. |
| 4 |
// All files in the project carrying such notice may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
//! Utilities and wrappers for Microsoft COM interfaces in Windows. |
| 8 |
//! |
| 9 |
//! This works with the `Class` and `Interface` traits from the `winapi` crate. |
| 10 |
|
| 11 |
use std::marker::PhantomData; |
| 12 |
use std::mem; |
| 13 |
use std::ops::Deref; |
| 14 |
use std::ptr::{self, null_mut, NonNull}; |
| 15 |
use std::rc::Rc; |
| 16 |
use std::slice; |
| 17 |
|
| 18 |
use winapi::shared::minwindef::LPVOID; |
| 19 |
use winapi::shared::{ |
| 20 |
winerror::HRESULT, |
| 21 |
wtypesbase::{CLSCTX, CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER}, |
| 22 |
}; |
| 23 |
use winapi::um::{ |
| 24 |
combaseapi::{CoCreateInstance, CoInitializeEx, CoTaskMemFree, CoUninitialize}, |
| 25 |
objbase::{COINIT_APARTMENTTHREADED, COINIT_MULTITHREADED}, |
| 26 |
unknwnbase::IUnknown, |
| 27 |
}; |
| 28 |
use winapi::{Class, Interface}; |
| 29 |
|
| 30 |
use check_succeeded; |
| 31 |
use error::{succeeded_or_err, HResult, ResultExt}; |
| 32 |
|
| 33 |
/// Wrap COM interfaces sanely |
| 34 |
/// |
| 35 |
/// Originally from [wio-rs](https://github.com/retep998/wio-rs) `ComPtr` |
| 36 |
#[repr(transparent)] |
| 37 |
pub struct ComRef<T>(NonNull<T>) |
| 38 |
where |
| 39 |
T: Interface; |
| 40 |
impl<T> ComRef<T> |
| 41 |
where |
| 42 |
T: Interface, |
| 43 |
{ |
| 44 |
/// Creates a `ComRef` to wrap a raw pointer. |
| 45 |
/// It takes ownership over the pointer which means it does __not__ call `AddRef`. |
| 46 |
/// `T` __must__ be a COM interface that inherits from `IUnknown`. |
| 47 |
pub unsafe fn from_raw(ptr: NonNull<T>) -> ComRef<T> { |
| 48 |
ComRef(ptr) |
| 49 |
} |
| 50 |
|
| 51 |
/// Casts up the inheritance chain |
| 52 |
pub fn up<U>(self) -> ComRef<U> |
| 53 |
where |
| 54 |
T: Deref<Target = U>, |
| 55 |
U: Interface, |
| 56 |
{ |
| 57 |
unsafe { ComRef::from_raw(NonNull::new(self.into_raw().as_ptr() as *mut U).unwrap()) } |
| 58 |
} |
| 59 |
|
| 60 |
/// Extracts the raw pointer. |
| 61 |
/// You are now responsible for releasing it yourself. |
| 62 |
pub fn into_raw(self) -> NonNull<T> { |
| 63 |
let p = self.0; |
| 64 |
mem::forget(self); |
| 65 |
p |
| 66 |
} |
| 67 |
|
| 68 |
fn as_unknown(&self) -> &IUnknown { |
| 69 |
unsafe { &*(self.as_raw_ptr() as *mut IUnknown) } |
| 70 |
} |
| 71 |
|
| 72 |
/// Get another interface via `QueryInterface`. |
| 73 |
/// |
| 74 |
/// If the call to `QueryInterface` fails or the resulting interface is null, return an error. |
| 75 |
pub fn cast<U>(&self) -> Result<ComRef<U>, HResult> |
| 76 |
where |
| 77 |
U: Interface, |
| 78 |
{ |
| 79 |
let mut obj = null_mut(); |
| 80 |
let hr = |
| 81 |
succeeded_or_err(unsafe { self.as_unknown().QueryInterface(&U::uuidof(), &mut obj) })?; |
| 82 |
NonNull::new(obj as *mut U) |
| 83 |
.map(|obj| unsafe { ComRef::from_raw(obj) }) |
| 84 |
.ok_or_else(|| HResult::new(hr).function("IUnknown::QueryInterface")) |
| 85 |
} |
| 86 |
|
| 87 |
/// Obtains the raw pointer without transferring ownership. |
| 88 |
/// |
| 89 |
/// Do __not__ release this pointer because it is still owned by the `ComRef`. |
| 90 |
/// |
| 91 |
/// Do __not__ use this pointer beyond the lifetime of the `ComRef`. |
| 92 |
pub fn as_raw(&self) -> NonNull<T> { |
| 93 |
self.0 |
| 94 |
} |
| 95 |
|
| 96 |
/// Obtains the raw pointer without transferring ownership. |
| 97 |
/// |
| 98 |
/// Do __not__ release this pointer because it is still owned by the `ComRef`. |
| 99 |
/// |
| 100 |
/// Do __not__ use this pointer beyond the lifetime of the `ComRef`. |
| 101 |
pub fn as_raw_ptr(&self) -> *mut T { |
| 102 |
self.0.as_ptr() |
| 103 |
} |
| 104 |
} |
| 105 |
impl<T> Deref for ComRef<T> |
| 106 |
where |
| 107 |
T: Interface, |
| 108 |
{ |
| 109 |
type Target = T; |
| 110 |
fn deref(&self) -> &T { |
| 111 |
unsafe { &*self.as_raw_ptr() } |
| 112 |
} |
| 113 |
} |
| 114 |
impl<T> Clone for ComRef<T> |
| 115 |
where |
| 116 |
T: Interface, |
| 117 |
{ |
| 118 |
fn clone(&self) -> Self { |
| 119 |
unsafe { |
| 120 |
self.as_unknown().AddRef(); |
| 121 |
ComRef::from_raw(self.as_raw()) |
| 122 |
} |
| 123 |
} |
| 124 |
} |
| 125 |
impl<T> Drop for ComRef<T> |
| 126 |
where |
| 127 |
T: Interface, |
| 128 |
{ |
| 129 |
fn drop(&mut self) { |
| 130 |
unsafe { |
| 131 |
self.as_unknown().Release(); |
| 132 |
} |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
/// A scope for automatic COM initialization and deinitialization. |
| 137 |
/// |
| 138 |
/// Functions that need COM initialized can take a `&ComApartmentScope` argument and be sure that |
| 139 |
/// it is so. It's recommended to use a thread local for this through the |
| 140 |
/// [`INIT_MTA`](constant.INIT_MTA.html) or [`INIT_STA`](constant.INIT_STA.html) statics. |
| 141 |
#[derive(Debug, Default)] |
| 142 |
pub struct ComApartmentScope { |
| 143 |
/// PhantomData used in lieu of unstable impl !Send + !Sync. |
| 144 |
/// It must be dropped on the same thread it was created on so it can't be Send, |
| 145 |
/// and references are meant to indicate that COM has been inited on the current thread so it |
| 146 |
/// can't be Sync. |
| 147 |
_do_not_send: PhantomData<Rc<()>>, |
| 148 |
} |
| 149 |
|
| 150 |
impl ComApartmentScope { |
| 151 |
/// This thread should be the sole occupant of a single thread apartment |
| 152 |
pub fn init_sta() -> Result<Self, HResult> { |
| 153 |
unsafe { check_succeeded!(CoInitializeEx(ptr::null_mut(), COINIT_APARTMENTTHREADED)) }?; |
| 154 |
|
| 155 |
Ok(Default::default()) |
| 156 |
} |
| 157 |
|
| 158 |
/// This thread should join the process's multithreaded apartment |
| 159 |
pub fn init_mta() -> Result<Self, HResult> { |
| 160 |
unsafe { check_succeeded!(CoInitializeEx(ptr::null_mut(), COINIT_MULTITHREADED)) }?; |
| 161 |
|
| 162 |
Ok(Default::default()) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
impl Drop for ComApartmentScope { |
| 167 |
fn drop(&mut self) { |
| 168 |
unsafe { |
| 169 |
CoUninitialize(); |
| 170 |
} |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
thread_local! { |
| 175 |
// TODO these examples should probably be in convenience functions. |
| 176 |
/// A single thread apartment scope for the duration of the current thread. |
| 177 |
/// |
| 178 |
/// # Example |
| 179 |
/// ``` |
| 180 |
/// use comedy::com::{ComApartmentScope, INIT_STA}; |
| 181 |
/// |
| 182 |
/// fn do_com_stuff(_com: &ComApartmentScope) { |
| 183 |
/// } |
| 184 |
/// |
| 185 |
/// INIT_STA.with(|com| { |
| 186 |
/// let com = match com { |
| 187 |
/// Err(e) => return Err(e.clone()), |
| 188 |
/// Ok(ref com) => com, |
| 189 |
/// }; |
| 190 |
/// do_com_stuff(com); |
| 191 |
/// Ok(()) |
| 192 |
/// }).unwrap() |
| 193 |
/// ``` |
| 194 |
pub static INIT_STA: Result<ComApartmentScope, HResult> = ComApartmentScope::init_sta(); |
| 195 |
|
| 196 |
/// A multithreaded apartment scope for the duration of the current thread. |
| 197 |
/// |
| 198 |
/// # Example |
| 199 |
/// ``` |
| 200 |
/// use comedy::com::{ComApartmentScope, INIT_MTA}; |
| 201 |
/// |
| 202 |
/// fn do_com_stuff(_com: &ComApartmentScope) { |
| 203 |
/// } |
| 204 |
/// |
| 205 |
/// INIT_MTA.with(|com| { |
| 206 |
/// let com = match com { |
| 207 |
/// Err(e) => return Err(e.clone()), |
| 208 |
/// Ok(ref com) => com, |
| 209 |
/// }; |
| 210 |
/// do_com_stuff(com); |
| 211 |
/// Ok(()) |
| 212 |
/// }).unwrap() |
| 213 |
/// ``` |
| 214 |
pub static INIT_MTA: Result<ComApartmentScope, HResult> = ComApartmentScope::init_mta(); |
| 215 |
} |
| 216 |
|
| 217 |
/// Create an instance of a COM class. |
| 218 |
/// |
| 219 |
/// This is mostly just a call to `CoCreateInstance` with some error handling. |
| 220 |
/// The CLSID of the class and the IID of the interface come from the winapi `RIDL` macro, which |
| 221 |
/// defines `Class` and `Interface` implementations. |
| 222 |
/// |
| 223 |
/// [`create_instance_local_server`](fn.create_instance_local_server.html) and |
| 224 |
/// [`create_instance_inproc_server`](fn.create_instance_inproc_server.html) are convenience |
| 225 |
/// functions for typical contexts. |
| 226 |
pub fn create_instance<C, I>(ctx: CLSCTX) -> Result<ComRef<I>, HResult> |
| 227 |
where |
| 228 |
C: Class, |
| 229 |
I: Interface, |
| 230 |
{ |
| 231 |
get(|interface| unsafe { |
| 232 |
CoCreateInstance( |
| 233 |
&C::uuidof(), |
| 234 |
ptr::null_mut(), // pUnkOuter |
| 235 |
ctx, |
| 236 |
&I::uuidof(), |
| 237 |
interface as *mut *mut _, |
| 238 |
) |
| 239 |
}) |
| 240 |
.function("CoCreateInstance") |
| 241 |
} |
| 242 |
|
| 243 |
/// Create an instance of a COM class in the current process (`CLSCTX_LOCAL_SERVER`). |
| 244 |
pub fn create_instance_local_server<C, I>() -> Result<ComRef<I>, HResult> |
| 245 |
where |
| 246 |
C: Class, |
| 247 |
I: Interface, |
| 248 |
{ |
| 249 |
create_instance::<C, I>(CLSCTX_LOCAL_SERVER) |
| 250 |
} |
| 251 |
|
| 252 |
/// Create an instance of a COM class in a separate process space on the same machine |
| 253 |
/// (`CLSCTX_INPROC_SERVER`). |
| 254 |
pub fn create_instance_inproc_server<C, I>() -> Result<ComRef<I>, HResult> |
| 255 |
where |
| 256 |
C: Class, |
| 257 |
I: Interface, |
| 258 |
{ |
| 259 |
create_instance::<C, I>(CLSCTX_INPROC_SERVER) |
| 260 |
} |
| 261 |
|
| 262 |
/// Call a COM method, returning a `Result`. |
| 263 |
/// |
| 264 |
/// An error is returned if the call fails. The error is augmented with the name of the interface |
| 265 |
/// and method, and the file name and line number of the macro usage. |
| 266 |
/// |
| 267 |
/// `QueryInterface` is not used, the receiving interface must already be the given type. |
| 268 |
/// |
| 269 |
/// # Example |
| 270 |
/// |
| 271 |
/// ```no_run |
| 272 |
/// # extern crate winapi; |
| 273 |
/// # |
| 274 |
/// # use winapi::um::bits::IBackgroundCopyJob; |
| 275 |
/// # |
| 276 |
/// # use comedy::com::ComRef; |
| 277 |
/// # use comedy::{com_call, HResult}; |
| 278 |
/// # |
| 279 |
/// fn cancel_job(job: &ComRef<IBackgroundCopyJob>) -> Result<(), HResult> { |
| 280 |
/// unsafe { |
| 281 |
/// com_call!(job, IBackgroundCopyJob::Cancel())?; |
| 282 |
/// } |
| 283 |
/// Ok(()) |
| 284 |
/// } |
| 285 |
/// ``` |
| 286 |
#[macro_export] |
| 287 |
macro_rules! com_call { |
| 288 |
($obj:expr, $interface:ident :: $method:ident ( $($arg:expr),* )) => {{ |
| 289 |
use $crate::error::ResultExt; |
| 290 |
$crate::error::succeeded_or_err({ |
| 291 |
let obj: &$interface = &*$obj; |
| 292 |
obj.$method($($arg),*) |
| 293 |
}).function(concat!(stringify!($interface), "::", stringify!($method))) |
| 294 |
.file_line(file!(), line!()) |
| 295 |
}}; |
| 296 |
|
| 297 |
// support for trailing comma in method argument list |
| 298 |
($obj:expr, $interface:ident :: $method:ident ( $($arg:expr),+ , )) => {{ |
| 299 |
$crate::com_call!($obj, $interface::$method($($arg),+)) |
| 300 |
}}; |
| 301 |
} |
| 302 |
|
| 303 |
/// Get an interface pointer that is returned through an output parameter. |
| 304 |
/// |
| 305 |
/// If the call returns a failure `HRESULT`, return an error. |
| 306 |
/// |
| 307 |
/// |
| 308 |
/// # Null and Enumerators |
| 309 |
/// If the method succeeds but the resulting interface pointer is null, this will return an |
| 310 |
/// `HResult` error with the successful return code. In particular this can happen with |
| 311 |
/// enumeration interfaces, which return `S_FALSE` when they write less than the requested number |
| 312 |
/// of results. |
| 313 |
pub fn get<I, F>(getter: F) -> Result<ComRef<I>, HResult> |
| 314 |
where |
| 315 |
I: Interface, |
| 316 |
F: FnOnce(*mut *mut I) -> HRESULT, |
| 317 |
{ |
| 318 |
let mut interface: *mut I = ptr::null_mut(); |
| 319 |
|
| 320 |
let hr = succeeded_or_err(getter(&mut interface as *mut *mut I))?; |
| 321 |
|
| 322 |
NonNull::new(interface) |
| 323 |
.map(|interface| unsafe { ComRef::from_raw(interface) }) |
| 324 |
.ok_or_else(|| HResult::new(hr)) |
| 325 |
} |
| 326 |
|
| 327 |
/// Call a COM method, create a [`ComRef`](com/struct.ComRef.html) from an output parameter. |
| 328 |
/// |
| 329 |
/// An error is returned if the call fails. The error is augmented with the name of the interface |
| 330 |
/// and method, and the file name and line number of the macro usage. |
| 331 |
/// |
| 332 |
/// # Null and Enumerators |
| 333 |
/// If the method succeeds but the resulting interface pointer is null, this will return an |
| 334 |
/// `HResult` error with the successful return code. In particular this can happen with |
| 335 |
/// enumeration interfaces, which return `S_FALSE` when they write less than the requested number |
| 336 |
/// of results. |
| 337 |
/// |
| 338 |
/// # Example |
| 339 |
/// |
| 340 |
/// ```no_run |
| 341 |
/// # extern crate winapi; |
| 342 |
/// # use winapi::shared::guiddef::GUID; |
| 343 |
/// # use winapi::um::bits::{IBackgroundCopyManager, IBackgroundCopyJob}; |
| 344 |
/// # use comedy::com::ComRef; |
| 345 |
/// # use comedy::{com_call_getter, HResult}; |
| 346 |
/// |
| 347 |
/// fn create_job(bcm: &ComRef<IBackgroundCopyManager>, id: &GUID) |
| 348 |
/// -> Result<ComRef<IBackgroundCopyJob>, HResult> |
| 349 |
/// { |
| 350 |
/// unsafe { |
| 351 |
/// com_call_getter!( |
| 352 |
/// |job| bcm, |
| 353 |
/// IBackgroundCopyManager::GetJob(id, job) |
| 354 |
/// ) |
| 355 |
/// } |
| 356 |
/// } |
| 357 |
/// ``` |
| 358 |
#[macro_export] |
| 359 |
macro_rules! com_call_getter { |
| 360 |
(| $outparam:ident | $obj:expr, $interface:ident :: $method:ident ( $($arg:expr),* )) => {{ |
| 361 |
use $crate::error::ResultExt; |
| 362 |
let obj: &$interface = &*$obj; |
| 363 |
$crate::com::get(|$outparam| { |
| 364 |
obj.$method($($arg),*) |
| 365 |
}).function(concat!(stringify!($interface), "::", stringify!($method))) |
| 366 |
.file_line(file!(), line!()) |
| 367 |
}}; |
| 368 |
|
| 369 |
// support for trailing comma in method argument list |
| 370 |
(| $outparam:ident | $obj:expr, $interface:ident :: $method:ident ( $($arg:expr),+ , )) => { |
| 371 |
$crate::com_call_getter!(|$outparam| $obj, $interface::$method($($arg),+)) |
| 372 |
}; |
| 373 |
} |
| 374 |
|
| 375 |
/// Get a task memory pointer that is returned through an output parameter. |
| 376 |
/// |
| 377 |
/// If the call returns a failure `HRESULT`, return an error. |
| 378 |
/// |
| 379 |
/// # Null |
| 380 |
/// If the method succeeds but the resulting pointer is null, this will return an |
| 381 |
/// `Err(HResult)` with the successful return code. |
| 382 |
pub fn get_cotaskmem<F, T>(getter: F) -> Result<CoTaskMem<T>, HResult> |
| 383 |
where |
| 384 |
F: FnOnce(*mut *mut T) -> HRESULT, |
| 385 |
{ |
| 386 |
let mut ptr = ptr::null_mut() as *mut T; |
| 387 |
|
| 388 |
let hr = succeeded_or_err(getter(&mut ptr))?; |
| 389 |
|
| 390 |
NonNull::new(ptr) |
| 391 |
.map(|ptr| unsafe { CoTaskMem::new(ptr) }) |
| 392 |
.ok_or_else(|| HResult::new(hr)) |
| 393 |
} |
| 394 |
|
| 395 |
/// Call a COM method, create a [`CoTaskMem`](handle/struct.CoTaskMem.html) from an output |
| 396 |
/// parameter. |
| 397 |
/// |
| 398 |
/// An error is returned if the call fails or if the pointer is null. The error is augmented with |
| 399 |
/// the name of the interface and method, and the file name and line number of the macro usage. |
| 400 |
/// |
| 401 |
/// # Null |
| 402 |
/// If the method succeeds but the resulting pointer is null, this will return an `HResult` |
| 403 |
/// error with the successful return code. |
| 404 |
/// |
| 405 |
/// # Example |
| 406 |
/// |
| 407 |
/// ```no_run |
| 408 |
/// # extern crate winapi; |
| 409 |
/// # use winapi::shared::winerror::HRESULT; |
| 410 |
/// # use winapi::um::bits::IBackgroundCopyManager; |
| 411 |
/// # use comedy::com::{ComRef, CoTaskMem}; |
| 412 |
/// # use comedy::{com_call_taskmem_getter, HResult}; |
| 413 |
/// # |
| 414 |
/// fn get_error_description(bcm: &ComRef<IBackgroundCopyManager>, lang_id: u32, hr: HRESULT) |
| 415 |
/// -> Result<CoTaskMem<u16>, HResult> |
| 416 |
/// { |
| 417 |
/// unsafe { |
| 418 |
/// com_call_taskmem_getter!( |
| 419 |
/// |desc| bcm, |
| 420 |
/// IBackgroundCopyManager::GetErrorDescription(hr, lang_id, desc) |
| 421 |
/// ) |
| 422 |
/// } |
| 423 |
/// } |
| 424 |
/// ``` |
| 425 |
#[macro_export] |
| 426 |
macro_rules! com_call_taskmem_getter { |
| 427 |
(| $outparam:ident | $obj:expr, $interface:ident :: $method:ident ( $($arg:expr),* )) => {{ |
| 428 |
use $crate::error::ResultExt; |
| 429 |
$crate::com::get_cotaskmem(|$outparam| { |
| 430 |
$obj.$method($($arg),*) |
| 431 |
}).function(concat!(stringify!($interface), "::", stringify!($method))) |
| 432 |
.file_line(file!(), line!()) |
| 433 |
}}; |
| 434 |
|
| 435 |
// support for trailing comma in method argument list |
| 436 |
(| $outparam:ident | $obj:expr, $interface:ident :: $method:ident ( $($arg:expr),+ , )) => { |
| 437 |
$crate::com_call_taskmem_getter!(|$outparam| $obj, $interface::$method($($arg),+)) |
| 438 |
}; |
| 439 |
} |
| 440 |
|
| 441 |
/// A Windows COM task memory pointer that will be automatically freed. |
| 442 |
// I have only found this useful with strings, so that is the only access provided here by |
| 443 |
// `as_slice_until_null()`. `Deref<Target=T>` would not be generally useful as task memory |
| 444 |
// is usually encountered as variable length structures. |
| 445 |
#[repr(transparent)] |
| 446 |
#[derive(Debug)] |
| 447 |
pub struct CoTaskMem<T>(NonNull<T>); |
| 448 |
|
| 449 |
impl<T> CoTaskMem<T> { |
| 450 |
/// Take ownership of COM task memory, which will be freed with `CoTaskMemFree()` upon drop. |
| 451 |
/// |
| 452 |
/// # Safety |
| 453 |
/// |
| 454 |
/// `p` should be the only copy of the pointer. |
| 455 |
pub unsafe fn new(p: NonNull<T>) -> CoTaskMem<T> { |
| 456 |
CoTaskMem(p) |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
impl<T> Drop for CoTaskMem<T> { |
| 461 |
fn drop(&mut self) { |
| 462 |
unsafe { |
| 463 |
CoTaskMemFree(self.0.as_ptr() as LPVOID); |
| 464 |
} |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
impl CoTaskMem<u16> { |
| 469 |
/// Interpret as a null-terminated `u16` array, return as a slice without terminator. |
| 470 |
pub unsafe fn as_slice_until_null(&self) -> &[u16] { |
| 471 |
for i in 0.. { |
| 472 |
if *self.0.as_ptr().offset(i) == 0 { |
| 473 |
return slice::from_raw_parts(self.0.as_ptr(), i as usize); |
| 474 |
} |
| 475 |
} |
| 476 |
unreachable!() |
| 477 |
} |
| 478 |
} |