Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Library::open_already_loaded() for Windows #85

Merged
merged 3 commits into from
Jan 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/libloading.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
- '*.mkd'
- 'LICENSE'
pull_request:
types: [opened, repoened, synchronize]
types: [opened, reopened, synchronize]

jobs:
native-test:
Expand Down
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub enum Error {
/// The source error.
source: WindowsError
},
/// The `LoadLibraryW` call failed and system did not report an error.
/// The `GetModuleHandleExW` call failed and system did not report an error.
GetModuleHandleExWUnknown,
/// The `GetProcAddress` call failed.
GetProcAddress {
Expand Down
39 changes: 39 additions & 0 deletions src/os/windows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,45 @@ impl Library {
}
}

/// Load a module that is already loaded by the program.
///
/// This function returns a `Library` corresponding to a module with the given name that is
/// already mapped into the address space of the process. If the module isn't found an error is
/// returned.
///
/// If the `filename` does not include a full path and there are multiple different loaded
/// modules corresponding to the `filename`, it is impossible to predict which module handle
/// will be returned. For more information refer to [MSDN].
///
/// If the `filename` specifies a library filename without path and with extension omitted,
/// `.dll` extension is implicitly added. This behaviour may be suppressed by appending a
/// trailing `.` to the `filename`.
///
/// This is equivalent to `GetModuleHandleExW(0, filename, _)`.
///
/// [MSDN]: https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandleexw
pub fn open_already_loaded<P: AsRef<OsStr>>(filename: P) -> Result<Library, crate::Error> {
let wide_filename: Vec<u16> = filename.as_ref().encode_wide().chain(Some(0)).collect();

let ret = unsafe {
let mut handle: HMODULE = std::ptr::null_mut();
with_get_last_error(|source| crate::Error::GetModuleHandleExW { source }, || {
// Make sure no winapi calls as a result of drop happen inside this closure, because
// otherwise that might change the return value of the GetLastError.
let result = libloaderapi::GetModuleHandleExW(0, wide_filename.as_ptr(), &mut handle);
if result == 0 {
None
} else {
Some(Library(handle))
}
}).map_err(|e| e.unwrap_or(crate::Error::GetModuleHandleExWUnknown))
};

drop(wide_filename); // Drop wide_filename here to ensure it doesn’t get moved and dropped
// inside the closure by mistake. See comment inside the closure.
ret
}

/// Find and load a module, additionally adjusting behaviour with flags.
///
/// See [`Library::new`] for documentation on handling of the `filename` argument. See the
Expand Down
20 changes: 20 additions & 0 deletions tests/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,23 @@ fn works_getlasterror0() {
assert_eq!(errhandlingapi::GetLastError(), gle())
}
}

#[cfg(windows)]
#[test]
fn library_open_already_loaded() {
use libloading::os::windows::Library;

// Present on Windows systems and NOT used by any other tests to prevent races.
const LIBPATH: &str = "Msftedit.dll";

// Not loaded yet.
assert!(match Library::open_already_loaded(LIBPATH) {
YaLTeR marked this conversation as resolved.
Show resolved Hide resolved
Err(libloading::Error::GetModuleHandleExW { .. }) => true,
_ => false,
});

let _lib = Library::new(LIBPATH).unwrap();

// Loaded now.
assert!(Library::open_already_loaded(LIBPATH).is_ok());
}