bp3d_os/module/library/
unix.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 bp3d_debug::debug;
33use libc::{dlclose, dlopen, dlsym, RTLD_LAZY};
34use std::ffi::{c_void, CString};
35use std::fmt::Debug;
36use std::os::unix::ffi::OsStrExt;
37use std::path::Path;
38
39#[cfg(target_vendor = "apple")]
40pub const EXT: &str = "dylib";
41
42#[cfg(all(unix, not(target_vendor = "apple")))]
43pub const EXT: &str = "so";
44
45/// This represents a module shared object.
46#[derive(Debug)]
47#[repr(transparent)]
48pub struct Library(*mut c_void);
49
50unsafe impl Send for Library {}
51
52impl Library {
53    /// Attempts to open a handle to the current running program.
54    pub fn open_self() -> module::Result<Self> {
55        let handle = unsafe { dlopen(std::ptr::null(), RTLD_LAZY) };
56        if handle.is_null() {
57            return Err(Error::Io(std::io::Error::last_os_error()));
58        }
59        Ok(Library(handle))
60    }
61
62    /// Loads a dynamic library from the given path.
63    ///
64    /// # Arguments
65    ///
66    /// * `path`: full path to the shared library including extension.
67    ///
68    /// returns: Result<Module, Error>
69    ///
70    /// # Safety
71    ///
72    /// This function is unsafe as it assumes the module to be loaded is trusted code. If the module
73    /// contains any constructor which causes UB then this function causes UB.
74    pub unsafe fn load(path: impl AsRef<Path>) -> module::Result<Self> {
75        let path = CString::new(path.as_ref().as_os_str().as_bytes()).map_err(|_| Error::Null)?;
76        let handle = dlopen(path.as_ptr(), RTLD_LAZY);
77        if handle.is_null() {
78            return Err(Error::Io(std::io::Error::last_os_error()));
79        }
80        Ok(Library(handle))
81    }
82}
83
84impl super::Library for Library {
85    unsafe fn load_symbol<T>(
86        &self,
87        name: impl AsRef<str>,
88    ) -> module::Result<Option<Symbol<'_, T>>> {
89        let name = CString::new(name.as_ref().as_bytes()).map_err(|_| Error::Null)?;
90        let sym = dlsym(self.0, name.as_ptr());
91        if sym.is_null() {
92            Ok(None)
93        } else {
94            Ok(Some(Symbol::from_raw(sym)))
95        }
96    }
97}
98
99impl Drop for Library {
100    fn drop(&mut self) {
101        debug!("dlclose");
102        unsafe { dlclose(self.0) };
103    }
104}