bp3d_os/module/library/windows.rs
1// Copyright (c) 2025, BlockProject 3D
2//
3// All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without modification,
6// are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of BlockProject 3D nor the names of its contributors
14// may be used to endorse or promote products derived from this software
15// without specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29use crate::module;
30use crate::module::error::Error;
31use crate::module::library::symbol::Symbol;
32use std::ffi::CString;
33use std::fmt::Debug;
34use std::os::windows::ffi::OsStrExt;
35use std::path::Path;
36use windows_sys::Win32::Foundation::{FreeLibrary, HMODULE};
37use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress, LoadLibraryW};
38
39pub const EXT: &str = "dll";
40
41/// This represents a module shared object.
42#[derive(Debug)]
43pub struct Library(HMODULE);
44
45unsafe impl Send for Library {}
46
47impl Library {
48 /// Attempts to open a handle to the current running program.
49 pub fn open_self() -> module::Result<Self> {
50 let handle = unsafe { GetModuleHandleW(std::ptr::null()) };
51 if handle.is_null() {
52 return Err(Error::Io(std::io::Error::last_os_error()));
53 }
54 Ok(Library(handle))
55 }
56
57 /// Loads a dynamic library from the given path.
58 ///
59 /// # Arguments
60 ///
61 /// * `path`: full path to the shared library including extension.
62 ///
63 /// returns: Result<Module, Error>
64 ///
65 /// # Safety
66 ///
67 /// This function is unsafe as it assumes the module to be loaded is trusted code. If the module
68 /// contains any constructor which causes UB then this function causes UB. Additionally, it is
69 /// UB to load a module with a DllMain function inside, if you absolutely need a DllMain function
70 /// use `bp3d_os_module_<name>_open` and `bp3d_os_module_<name>_close`.
71 pub unsafe fn load(path: impl AsRef<Path>) -> module::Result<Self> {
72 let mut path = path.as_ref().as_os_str().encode_wide().collect::<Vec<_>>();
73 if path.iter().any(|v| *v == 0x0) {
74 return Err(Error::Null);
75 }
76 path.push(0);
77 let handle = LoadLibraryW(path.as_ptr());
78 if handle.is_null() {
79 return Err(Error::Io(std::io::Error::last_os_error()));
80 }
81 Ok(Library(handle))
82 }
83}
84
85impl super::Library for Library {
86 unsafe fn load_symbol<T>(
87 &self,
88 name: impl AsRef<str>,
89 ) -> module::Result<Option<Symbol<'_, T>>> {
90 let name = CString::new(name.as_ref().as_bytes()).map_err(|_| Error::Null)?;
91 let sym = GetProcAddress(self.0, name.as_ptr() as _);
92 if sym.is_none() {
93 Ok(None)
94 } else {
95 Ok(Some(Symbol::from_raw(std::mem::transmute(sym))))
96 }
97 }
98}
99
100impl Drop for Library {
101 fn drop(&mut self) {
102 unsafe { FreeLibrary(self.0) };
103 }
104}