Struct minidl::Library

source ·
pub struct Library(/* private fields */);
Expand description

A loaded library handle.

Implementations§

source§

impl Library

source

pub fn load(path: impl AsRef<Path>) -> Result<Self>

Load a library, forever.

OSBehavior
WindowsLoadLibraryW(path)
Unixdlopen(path, ...)
source

pub unsafe fn from_ptr(handle: *mut c_void) -> Option<Self>

Wrap a forever-loaded library in Library for interop purpouses.

Wrap a winapi::shared::minwindef::HMODULE with Library::from_ptr(handle.cast()).
Wrap a windows::Win32::Foundation::HMODULE with Library::from_ptr(handle.0 as _).

Safety

If handle is not null, it is expected to be a valid library handle for the duration of the program.

Platform
OSExpects
Windowslibloaderapi.h-compatible HMODULE
Unixdlfcn.h-compatible handle
source

pub unsafe fn from_non_null(handle: NonNull<c_void>) -> Self

Wrap a forever-loaded library in Library for interop purpouses.

Safety

handle is expected to be a valid library handle for the duration of the program.

Platform
OSExpects
Windowslibloaderapi.h-compatible HMODULE
Unixdlfcn.h-compatible handle
source

pub fn as_ptr(&self) -> *mut c_void

Return a raw handle pointer for interop purpouses.

Acquire a winapi::shared::minwindef::HMODULE with handle.as_ptr() as HMODULE.
Acquire a windows::Win32::Foundation::HMODULE with HMODULE(handle.as_ptr() as _).

Safety

Don’t use this pointer to unload the library.

source

pub fn as_non_null(&self) -> NonNull<c_void>

Return a raw handle pointer for interop purpouses.

Safety

Don’t use this pointer to unload the library.

source

pub unsafe fn sym<'a, T>(&self, name: impl AsRef<str>) -> Result<T>

Load a symbol from the library. Note that the symbol name must end with ‘\0’. Limiting yourself to basic ASCII is also likely wise.

Safety

This function implicitly transmutes! Use extreme caution.

Platform
OSBehavior
WindowsGetProcAddress(..., name)
Unixdlsym(..., name)
source

pub unsafe fn sym_opt<'a, T>(&self, name: impl AsRef<str>) -> Option<T>

Load a symbol from the library. Note that the symbol name must end with ‘\0’. Limiting yourself to basic ASCII is also likely wise.

Safety

This function implicitly transmutes! Use extreme caution.

Platform
OSBehavior
WindowsGetProcAddress(..., name)
Unixdlsym(..., name)
source

pub unsafe fn sym_by_ordinal<T>(self, ordinal: u16) -> Result<T>

Load a symbol from the library by ordinal.

Safety

This function implicitly transmutes! Use extreme caution. Additionally, DLL ordinals are typically unstable and might change between minor versions of the same DLL, breaking your imports in nastily subtle ways. If a function name is available, use it instead!

Platform
OSBehavior
WindowsGetProcAddress(..., MAKEINTRESOURCE(ordinal))
UnixErr(...)
source

pub unsafe fn sym_opt_by_ordinal<T>(self, ordinal: u16) -> Option<T>

Load a symbol from the library by ordinal.

Safety

This function implicitly transmutes! Use extreme caution. Additionally, DLL ordinals are typically unstable and might change between minor versions of the same DLL, breaking your imports in nastily subtle ways. If a function name is available, use it instead!

Platform
OSBehavior
WindowsGetProcAddress(..., MAKEINTRESOURCE(ordinal))
UnixNone
source

pub fn has_sym(self, name: impl AsRef<str>) -> bool

Check if a symbol existing in the library. Note that the symbol name must end with ‘\0’. Limiting yourself to basic ASCII is also likely wise.

Platform
OSBehavior
Windows!!GetProcAddress(..., name)
Unix!!dlsym(..., name)
source

pub unsafe fn close_unsafe_unsound_possible_noop_do_not_use_in_production( self ) -> Result<()>

Attempt to unload the library.

Safety

❌ This is a fundamentally unsound operation that may do nothing and invalidates everything

