Skip to main content

executable/
traits.rs

1use crate::Standard;
2use alloc::{boxed::Box, string::String, vec::Vec};
3use core::{num::NonZeroUsize, pin::Pin};
4use file_system::{
5    ControlCommand, ControlCommandIdentifier, DirectBaseOperations, DirectCharacterDevice,
6    MountOperations, define_command,
7};
8use shared::AnyByLayout;
9
10pub type MainFunction = Option<
11    Box<dyn Fn(&'static ExecutableContext, Standard<'static>, Vec<String>) -> MainFuture + 'static>,
12>;
13
14file_system::plain_data! {
15    #[repr(C)]
16    /// Plain-data payload of [`GET_MAIN_FUNCTION`]: the two words of a
17    /// [`MainFunction`] fat pointer, so the payload size and layout are
18    /// unchanged. A function pointer is not plain data, so the payload type
19    /// is this mirror; the host converts it back where the value is read.
20    ///
21    /// The value carries the owning `Box<dyn Fn>` pointer, so it is not
22    /// `Clone`/`Copy`: convert it with [`MainFunctionAbi::into_main_function`]
23    /// at most once, or the box would be freed twice.
24    #[derive(Debug, Default)]
25    pub struct MainFunctionAbi {
26        pub data: usize,
27        pub virtual_table: usize,
28    }
29}
30
31const _: () = assert!(
32    core::mem::size_of::<MainFunctionAbi>() == core::mem::size_of::<MainFunction>()
33        && core::mem::align_of::<MainFunctionAbi>() == core::mem::align_of::<MainFunction>(),
34    "MainFunctionAbi must mirror the MainFunction fat pointer"
35);
36
37impl From<MainFunction> for MainFunctionAbi {
38    fn from(value: MainFunction) -> Self {
39        // SAFETY: the const assertion above proves the sizes and alignments
40        // match, and a fat pointer is exactly two words.
41        unsafe { core::mem::transmute(value) }
42    }
43}
44
45impl MainFunctionAbi {
46    /// Reinterprets a payload written by the host device as the function
47    /// pointer it carries.
48    ///
49    /// The payload holds an owning `Box<dyn Fn>`, so it must be converted at
50    /// most once: converting a copy twice would free the box twice.
51    ///
52    /// # Safety
53    ///
54    /// The value must come from a [`MainFunction`] produced by the host:
55    /// arbitrary bytes are not a valid function pointer.
56    pub unsafe fn into_main_function(self) -> MainFunction {
57        // SAFETY: the caller guarantees the payload holds a real
58        // `MainFunction`; sizes and alignments match (asserted above).
59        unsafe { core::mem::transmute(self) }
60    }
61}
62
63define_command!(
64    GET_MAIN_FUNCTION,
65    Read,
66    device::kind::EXECUTABLE,
67    1,
68    (),
69    MainFunctionAbi
70);
71
72pub trait ExecutableTrait: 'static + Send + Sync {
73    fn main(standard: Standard<'static>, arguments: Vec<String>) -> MainFuture;
74}
75
76pub struct ExecutableContext {
77    pub task_manager: &'static task::Manager,
78    pub users_manager: &'static users::Manager,
79    pub virtual_file_system: &'static virtual_file_system::VirtualFileSystem,
80    #[cfg(feature = "graphics")]
81    pub graphics_manager: Option<&'static graphics::Manager>,
82    #[cfg(feature = "network")]
83    pub network_manager: Option<&'static network::Manager>,
84    pub formats: &'static [crate::ExecutableFormat],
85    pub time_manager: &'static time::Manager<'static>,
86}
87
88impl ExecutableContext {
89    /// A context without a graphics or network manager, whichever features are
90    /// enabled: callers need not know whether those fields exist.
91    pub fn new(
92        task_manager: &'static task::Manager,
93        users_manager: &'static users::Manager,
94        virtual_file_system: &'static virtual_file_system::VirtualFileSystem,
95        time_manager: &'static time::Manager<'static>,
96    ) -> Self {
97        Self {
98            task_manager,
99            users_manager,
100            virtual_file_system,
101            #[cfg(feature = "graphics")]
102            graphics_manager: None,
103            #[cfg(feature = "network")]
104            network_manager: None,
105            formats: &[],
106            time_manager,
107        }
108    }
109}
110
111pub type MainFuture =
112    Pin<Box<dyn Future<Output = core::result::Result<(), NonZeroUsize>> + 'static>>;
113
114pub struct ExecutableWrapper<T: ExecutableTrait>(T, &'static ExecutableContext);
115
116impl<T: ExecutableTrait> ExecutableWrapper<T> {
117    pub fn new(executable: T, context: &'static ExecutableContext) -> Self {
118        Self(executable, context)
119    }
120}
121
122impl<T: ExecutableTrait> MountOperations for ExecutableWrapper<T> {}
123
124impl<T: ExecutableTrait> DirectBaseOperations for ExecutableWrapper<T> {
125    fn read(
126        &self,
127        _cx: &mut core::task::Context<'_>,
128        _buffer: &mut [u8],
129        _absolute_position: file_system::Size,
130    ) -> core::task::Poll<file_system::Result<usize>> {
131        file_system::ready(|| Err(file_system::IoErrorKind::Unsupported))
132    }
133
134    fn write(
135        &self,
136        _cx: &mut core::task::Context<'_>,
137        _buffer: &[u8],
138        _absolute_position: file_system::Size,
139    ) -> core::task::Poll<file_system::Result<usize>> {
140        file_system::ready(|| Err(file_system::IoErrorKind::Unsupported))
141    }
142
143    fn control(
144        &self,
145        _cx: &mut core::task::Context<'_>,
146        command: ControlCommandIdentifier,
147        _: &AnyByLayout,
148        output: &mut AnyByLayout,
149    ) -> core::task::Poll<file_system::Result<()>> {
150        file_system::ready(|| {
151            log::debug!("ExecutableWrapper control command: {:?}", command);
152
153            match command {
154                GET_MAIN_FUNCTION::IDENTIFIER => {
155                    let output = GET_MAIN_FUNCTION::cast_output(output)?;
156                    let executable_context = self.1;
157                    let main: MainFunction = Some(Box::new(move |context, standard, arguments| {
158                        let mut standard = standard;
159                        standard.context = context;
160                        debug_assert!(core::ptr::eq(context, executable_context));
161                        T::main(standard, arguments)
162                    }));
163                    *output = MainFunctionAbi::from(main);
164                    Ok(())
165                }
166                _ => Err(file_system::IoErrorKind::Unsupported),
167            }
168        })
169    }
170}
171
172impl<T: ExecutableTrait> DirectCharacterDevice for ExecutableWrapper<T> {}
173
174#[macro_export]
175macro_rules! mount_executables {
176
177    ( $context:expr, $virtual_file_system:expr, $task:expr, &[ $( $(#[$attribute:meta])* ($path:expr, $executable:expr) ),* $(,)? ] ) => {
178
179    async || -> $crate::exported_virtual_file_system::Result<()>
180    {
181        use $crate::exported_file_system::{Permissions};
182        use $crate::exported_virtual_file_system::ItemStatic;
183
184        $(
185            $(#[$attribute])*
186            {
187                let __executable = $crate::ExecutableWrapper::new($executable, $context);
188
189                let _ = $virtual_file_system.remove($task, $path).await;
190                $virtual_file_system.mount_character_device($task, $path, __executable).await?;
191                $virtual_file_system.set_permissions($task, $path, Permissions::EXECUTABLE).await?;
192            }
193        )*
194
195        Ok(())
196    }()
197};
198
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn main_function_abi_round_trips_a_function_pointer() {
207        let main: MainFunction = Some(Box::new(|_, _, _| Box::pin(async { Ok(()) })));
208        let abi = MainFunctionAbi::from(main);
209        // SAFETY: the payload was produced from a real `MainFunction`.
210        let recovered = unsafe { abi.into_main_function() };
211        assert!(recovered.is_some());
212        let abi = MainFunctionAbi::from(MainFunction::None);
213        // SAFETY: the payload was produced from a real `MainFunction`.
214        assert!(unsafe { abi.into_main_function() }.is_none());
215    }
216}