1use std::ffi::c_void;
5use std::path::{Path, PathBuf};
6
7use crate::lookup::{INSTANCE_VARIABLE, RuntimeLocator, SearchPath};
8
9pub 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
17pub 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
31pub fn installed_bin_folder() -> Option<PathBuf> {
35 os::install_folder().map(|folder| folder.join("bin"))
36}
37
38pub(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 unsafe { os::open_with_runtime_search_rules(&absolute_path) }
50 .map_err(|error| describe_open_error(&error))
51}
52
53fn 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
62pub(crate) fn module_path_containing(address: *const c_void) -> Option<PathBuf> {
64 os::module_path_containing(address)
65}
66
67pub(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 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 unsafe { open_library_file(path) }
122 }
123
124 fn load_by_linker_search(&self, file_name: &str) -> Result<libloading::Library, String> {
125 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let found = unsafe { dladdr(address, &raw mut info) };
383 if found == 0 || info.file_name.is_null() {
384 return None;
385 }
386 let file_name = unsafe { CStr::from_ptr(info.file_name) };
389 let path = PathBuf::from(OsStr::from_bytes(file_name.to_bytes()));
390 if path.is_absolute() {
392 Some(path)
393 } else {
394 std::env::current_exe().ok()
395 }
396 }
397}