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

qaros_sys/
loader.rs

1use std::ffi::{OsStr, c_void};
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use crate::lookup::{LookupAttempt, LookupStep, find_runtime};
6use crate::platform::{SystemLocator, module_path_containing, open_library_file};
7#[allow(clippy::wildcard_imports)]
8use crate::types::*;
9
10/// Why [`QarApi::load`] failed.
11#[derive(Debug)]
12pub enum LoadError {
13    /// The operating system could not open the library (missing file,
14    /// missing dependent DLL, wrong architecture).
15    Open {
16        /// The path given to the loader.
17        path: PathBuf,
18        /// The operating system's reason.
19        message: String,
20    },
21    /// The library opened but lacks symbols this binding needs. All missing
22    /// names are listed; nothing was loaded.
23    MissingSymbols {
24        /// The path given to the loader.
25        path: PathBuf,
26        /// Every required symbol the library does not export.
27        symbols: Vec<&'static str>,
28    },
29    /// The default lookup ([`QarApi::load_default`]) found no runtime it could load. The
30    /// attempts name every place looked at, in lookup order; a set `QAR_INSTANCE` that names no
31    /// valid or known instance, or an instance or installed QAROS whose runtime is missing or
32    /// fails to load, ends the lookup there.
33    NotFound {
34        /// Each place looked at and what was met there.
35        attempts: Vec<LookupAttempt>,
36    },
37}
38
39impl fmt::Display for LoadError {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            Self::Open { path, message } => {
43                write!(formatter, "cannot open {}: {message}", path.display())
44            }
45            Self::MissingSymbols { path, symbols } => write!(
46                formatter,
47                "{} lacks {} of {} required symbols: {}",
48                path.display(),
49                symbols.len(),
50                SYMBOL_NAMES.len(),
51                symbols.join(", ")
52            ),
53            Self::NotFound { attempts } => {
54                write!(
55                    formatter,
56                    "no loadable QAROS runtime ({}); looked at:",
57                    crate::LIBRARY_FILE_NAME
58                )?;
59                for attempt in attempts {
60                    write!(formatter, "\n  - {attempt}")?;
61                }
62                Ok(())
63            }
64        }
65    }
66}
67
68impl std::error::Error for LoadError {}
69
70macro_rules! define_api_table {
71    ($(
72        pub fn $name:ident($($argument:ident : $argument_type:ty),* $(,)?) $(-> $return_type:ty)?;
73    )*) => {
74        /// Every `qar_impl_*` symbol this binding requires, in table order.
75        pub const SYMBOL_NAMES: &[&str] = &[$(stringify!($name)),*];
76
77        /// Table of the exported `qar_impl_*` functions.
78        ///
79        /// In runtime-loading mode the table owns the opened library, which
80        /// stays loaded until the table is dropped. The function pointers are
81        /// valid only while the table is alive: do not copy one out of it.
82        pub struct QarApi {
83            $(pub $name: unsafe extern "C" fn($($argument_type),*) $(-> $return_type)?,)*
84            library: Option<libloading::Library>,
85            library_path: Option<PathBuf>,
86            lookup_step: Option<LookupStep>,
87        }
88
89        impl QarApi {
90            fn resolve(library: libloading::Library, path: &Path) -> Result<Self, LoadError> {
91                let mut missing: Vec<&'static str> = Vec::new();
92                $(
93                    // SAFETY: the symbol type is the declaration generated from
94                    // qar_streaming.h for this target.
95                    let $name = match unsafe {
96                        library.get::<unsafe extern "C" fn($($argument_type),*) $(-> $return_type)?>(
97                            concat!(stringify!($name), "\0").as_bytes(),
98                        )
99                    } {
100                        Ok(symbol) => Some(*symbol),
101                        Err(_) => {
102                            missing.push(stringify!($name));
103                            None
104                        }
105                    };
106                )*
107                let assemble = || Some(Self { $($name: $name?,)* library: None, library_path: None, lookup_step: None });
108                match assemble() {
109                    Some(table) if missing.is_empty() => {
110                        let library_path =
111                            module_path_containing(table.qar_impl_library_init as *const c_void);
112                        Ok(Self { library: Some(library), library_path, ..table })
113                    }
114                    _ => Err(LoadError::MissingSymbols { path: path.to_path_buf(), symbols: missing }),
115                }
116            }
117
118            /// Builds the table from the import-library declarations.
119            #[cfg(feature = "link")]
120            pub fn linked() -> Self {
121                Self { $($name: linked::$name,)* library: None, library_path: None, lookup_step: None }
122            }
123        }
124
125        #[cfg(feature = "link")]
126        mod linked {
127            #[allow(clippy::wildcard_imports)]
128            use crate::types::*;
129
130            #[link(name = "qar-streaming-c")]
131            unsafe extern "C" {
132                $(pub fn $name($($argument: $argument_type),*) $(-> $return_type)?;)*
133            }
134        }
135    };
136}
137
138qar_impl_function_list!(define_api_table);
139
140impl QarApi {
141    /// Opens the C API library file at `path` and resolves every `qar_impl_*` symbol. Only that
142    /// file is tried, from its absolute path (a relative path is taken from the current
143    /// directory), with its dependencies resolved from its own folder and System32. Either all
144    /// symbols resolve or none are kept.
145    ///
146    /// Explicit paths are for development builds of QAROS itself; a distributed application uses
147    /// [`QarApi::load_default`].
148    ///
149    /// # Safety
150    ///
151    /// `path` must name a `qar-streaming-c` build whose exports match these bindings. Opening a
152    /// library runs its initialization code, and a library exporting these names with different
153    /// signatures causes undefined behaviour on the first call.
154    pub unsafe fn load(path: impl AsRef<OsStr>) -> Result<Self, LoadError> {
155        let path = Path::new(path.as_ref());
156        // SAFETY: forwarded to the caller.
157        let library = unsafe { open_package_library(path) }?;
158        Self::resolve(library, path)
159    }
160
161    /// Finds the runtime with the default lookup every QAROS binding follows and resolves every
162    /// `qar_impl_*` symbol. The first match wins:
163    ///
164    /// 0. a `qar-streaming-c` already loaded in the process (a reference is taken);
165    /// 1. `qar-streaming-c.dll` beside the binding: in the folder of the executable or library
166    ///    this crate is compiled into;
167    /// 2. when `QAR_INSTANCE` names a QAROS instance (Windows only), that instance's runtime
168    ///    folder: `default` is the installed QAROS, any other name the `RuntimeFolder` recorded
169    ///    under `HKCU\SOFTWARE\Quaternar\QAROS\Instances\<name>` (a QAROS development hub
170    ///    records its build output there and sets `QAR_INSTANCE` for the apps it starts), else
171    ///    that record's `<InstallFolder>\bin`. When the variable is set it is the only copy
172    ///    considered: an invalid name, an unknown instance, or a runtime missing there or failing
173    ///    to load is an error, never a reason to load another instance's runtime;
174    /// 3. the installed QAROS, `<InstallFolder>\bin`, from `HKLM\SOFTWARE\Quaternar\QAROS`
175    ///    (Windows); an installed runtime missing or failing to load is an error;
176    /// 4. each folder on `PATH`, in order (elsewhere: the dynamic linker's search).
177    ///
178    /// The current directory is never searched, and the process's search path is not changed.
179    /// Every candidate loads from its absolute path, its dependencies from its own folder and
180    /// System32. With no runtime found, [`LoadError::NotFound`] names every place looked at.
181    /// [`QarApi::library_path`] tells which file was loaded.
182    ///
183    /// # Safety
184    ///
185    /// The runtime found must be a `qar-streaming-c` build whose exports match these bindings;
186    /// see [`QarApi::load`].
187    pub unsafe fn load_default() -> Result<Self, LoadError> {
188        let found = find_runtime(&SystemLocator, crate::LIBRARY_FILE_NAME)
189            .map_err(|attempts| LoadError::NotFound { attempts })?;
190        let table = Self::resolve(found.library, &found.path)?;
191        Ok(Self {
192            lookup_step: Some(found.step),
193            ..table
194        })
195    }
196
197    /// Whether this table owns a library opened by [`QarApi::load`] or
198    /// [`QarApi::load_default`].
199    pub fn is_runtime_loaded(&self) -> bool {
200        self.library.is_some()
201    }
202
203    /// The file of the library this table was loaded from, for diagnostics. `None` for an
204    /// import-linked table or when the operating system does not name the module.
205    pub fn library_path(&self) -> Option<&Path> {
206        self.library_path.as_deref()
207    }
208
209    /// The step of the default lookup that found the runtime; `None` when it was not loaded by
210    /// [`QarApi::load_default`].
211    pub fn lookup_step(&self) -> Option<LookupStep> {
212        self.lookup_step
213    }
214}
215
216/// Opens a library file with the search rules [`QarApi::load`] uses: from its absolute path, its
217/// dependencies from its own folder and System32. For other libraries of a QAROS build, such as
218/// the test-only counterparts library.
219///
220/// # Safety
221///
222/// Opening a library runs its initialization code.
223pub unsafe fn open_package_library(path: &Path) -> Result<libloading::Library, LoadError> {
224    // SAFETY: forwarded to the caller.
225    unsafe { open_library_file(path) }.map_err(|message| LoadError::Open {
226        path: path.to_path_buf(),
227        message,
228    })
229}
230
231impl fmt::Debug for QarApi {
232    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233        formatter
234            .debug_struct("QarApi")
235            .field("symbols", &SYMBOL_NAMES.len())
236            .field("runtime_loaded", &self.library.is_some())
237            .field("library_path", &self.library_path)
238            .field("lookup_step", &self.lookup_step)
239            .finish_non_exhaustive()
240    }
241}