Skip to main content
QAROS Rust API Dev (main) · versions: Dev (main) · Developer Guide

qaros_sys/
platform.rs

1//! What the loader needs from the operating system: opening a library with the runtime's
2//! search rules, the module an address belongs to, and the places of the default lookup.
3
4use std::ffi::c_void;
5use std::path::{Path, PathBuf};
6
7use crate::lookup::{INSTANCE_VARIABLE, RuntimeLocator, SearchPath};
8
9/// The value of `QAR_INSTANCE`, exactly as set, when it is set and not empty (read lossily when
10/// it is not Unicode, which no instance name is). The default lookup reads it on Windows only.
11pub fn requested_instance() -> Option<String> {
12    std::env::var_os(INSTANCE_VARIABLE)
13        .filter(|value| !value.is_empty())
14        .map(|value| value.to_string_lossy().into_owned())
15}
16
17/// The folder holding the runtime of QAROS instance `instance`, as step 2 of the default lookup
18/// picks it: for `default` the installed QAROS's `<InstallFolder>\bin` ([`installed_bin_folder`]);
19/// for any other name the fully qualified value `RuntimeFolder` of
20/// `HKCU\SOFTWARE\Quaternar\QAROS\Instances\<name>`, which a QAROS development hub writes for
21/// the apps it starts, else that record's fully qualified `<InstallFolder>\bin`. `None` when the
22/// name is not valid ([`crate::is_valid_instance_name`]), no folder is recorded, or outside
23/// Windows, which has no instance records.
24pub fn instance_runtime_folder(instance: &str) -> Option<PathBuf> {
25    if !cfg!(windows) {
26        return None;
27    }
28    crate::lookup::instance_runtime_folder(&SystemLocator, instance)
29}
30
31/// `<InstallFolder>\bin` of the QAROS installed on this PC, read from
32/// `HKLM\SOFTWARE\Quaternar\QAROS`. `None` when QAROS is not installed, and always outside
33/// Windows.
34pub fn installed_bin_folder() -> Option<PathBuf> {
35    os::install_folder().map(|folder| folder.join("bin"))
36}
37
38/// Opens the library file at `path` the way every QAROS binding does: from its absolute path,
39/// with its dependencies resolved from its own folder and System32 only, never from the
40/// application's folder or the current directory.
41///
42/// # Safety
43///
44/// Opening a library runs its initialization code.
45pub(crate) unsafe fn open_library_file(path: &Path) -> Result<libloading::Library, String> {
46    let absolute_path = std::path::absolute(path)
47        .map_err(|error| format!("cannot make {} absolute: {error}", path.display()))?;
48    // SAFETY: forwarded to the caller.
49    unsafe { os::open_with_runtime_search_rules(&absolute_path) }
50        .map_err(|error| describe_open_error(&error))
51}
52
53/// libloading's message for a failed open omits the operating system's reason (for example a
54/// missing dependent DLL), which sits in its source.
55fn describe_open_error(error: &libloading::Error) -> String {
56    match std::error::Error::source(error) {
57        Some(reason) => format!("{error}: {reason}"),
58        None => error.to_string(),
59    }
60}
61
62/// The file of the module (executable or library) that contains `address`.
63pub(crate) fn module_path_containing(address: *const c_void) -> Option<PathBuf> {
64    os::module_path_containing(address)
65}
66
67/// The real process, environment and file system.
68pub(crate) struct SystemLocator;
69
70impl RuntimeLocator for SystemLocator {
71    type Library = libloading::Library;
72
73    fn already_loaded(&self) -> Option<libloading::Library> {
74        os::open_already_loaded(crate::LIBRARY_FILE_NAME)
75    }
76
77    fn binding_folder(&self) -> Option<PathBuf> {
78        let address_in_this_module = module_path_containing as *const c_void;
79        module_path_containing(address_in_this_module)?
80            .parent()
81            .map(Path::to_path_buf)
82    }
83
84    fn requested_instance(&self) -> Option<String> {
85        // Outside Windows there are no instance records, and the C loader does not read the
86        // variable either.
87        if cfg!(windows) {
88            requested_instance()
89        } else {
90            None
91        }
92    }
93
94    fn instance_record_value(&self, instance: &str, value: &str) -> Option<String> {
95        os::instance_record_value(instance, value)
96    }
97
98    fn installed_bin_folder(&self) -> Option<PathBuf> {
99        installed_bin_folder()
100    }
101
102    fn search_path(&self) -> SearchPath {
103        if cfg!(windows) {
104            SearchPath::Folders(
105                std::env::var_os("PATH")
106                    .map(|path_value| crate::lookup::search_path_folders(&path_value))
107                    .unwrap_or_default(),
108            )
109        } else {
110            SearchPath::DynamicLinker
111        }
112    }
113
114    fn is_file(&self, path: &Path) -> bool {
115        path.is_file()
116    }
117
118    fn load(&self, path: &Path) -> Result<libloading::Library, String> {
119        // SAFETY: the default lookup is `unsafe` for its caller, who accepts that the runtime
120        // found runs its initialization code.
121        unsafe { open_library_file(path) }
122    }
123
124    fn load_by_linker_search(&self, file_name: &str) -> Result<libloading::Library, String> {
125        // SAFETY: as `load`.
126        unsafe { os::open_by_linker_search(file_name) }
127    }
128}
129
130#[cfg(windows)]
131mod os {
132    use std::ffi::{OsStr, OsString, c_void};
133    use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _};
134    use std::path::{Path, PathBuf};
135
136    use crate::lookup::{INSTALL_FOLDER_VALUE, INSTALL_REGISTRY_KEY, INSTANCES_REGISTRY_KEY};
137
138    type ModuleHandle = *mut c_void;
139    type RegistryKey = isize;
140
141    const GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT: u32 = 0x0000_0002;
142    const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x0000_0004;
143    #[allow(clippy::cast_possible_wrap)]
144    const HKEY_CURRENT_USER: RegistryKey = 0x8000_0001_u32 as i32 as RegistryKey;
145    #[allow(clippy::cast_possible_wrap)]
146    const HKEY_LOCAL_MACHINE: RegistryKey = 0x8000_0002_u32 as i32 as RegistryKey;
147    const RRF_RT_REG_SZ: u32 = 0x0000_0002;
148    const ERROR_SUCCESS: i32 = 0;
149    /// The longest path the wide Windows API accepts.
150    const LONGEST_PATH: usize = 32_768;
151
152    #[link(name = "kernel32")]
153    unsafe extern "system" {
154        fn GetModuleHandleExW(
155            flags: u32,
156            module_name: *const u16,
157            module: *mut ModuleHandle,
158        ) -> i32;
159        fn GetModuleFileNameW(module: ModuleHandle, file_name: *mut u16, size: u32) -> u32;
160    }
161
162    #[link(name = "advapi32")]
163    unsafe extern "system" {
164        fn RegGetValueW(
165            key: RegistryKey,
166            sub_key: *const u16,
167            value: *const u16,
168            flags: u32,
169            value_type: *mut u32,
170            data: *mut c_void,
171            data_size: *mut u32,
172        ) -> i32;
173    }
174
175    fn wide(text: &str) -> Vec<u16> {
176        OsStr::new(text).encode_wide().chain(Some(0)).collect()
177    }
178
179    pub(super) unsafe fn open_with_runtime_search_rules(
180        absolute_path: &Path,
181    ) -> Result<libloading::Library, libloading::Error> {
182        use libloading::os::windows::{
183            LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32,
184        };
185        // SAFETY: forwarded to the caller.
186        let library = unsafe {
187            libloading::os::windows::Library::load_with_flags(
188                absolute_path,
189                LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
190            )
191        }?;
192        Ok(library.into())
193    }
194
195    /// GetModuleHandleExW without flags takes a reference, which keeps unloading balanced.
196    pub(super) fn open_already_loaded(file_name: &str) -> Option<libloading::Library> {
197        libloading::os::windows::Library::open_already_loaded(file_name)
198            .ok()
199            .map(Into::into)
200    }
201
202    /// Never reached: on Windows step 4 searches the folders on `PATH`.
203    pub(super) unsafe fn open_by_linker_search(
204        file_name: &str,
205    ) -> Result<libloading::Library, String> {
206        Err(format!(
207            "{file_name}: Windows searches the folders on PATH instead"
208        ))
209    }
210
211    pub(super) fn module_path_containing(address: *const c_void) -> Option<PathBuf> {
212        let mut module: ModuleHandle = std::ptr::null_mut();
213        // SAFETY: with FROM_ADDRESS the name argument is an address inside a loaded module;
214        // UNCHANGED_REFCOUNT takes no reference, so nothing needs releasing.
215        let found = unsafe {
216            GetModuleHandleExW(
217                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
218                    | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
219                address.cast(),
220                &raw mut module,
221            )
222        };
223        if found == 0 {
224            return None;
225        }
226        let mut capacity = 260;
227        while capacity <= LONGEST_PATH {
228            let mut buffer = vec![0_u16; capacity];
229            let capacity_u32 = u32::try_from(capacity).ok()?;
230            // SAFETY: the buffer is writable for `capacity` characters.
231            let length = unsafe { GetModuleFileNameW(module, buffer.as_mut_ptr(), capacity_u32) };
232            if length == 0 {
233                return None;
234            }
235            if length < capacity_u32 {
236                buffer.truncate(length as usize);
237                return Some(PathBuf::from(OsString::from_wide(&buffer)));
238            }
239            capacity *= 2;
240        }
241        None
242    }
243
244    /// `InstallFolder` of the installed QAROS, from `HKLM` only: `HKCU` is writable by every
245    /// process of the user.
246    pub(super) fn install_folder() -> Option<PathBuf> {
247        read_registry_string(
248            HKEY_LOCAL_MACHINE,
249            INSTALL_REGISTRY_KEY,
250            INSTALL_FOLDER_VALUE,
251        )
252        .map(PathBuf::from)
253    }
254
255    /// Value `value` of the per-user record of `instance`, under `HKCU`. The caller passes only
256    /// valid instance names, so the key cannot leave the instances key.
257    pub(super) fn instance_record_value(instance: &str, value: &str) -> Option<String> {
258        let key = format!("{INSTANCES_REGISTRY_KEY}\\{instance}");
259        read_registry_string(HKEY_CURRENT_USER, &key, value)
260    }
261
262    /// A `REG_SZ` value, as stored; `None` when it is missing, empty or of another type.
263    fn read_registry_string(root: RegistryKey, key: &str, value: &str) -> Option<String> {
264        let key = wide(key);
265        let value = wide(value);
266        let mut size_in_bytes: u32 = 0;
267        // SAFETY: a size query: no data pointer, a valid size out-pointer.
268        let status = unsafe {
269            RegGetValueW(
270                root,
271                key.as_ptr(),
272                value.as_ptr(),
273                RRF_RT_REG_SZ,
274                std::ptr::null_mut(),
275                std::ptr::null_mut(),
276                &raw mut size_in_bytes,
277            )
278        };
279        if status != ERROR_SUCCESS || size_in_bytes == 0 {
280            return None;
281        }
282        let mut buffer = vec![0_u16; (size_in_bytes as usize).div_ceil(2)];
283        // SAFETY: the buffer holds `size_in_bytes` bytes.
284        let status = unsafe {
285            RegGetValueW(
286                root,
287                key.as_ptr(),
288                value.as_ptr(),
289                RRF_RT_REG_SZ,
290                std::ptr::null_mut(),
291                buffer.as_mut_ptr().cast(),
292                &raw mut size_in_bytes,
293            )
294        };
295        if status != ERROR_SUCCESS {
296            return None;
297        }
298        let length = buffer
299            .iter()
300            .position(|&character| character == 0)
301            .unwrap_or(buffer.len());
302        (length > 0).then(|| {
303            OsString::from_wide(&buffer[..length])
304                .to_string_lossy()
305                .into_owned()
306        })
307    }
308}
309
310#[cfg(not(windows))]
311mod os {
312    use std::ffi::{CStr, OsStr, c_char, c_int, c_void};
313    use std::os::unix::ffi::OsStrExt as _;
314    use std::path::{Path, PathBuf};
315
316    use libloading::os::unix::{RTLD_LOCAL, RTLD_NOW};
317
318    #[cfg(target_os = "macos")]
319    const RTLD_NOLOAD: c_int = 0x10;
320    #[cfg(not(target_os = "macos"))]
321    const RTLD_NOLOAD: c_int = 0x4;
322
323    #[repr(C)]
324    struct DynamicLinkInfo {
325        file_name: *const c_char,
326        base_address: *mut c_void,
327        symbol_name: *const c_char,
328        symbol_address: *mut c_void,
329    }
330
331    unsafe extern "C" {
332        fn dladdr(address: *const c_void, info: *mut DynamicLinkInfo) -> c_int;
333    }
334
335    pub(super) unsafe fn open_with_runtime_search_rules(
336        absolute_path: &Path,
337    ) -> Result<libloading::Library, libloading::Error> {
338        // SAFETY: forwarded to the caller.
339        let library = unsafe {
340            libloading::os::unix::Library::open(Some(absolute_path), RTLD_NOW | RTLD_LOCAL)
341        }?;
342        Ok(library.into())
343    }
344
345    pub(super) fn install_folder() -> Option<PathBuf> {
346        None
347    }
348
349    pub(super) fn instance_record_value(_instance: &str, _value: &str) -> Option<String> {
350        None
351    }
352
353    pub(super) fn open_already_loaded(file_name: &str) -> Option<libloading::Library> {
354        // SAFETY: RTLD_NOLOAD opens nothing new; it only takes a reference on a loaded library.
355        unsafe {
356            libloading::os::unix::Library::open(
357                Some(file_name),
358                RTLD_NOW | RTLD_NOLOAD | RTLD_LOCAL,
359            )
360        }
361        .ok()
362        .map(Into::into)
363    }
364
365    pub(super) unsafe fn open_by_linker_search(
366        file_name: &str,
367    ) -> Result<libloading::Library, String> {
368        // SAFETY: forwarded to the caller.
369        unsafe { libloading::os::unix::Library::open(Some(file_name), RTLD_NOW | RTLD_LOCAL) }
370            .map(Into::into)
371            .map_err(|error| error.to_string())
372    }
373
374    pub(super) fn module_path_containing(address: *const c_void) -> Option<PathBuf> {
375        let mut info = DynamicLinkInfo {
376            file_name: std::ptr::null(),
377            base_address: std::ptr::null_mut(),
378            symbol_name: std::ptr::null(),
379            symbol_address: std::ptr::null_mut(),
380        };
381        // SAFETY: a valid out-pointer; dladdr only reads the address.
382        let found = unsafe { dladdr(address, &raw mut info) };
383        if found == 0 || info.file_name.is_null() {
384            return None;
385        }
386        // SAFETY: dladdr returned a NUL-terminated name that stays valid while the module is
387        // loaded, which it is, since `address` lies in it.
388        let file_name = unsafe { CStr::from_ptr(info.file_name) };
389        let path = PathBuf::from(OsStr::from_bytes(file_name.to_bytes()));
390        // The main executable can be reported by the relative name it was started with.
391        if path.is_absolute() {
392            Some(path)
393        } else {
394            std::env::current_exe().ok()
395        }
396    }
397}