bp3d_os/module/loader/
interface.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::library::types::{OsLibrary, VirtualLibrary};
30use crate::module::library::Library;
31use crate::module::loader::ModuleLoader;
32use crate::module::Module;
33use crate::module::Result;
34use std::path::Path;
35use std::sync::MutexGuard;
36
37/// Represents a handle to a [Module] stored in the application's [ModuleLoader].
38pub trait ModuleHandle {
39    /// The type of [Library] to return.
40    type Library: Library;
41
42    /// Returns a reference to the stored [Module] type.
43    fn get(&self) -> &Module<Self::Library>;
44}
45
46struct VirtualLibraryHandle<'a> {
47    loader: &'a ModuleLoader,
48    id: usize,
49}
50
51impl<'a> VirtualLibraryHandle<'a> {
52    fn new(loader: &'a ModuleLoader, id: usize) -> VirtualLibraryHandle<'a> {
53        VirtualLibraryHandle { loader, id }
54    }
55}
56
57impl<'a> ModuleHandle for VirtualLibraryHandle<'a> {
58    type Library = VirtualLibrary;
59
60    fn get(&self) -> &Module<VirtualLibrary> {
61        self.loader.builtin_modules.get(&self.id).unwrap()
62    }
63}
64
65struct OsLibraryHandle<'a> {
66    loader: &'a ModuleLoader,
67    id: usize,
68}
69
70impl<'a> OsLibraryHandle<'a> {
71    fn new(loader: &'a ModuleLoader, id: usize) -> OsLibraryHandle<'a> {
72        OsLibraryHandle { loader, id }
73    }
74}
75
76impl<'a> ModuleHandle for OsLibraryHandle<'a> {
77    type Library = OsLibrary;
78
79    fn get(&self) -> &Module<OsLibrary> {
80        self.loader.modules.get(&self.id).unwrap()
81    }
82}
83
84/// A structure that represents a lock to the application's [ModuleLoader].
85pub struct Lock<'a> {
86    pub(super) lock: MutexGuard<'a, ModuleLoader>,
87}
88
89impl<'a> Lock<'a> {
90    /// Attempts to load the given builtin module from its name.
91    ///
92    /// # Arguments
93    ///
94    /// * `name`: the name of the builtin module to load.
95    ///
96    /// returns: Result<&Module<VirtualLibrary>, Error>
97    ///
98    /// # Safety
99    ///
100    /// This function assumes the module to be loaded, if it exists has the correct format otherwise
101    /// this function is UB.
102    pub unsafe fn load_builtin(&mut self, name: &str) -> Result<impl ModuleHandle + '_> {
103        self.lock
104            ._load_builtin(name)
105            .map(|id| VirtualLibraryHandle::new(&self.lock, id))
106    }
107
108    /// Attempts to load a module from the specified name which is dynamically linked in the current
109    /// running software.
110    ///
111    /// # Arguments
112    ///
113    /// * `name`: the name of the module to be loaded.
114    ///
115    /// returns: Result<&Module, Error>
116    ///
117    /// # Safety
118    ///
119    /// This function assumes the module to be loaded, if it exists has the correct format otherwise
120    /// this function is UB.
121    pub unsafe fn load_self(&mut self, name: &str) -> Result<impl ModuleHandle + '_> {
122        self.lock
123            ._load_self(name)
124            .map(|id| OsLibraryHandle::new(&self.lock, id))
125    }
126
127    /// Attempts to load a module from the specified name.
128    ///
129    /// This function already does check for the version of rustc and dependencies for Rust based
130    /// modules to ensure maximum ABI compatibility.
131    ///
132    /// This function assumes the code to be loaded is trusted and delegates this operation to the
133    /// underlying OS.
134    ///
135    /// # Arguments
136    ///
137    /// * `name`: the name of the module to be loaded.
138    ///
139    /// returns: ()
140    ///
141    /// # Safety
142    ///
143    /// It is assumed that the module is intended to be used with this instance of [ModuleLoader];
144    /// if not, this function is UB. Additionally, if some dependency used in public facing APIs
145    /// for the module are not added with [add_public_dependency](Self::add_public_dependency),
146    /// this is also UB.
147    pub unsafe fn load(&mut self, name: &str) -> Result<impl ModuleHandle + '_> {
148        self.lock
149            ._load(name)
150            .map(|id| OsLibraryHandle::new(&self.lock, id))
151    }
152
153    /// Attempts to unload the given module.
154    ///
155    /// # Arguments
156    ///
157    /// * `name`: the name of the module to unload.
158    ///
159    /// returns: ()
160    pub fn unload(&mut self, name: &str) -> Result<()> {
161        self.lock._unload(name)
162    }
163
164    /// Adds the given path to the path search list.
165    ///
166    /// # Arguments
167    ///
168    /// * `path`: the path to include.
169    ///
170    /// returns: ()
171    pub fn add_search_path(&mut self, path: impl AsRef<Path>) {
172        self.lock._add_search_path(path);
173    }
174
175    /// Removes the given path to the path search list.
176    ///
177    /// # Arguments
178    ///
179    /// * `path`: the path to remove.
180    ///
181    /// returns: ()
182    pub fn remove_search_path(&mut self, path: impl AsRef<Path>) {
183        self.lock._remove_search_path(path);
184    }
185
186    /// Adds a public facing API dependency to the list of dependency for version checks.
187    ///
188    /// This is used to check if there are any ABI incompatibilities between dependency versions
189    /// when loading a Rust based module.
190    ///
191    /// # Arguments
192    ///
193    /// * `name`: the name of the dependency.
194    /// * `version`: the version of the dependency.
195    ///
196    /// returns: ()
197    pub fn add_public_dependency<'b>(
198        &mut self,
199        name: &str,
200        version: &str,
201        features: impl IntoIterator<Item = &'b str>,
202    ) {
203        self.lock._add_public_dependency(name, version, features);
204    }
205
206    /// Returns the builtin module identified by the name `name`, returns [None] if the module is
207    /// not loaded.
208    pub fn get_builtin(&self, name: &str) -> Option<impl ModuleHandle + '_> {
209        self.lock
210            ._get_builtin(name)
211            .map(|id| VirtualLibraryHandle::new(&self.lock, id))
212    }
213
214    /// Returns the module identified by the name `name`, returns [None] if the module is
215    /// not loaded.
216    pub fn get_module(&self, name: &str) -> Option<impl ModuleHandle + '_> {
217        self.lock
218            ._get_module(name)
219            .map(|id| OsLibraryHandle::new(&self.lock, id))
220    }
221}