glib_win32/functions.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2#[cfg(any(windows, docsrs))]
3use glib::translate::*;
4#[cfg(any(windows, docsrs))]
5use std::path::PathBuf;
6
7#[cfg(any(windows, docsrs))]
8use crate::ffi;
9
10#[cfg(windows)]
11use std::os::windows::raw::HANDLE;
12#[cfg(all(unix, docsrs))]
13pub type HANDLE = *mut std::os::raw::c_void;
14
15#[doc(alias = "g_win32_get_package_installation_directory_of_module")]
16#[doc(alias = "get_package_installation_directory_of_module")]
17#[cfg(any(windows, docsrs))]
18pub fn package_installation_directory_of_module(
19 hmodule: HANDLE,
20) -> Result<PathBuf, std::io::Error> {
21 // # Safety
22 // The underlying `GetModuleFilenameW` function has three possible
23 // outcomes when a raw pointer get passed to it:
24 // - When the pointer is a valid HINSTANCE of a DLL (e.g. acquired
25 // through the `GetModuleHandleW`), it sets a file path to the
26 // assigned "out" buffer and sets the return value to be the length
27 // of said path string
28 // - When the pointer is null, it sets the full path of the process'
29 // executable binary to the assigned buffer and sets the return value
30 // to be the length of said string
31 // - Whenever the provided buffer size is too small, it will set a
32 // truncated version of the path and return the length of said string
33 // while also setting the thread-local last-error code to
34 // `ERROR_INSUFFICIENT_BUFFER` (evaluates to 0x7A)
35 // - When the pointer is not a valid HINSTANCE that isn't NULL (e.g.
36 // a pointer to some GKeyFile), it will return 0 and set the last-error
37 // code to `ERROR_MOD_NOT_FOUND` (evaluates to 0x7E)
38 //
39 // The `g_win32_get_package_installation_directory_of_module` already
40 // handles all of the outcomes gracefully by:
41 // - Preallocating a MAX_PATH-long array of wchar_t for the out buffer,
42 // so that outcome #3 can be safely assumed to never happen
43 // - Returning NULL when outcome #4 happens
44 match unsafe {
45 from_glib_full::<_, Option<PathBuf>>(
46 ffi::g_win32_get_package_installation_directory_of_module(hmodule),
47 )
48 } {
49 Some(pb) => Ok(pb),
50 None => Err(std::io::Error::last_os_error()),
51 }
52}