You are practically guaranteed undefined behavior from some kind of dangling pointer or reference. Several platforms don’t even bother implementing unloading. Those that do implement unloading often have ways of opting out of actually unloading. I’d argue the only valid use case for this fn is unit testing the unloading of your DLLs, when someone else was crazy enough to unload libraries in production.

Based on that reasoning, this crate has been designed around the assumption that you will never do this. It lacks lifetimes and implements Library : Copy, which makes use-after-free bugs easy. Be especially careful - all of the following are invalidated when this function is called:

  • All fns/pointers previously returned by sym* for this library, including through copies of self.
  • The Library itself, and any Copy thereof. This means even self.has_sym(...) is no longer sound to call, despite the fn being safe, even though it will compile without error (as self is Copy)!
Safe Alternatives
  • Restart the entire process (fine for production since process shutdown is actually tested)
  • Use a sub-process and restart that (will also make your code more stable if a hot-reloading “plugin” crashes)
  • Simply leak the library (fine for dev builds)
    • Export a function to free memory, join threads, close file handles, etc. if you want to reduce memory use / file locks
    • Load a temporary copy of the library instead of the original if you hate having a file lock on the original library
Unsafe Alternatives

A wrapper or crate with “better” support for this fundamentally flawed operation might:

  • Limit support to plugin-shaped dynamic libraries that opt-in to claiming they’re safe to unload (export a special fn/symbol?)
  • Actively test unloading to catch the bugs in those libraries
  • Introduce lifetimes (e.g. libloading::Symbol), or make fn pointers private, to help combat fn pointer invalidation bugs
  • Not implement Copy for Library (or equivalent)
  • Not default-implement Clone for Library (or equivalent - properly implemented refcounting might be OK)
  • Implement Drop for Library (or equivalent) if you’re arrogant enough to claim your unloading code is actually safe/sound.
This might do nothing useful whatsoever
Threads are a problem

Any thread (including those started automatically by the library itself on load) containing any library code anywhere in it’s callstack will exhibit undefined behavior:

  • Unwinding through library code via panic/exceptions/SEH will presumably use dangling unwinding information pointers
  • Callstack snapshots (for allocation tracking, sentry.io event reporting, etc.) will contain dangling symbol pointers etc.
  • Dangling instruction pointers (through execution or returning to library code) will, presumably:
    • Crash if unmapped, or mapped without execution permissions
    • Execute random, possibly “unreachable” code - or data misinterpreted as code - if mapped with execution permissions

These are among the many reasons windows offers such a wide variety of unloading functions (lacking in POSIX systems):

Some related reading:

Additionally, there are serious limitations on what DllMain / destructors can do without deadlocking or worse, limiting the DLL’s ability to fix any of this:

Callbacks are a problem

The library has many ways of creating pointers into itself which will dangle if the library is unloaded:

String literals and other 'static references are a problem

Allocator debugging code often likes to register references or pointers to __FILE__ (common in C++ macros) or core::file!() (Rust). These are generally treated - by 100% safe code - as having 'static lifetimes, and not deep copied. While this is sound within the context of a single module, those references and pointers will dangle - with all the undefined behavior that comes with that - if those references and pointers ever end up in another module that outlasts the library.

This is only the most ubiquitous example of the larger problem: Every reference or pointer to const, static, or literal variables of the library becomes a ticking timebomb and hazard in 100% “safe” code.

Testing is a problem

Nobody tests unloading dynamic libraries. Nobody. I can’t even unload debug CRTs without triggering assertions. Calling this function will simply invoke broken untested code.

Platform
OSBehavior
WindowsFreeLibrary(...)
Unixdlclose(...)

Trait Implementations§

source§

impl Clone for Library

source§

fn clone(&self) -> Library

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Library

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Hash for Library

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl Ord for Library

source§

fn cmp(&self, other: &Library) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl PartialEq for Library

source§

fn eq(&self, other: &Library) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PartialOrd for Library

source§

fn partial_cmp(&self, other: &Library) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl Copy for Library

source§

impl Eq for Library

source§

impl Send for Library

source§

impl StructuralEq for Library

source§

impl StructuralPartialEq for Library

source§

impl Sync for Library

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.