Skip to main content

libloading/os/unix/
mod.rs

1pub use self::consts::*;
2use crate::as_filename::AsFilename;
3use crate::as_symbol_name::AsSymbolName;
4use crate::util::ensure_compatible_types;
5use core::ffi::CStr;
6use core::ptr::null;
7use core::{fmt, marker, mem, ptr};
8
9mod consts;
10
11/// Run code and handle errors reported by `dlerror`.
12///
13/// This function first executes the `closure` function containing calls to the functions that
14/// report their errors via `dlerror`. This closure may return either `None` or `Some(*)` to
15/// further affect operation of this function.
16///
17/// In case the `closure` returns `None`, `with_dlerror` inspects the `dlerror`. `dlerror` may
18/// decide to not provide any error description, in which case `Err(None)` is returned to the
19/// caller. Otherwise the `error` callback is invoked to allow inspection and conversion of the
20/// error message. The conversion result is returned as `Err(Some(Error))`.
21///
22/// If the operations that report their errors via `dlerror` were all successful, `closure` should
23/// return `Some(T)` instead. In this case `dlerror` is not inspected at all.
24///
25/// # Notes
26///
27/// The whole `dlerror` handling scheme is done via setting and querying some global state. For
28/// that reason it is not safe to use dynamic library loading in MT-capable environment at all.
29/// Only in POSIX 2008+TC1 a thread-local state was allowed for `dlerror`, making the dl* family of
30/// functions possibly MT-safe, depending on the implementation of `dlerror`.
31///
32/// In practice (as of 2020-04-01) most of the widely used targets use a thread-local for error
33/// state and have been doing so for a long time.
34pub fn with_dlerror<T, F, Error>(closure: F, error: fn(&CStr) -> Error) -> Result<T, Option<Error>>
35where
36    F: FnOnce() -> Option<T>,
37{
38    // We used to guard all uses of dl* functions with our own mutex. This made them safe to use in
39    // MT programs provided the only way a program used dl* was via this library. However, it also
40    // had a number of downsides or cases where it failed to handle the problems. For instance,
41    // if any other library called `dlerror` internally concurrently with `libloading` things would
42    // still go awry.
43    //
44    // On platforms where `dlerror` is still MT-unsafe, `dlsym` (`Library::get`) can spuriously
45    // succeed and return a null pointer for a symbol when the actual symbol look-up operation
46    // fails. Instances where the actual symbol _could_ be `NULL` are platform specific. For
47    // instance on GNU glibc based-systems (an excerpt from dlsym(3)):
48    //
49    // > The value of a symbol returned by dlsym() will never be NULL if the shared object is the
50    // > result of normal compilation,  since  a  global  symbol is never placed at the NULL
51    // > address. There are nevertheless cases where a lookup using dlsym() may return NULL as the
52    // > value of a symbol. For example, the symbol value may be  the  result of a GNU indirect
53    // > function (IFUNC) resolver function that returns NULL as the resolved value.
54
55    // While we could could call `dlerror` here to clear the previous error value, only the `dlsym`
56    // call depends on it being cleared beforehand and only in some cases too. We will instead
57    // clear the error inside the dlsym binding instead.
58    //
59    // In all the other cases, clearing the error here will only be hiding misuse of these bindings
60    // or a bug in implementation of dl* family of functions.
61    closure().ok_or_else(|| unsafe {
62        // This code will only get executed if the `closure` returns `None`.
63        let dlerror_str = dlerror();
64        if dlerror_str.is_null() {
65            // In non-dlsym case this may happen when there’re bugs in our bindings or there’s
66            // non-libloading user of libdl; possibly in another thread.
67            None
68        } else {
69            // You can’t even rely on error string being static here; call to subsequent dlerror
70            // may invalidate or overwrite the error message. Why couldn’t they simply give up the
71            // ownership over the message?
72            // TODO: should do locale-aware conversion here. OTOH Rust doesn’t seem to work well in
73            // any system that uses non-utf8 locale, so I doubt there’s a problem here.
74            Some(error(CStr::from_ptr(dlerror_str)))
75            // Since we do a copy of the error string above, maybe we should call dlerror again to
76            // let libdl know it may free its copy of the string now?
77        }
78    })
79}
80
81/// A platform-specific counterpart of the cross-platform [`Library`](crate::Library).
82pub struct Library {
83    handle: *mut core::ffi::c_void,
84}
85
86unsafe impl Send for Library {}
87
88// That being said... this section in the volume 2 of POSIX.1-2008 states:
89//
90// > All functions defined by this volume of POSIX.1-2008 shall be thread-safe, except that the
91// > following functions need not be thread-safe.
92//
93// With notable absence of any dl* function other than dlerror in the list. By “this volume”
94// I suppose they refer precisely to the “volume 2”. dl* family of functions are specified
95// by this same volume, so the conclusion is indeed that dl* functions are required by POSIX
96// to be thread-safe. Great!
97//
98// See for more details:
99//
100//  * https://github.com/nagisa/rust_libloading/pull/17
101//  * http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_09_01
102unsafe impl Sync for Library {}
103
104impl Library {
105    /// Find and eagerly load a shared library (module).
106    ///
107    /// If the `filename` contains a [path separator], the `filename` is interpreted as a `path` to
108    /// a file. Otherwise, platform-specific algorithms are employed to find a library with a
109    /// matching file name.
110    ///
111    /// This is equivalent to <code>[Library::open](filename, [RTLD_LAZY] | [RTLD_LOCAL])</code>.
112    ///
113    /// [path separator]: std::path::MAIN_SEPARATOR
114    ///
115    /// # Safety
116    ///
117    /// When a library is loaded, initialisation routines contained within the library are executed.
118    /// For the purposes of safety, the execution of these routines is conceptually the same calling an
119    /// unknown foreign function and may impose arbitrary requirements on the caller for the call
120    /// to be sound.
121    ///
122    /// Additionally, the callers of this function must also ensure that execution of the
123    /// termination routines contained within the library is safe as well. These routines may be
124    /// executed when the library is unloaded.
125    #[inline]
126    pub unsafe fn new(filename: impl AsFilename) -> Result<Library, crate::Error> {
127        Library::open(Some(filename), RTLD_LAZY | RTLD_LOCAL)
128    }
129
130    /// Load the `Library` representing the current executable.
131    ///
132    /// [`Library::get`] calls of the returned `Library` will look for symbols in following
133    /// locations in order:
134    ///
135    /// 1. The original program image;
136    /// 2. Any executable object files (e.g. shared libraries) loaded at program startup;
137    /// 3. Any executable object files loaded at runtime (e.g. via other `Library::new` calls or via
138    ///    calls to the `dlopen` function).
139    ///
140    /// Note that the behaviour of a `Library` loaded with this method is different from that of
141    /// Libraries loaded with [`os::windows::Library::this`].
142    ///
143    /// This is equivalent to <code>[Library::open](None, [RTLD_LAZY] | [RTLD_LOCAL])</code>.
144    ///
145    /// [`os::windows::Library::this`]: crate::os::windows::Library::this
146    #[inline]
147    pub fn this() -> Library {
148        unsafe {
149            // SAFE: this does not load any new shared library images, no danger in it executing
150            // initialiser routines.
151            Library::open_char_ptr(null(), RTLD_LAZY | RTLD_LOCAL).expect("this should never fail")
152        }
153    }
154
155    /// Find and load an executable object file (shared library).
156    ///
157    /// See documentation for [`Library::this`] for further description of the behaviour
158    /// when the `filename` is `None`. Otherwise see [`Library::new`].
159    ///
160    /// Corresponds to `dlopen(filename, flags)`.
161    ///
162    /// # Safety
163    ///
164    /// When a library is loaded, initialisation routines contained within the library are executed.
165    /// For the purposes of safety, the execution of these routines is conceptually the same calling an
166    /// unknown foreign function and may impose arbitrary requirements on the caller for the call
167    /// to be sound.
168    ///
169    /// Additionally, the callers of this function must also ensure that execution of the
170    /// termination routines contained within the library is safe as well. These routines may be
171    /// executed when the library is unloaded.
172    pub unsafe fn open<P>(
173        filename: Option<P>,
174        flags: core::ffi::c_int,
175    ) -> Result<Library, crate::Error>
176    where
177        P: AsFilename,
178    {
179        let Some(filename) = filename else {
180            return Self::open_char_ptr(null(), flags);
181        };
182        filename.posix_filename(|posix_filename| Library::open_char_ptr(posix_filename, flags))
183    }
184
185    /// private helper to call dlopen+dlerror once we de-tangled the string into a raw pointer to a 0 terminated utf-8 string.
186    /// caller must ensure that the string is actually 0 terminated.
187    unsafe fn open_char_ptr(
188        filename: *const core::ffi::c_char,
189        flags: core::ffi::c_int,
190    ) -> Result<Library, crate::Error> {
191        with_dlerror(
192            move || {
193                let result = dlopen(filename, flags);
194
195                // ensure filename lives until dlopen completes
196                if result.is_null() {
197                    None
198                } else {
199                    Some(Library { handle: result })
200                }
201            },
202            |desc| crate::Error::DlOpen {
203                source: desc.into(),
204            },
205        )
206        .map_err(|e| e.unwrap_or(crate::Error::DlOpenUnknown))
207    }
208
209    unsafe fn get_impl<T, F>(
210        &self,
211        symbol: impl AsSymbolName,
212        on_null: F,
213    ) -> Result<Symbol<T>, crate::Error>
214    where
215        F: FnOnce() -> Result<Symbol<T>, crate::Error>,
216    {
217        ensure_compatible_types::<T, *mut core::ffi::c_void>()?;
218        // `dlsym` may return nullptr in two cases: when a symbol genuinely points to a null
219        // pointer or the symbol cannot be found. In order to detect this case a double dlerror
220        // pattern must be used, which is, sadly, a little bit racy.
221        //
222        // We try to leave as little space as possible for this to occur, but we can’t exactly
223        // fully prevent it.
224        symbol.symbol_name(|posix_symbol| {
225            let result = with_dlerror(
226                || {
227                    dlerror();
228                    let symbol = dlsym(self.handle, posix_symbol);
229                    if symbol.is_null() {
230                        None
231                    } else {
232                        Some(Symbol {
233                            pointer: symbol,
234                            pd: marker::PhantomData,
235                        })
236                    }
237                },
238                |desc| crate::Error::DlSym {
239                    source: desc.into(),
240                },
241            );
242            match result {
243                Err(None) => on_null(),
244                Err(Some(e)) => Err(e),
245                Ok(x) => Ok(x),
246            }
247        })
248    }
249
250    /// Get a pointer to a function or static variable by symbol name.
251    ///
252    /// The `symbol` may not contain any null bytes, with the exception of the last byte. Providing a
253    /// null terminated `symbol` may help to avoid an allocation.
254    ///
255    /// Symbol is interpreted as-is; no mangling is done. This means that symbols like `x::y` are
256    /// most likely invalid.
257    ///
258    /// # Safety
259    ///
260    /// Users of this API must specify the correct type of the function or variable loaded. Using a
261    /// `Symbol` with a wrong type is undefined.
262    ///
263    /// # Platform-specific behaviour
264    ///
265    /// Implementation of thread local variables is extremely platform specific and uses of such
266    /// variables that work on e.g. Linux may have unintended behaviour on other targets.
267    ///
268    /// On POSIX implementations where the `dlerror` function is not confirmed to be MT-safe (such
269    /// as FreeBSD), this function will unconditionally return an error when the underlying `dlsym`
270    /// call returns a null pointer. There are rare situations where `dlsym` returns a genuine null
271    /// pointer without it being an error. If loading a null pointer is something you care about,
272    /// consider using the [`Library::get_singlethreaded`] call.
273    #[inline(always)]
274    pub unsafe fn get<T>(&self, symbol: impl AsSymbolName) -> Result<Symbol<T>, crate::Error> {
275        #[cfg_attr(libloading_docs, allow(unused_extern_crates))]
276        #[cfg(libloading_docs)]
277        extern crate cfg_if;
278        cfg_if::cfg_if! {
279            // These targets are known to have MT-safe `dlerror`.
280            if #[cfg(any(
281                target_os = "linux",
282                target_os = "android",
283                target_os = "openbsd",
284                target_os = "macos",
285                target_os = "ios",
286                target_os = "solaris",
287                target_os = "illumos",
288                target_os = "redox",
289                target_os = "fuchsia",
290                target_os = "cygwin",
291            ))] {
292                self.get_singlethreaded(symbol)
293            } else {
294                self.get_impl(symbol, || Err(crate::Error::DlSymUnknown))
295            }
296        }
297    }
298
299    /// Get a pointer to function or static variable by symbol name.
300    ///
301    /// The `symbol` may not contain any null bytes, with the exception of the last byte. Providing a
302    /// null terminated `symbol` may help to avoid an allocation.
303    ///
304    /// Symbol is interpreted as-is; no mangling is done. This means that symbols like `x::y` are
305    /// most likely invalid.
306    ///
307    /// # Safety
308    ///
309    /// Users of this API must specify the correct type of the function or variable loaded.
310    ///
311    /// It is up to the user of this library to ensure that no other calls to an MT-unsafe
312    /// implementation of `dlerror` occur during the execution of this function. Failing that, the
313    /// behaviour of this function is not defined.
314    ///
315    /// # Platform-specific behaviour
316    ///
317    /// The implementation of thread-local variables is extremely platform specific and uses of such
318    /// variables that work on e.g. Linux may have unintended behaviour on other targets.
319    #[inline(always)]
320    pub unsafe fn get_singlethreaded<T>(
321        &self,
322        symbol: impl AsSymbolName,
323    ) -> Result<Symbol<T>, crate::Error> {
324        self.get_impl(symbol, || {
325            Ok(Symbol {
326                pointer: ptr::null_mut(),
327                pd: marker::PhantomData,
328            })
329        })
330    }
331
332    /// Convert the `Library` to a raw handle.
333    ///
334    /// The handle returned by this function shall be usable with APIs which accept handles
335    /// as returned by `dlopen`.
336    pub fn into_raw(self) -> *mut core::ffi::c_void {
337        let handle = self.handle;
338        mem::forget(self);
339        handle
340    }
341
342    /// Convert a raw handle returned by `dlopen`-family of calls to a `Library`.
343    ///
344    /// # Safety
345    ///
346    /// The pointer shall be a result of a successful call of the `dlopen`-family of functions or a
347    /// pointer previously returned by `Library::into_raw` call. It must be valid to call `dlclose`
348    /// with this pointer as an argument.
349    pub unsafe fn from_raw(handle: *mut core::ffi::c_void) -> Library {
350        Library { handle }
351    }
352
353    /// Unload the library.
354    ///
355    /// This method might be a no-op, depending on the flags with which the `Library` was opened,
356    /// what library was opened or other platform specifics.
357    ///
358    /// You only need to call this if you are interested in handling any errors that may arise when
359    /// library is unloaded. Otherwise the implementation of `Drop` for `Library` will close the
360    /// library and ignore the errors were they arise.
361    ///
362    /// The underlying data structures may still get leaked if an error does occur.
363    pub fn close(self) -> Result<(), crate::Error> {
364        let result = with_dlerror(
365            || {
366                if unsafe { dlclose(self.handle) } == 0 {
367                    Some(())
368                } else {
369                    None
370                }
371            },
372            |desc| crate::Error::DlClose {
373                source: desc.into(),
374            },
375        )
376        .map_err(|e| e.unwrap_or(crate::Error::DlCloseUnknown));
377        // While the library is not free'd yet in case of an error, there is no reason to try
378        // dropping it again, because all that will do is try calling `dlclose` again. only
379        // this time it would ignore the return result, which we already seen failing…
380        mem::forget(self);
381        result
382    }
383}
384
385impl Drop for Library {
386    fn drop(&mut self) {
387        unsafe {
388            dlclose(self.handle);
389        }
390    }
391}
392
393impl fmt::Debug for Library {
394    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
395        f.write_fmt(format_args!("Library@{:p}", self.handle))
396    }
397}
398
399/// Symbol from a library.
400///
401/// A major difference compared to the cross-platform `Symbol` is that this does not ensure that the
402/// `Symbol` does not outlive the `Library` it comes from.
403pub struct Symbol<T> {
404    pointer: *mut core::ffi::c_void,
405    pd: marker::PhantomData<T>,
406}
407
408impl<T> Symbol<T> {
409    /// Convert the loaded `Symbol` into a raw pointer.
410    pub fn into_raw(self) -> *mut core::ffi::c_void {
411        self.pointer
412    }
413
414    /// Convert the loaded `Symbol` into a raw pointer.
415    /// For unix this does the same as into_raw.
416    pub fn as_raw_ptr(self) -> *mut core::ffi::c_void {
417        self.pointer
418    }
419}
420
421impl<T> Symbol<Option<T>> {
422    /// Lift Option out of the symbol.
423    pub fn lift_option(self) -> Option<Symbol<T>> {
424        if self.pointer.is_null() {
425            None
426        } else {
427            Some(Symbol {
428                pointer: self.pointer,
429                pd: marker::PhantomData,
430            })
431        }
432    }
433}
434
435unsafe impl<T: Send> Send for Symbol<T> {}
436unsafe impl<T: Sync> Sync for Symbol<T> {}
437
438impl<T> Clone for Symbol<T> {
439    fn clone(&self) -> Symbol<T> {
440        Symbol { ..*self }
441    }
442}
443
444impl<T> core::ops::Deref for Symbol<T> {
445    type Target = T;
446    fn deref(&self) -> &T {
447        unsafe {
448            // Additional reference level for a dereference on `deref` return value.
449            &*(&self.pointer as *const *mut _ as *const T)
450        }
451    }
452}
453
454impl<T> fmt::Debug for Symbol<T> {
455    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
456        unsafe {
457            let mut info = mem::MaybeUninit::<DlInfo>::uninit();
458            if dladdr(self.pointer, info.as_mut_ptr()) != 0 {
459                let info = info.assume_init();
460                if info.dli_sname.is_null() {
461                    f.write_fmt(format_args!(
462                        "Symbol@{:p} from {:?}",
463                        self.pointer,
464                        CStr::from_ptr(info.dli_fname)
465                    ))
466                } else {
467                    f.write_fmt(format_args!(
468                        "Symbol {:?}@{:p} from {:?}",
469                        CStr::from_ptr(info.dli_sname),
470                        self.pointer,
471                        CStr::from_ptr(info.dli_fname)
472                    ))
473                }
474            } else {
475                f.write_fmt(format_args!("Symbol@{:p}", self.pointer))
476            }
477        }
478    }
479}
480
481// Platform specific things
482#[cfg_attr(any(target_os = "linux", target_os = "android"), link(name = "dl"))]
483#[cfg_attr(any(target_os = "freebsd", target_os = "dragonfly"), link(name = "c"))]
484extern "C" {
485    fn dlopen(
486        filename: *const core::ffi::c_char,
487        flags: core::ffi::c_int,
488    ) -> *mut core::ffi::c_void;
489    fn dlclose(handle: *mut core::ffi::c_void) -> core::ffi::c_int;
490    fn dlsym(
491        handle: *mut core::ffi::c_void,
492        symbol: *const core::ffi::c_char,
493    ) -> *mut core::ffi::c_void;
494    fn dlerror() -> *mut core::ffi::c_char;
495    fn dladdr(addr: *mut core::ffi::c_void, info: *mut DlInfo) -> core::ffi::c_int;
496}
497
498#[repr(C)]
499struct DlInfo {
500    dli_fname: *const core::ffi::c_char,
501    dli_fbase: *mut core::ffi::c_void,
502    dli_sname: *const core::ffi::c_char,
503    dli_saddr: *mut core::ffi::c_void,
504}