Skip to main content

wasi_virt_layer/wasi/
process.rs

1use crate::memory::{WasmAccess, WasmAccessName};
2
3/// Trait for handling process exit.
4pub trait ProcessExit {
5    /// Exits the current process with the given code.
6    fn proc_exit<Wasm: WasmAccess + WasmAccessName + 'static>(code: i32);
7}
8
9/// Default implementation of `ProcessExit`.
10pub struct StandardProcess;
11
12impl ProcessExit for StandardProcess {
13    fn proc_exit<Wasm: WasmAccess + WasmAccessName + 'static>(code: i32) {
14        #[cfg(feature = "std")]
15        {
16            std::process::exit(code as i32);
17        }
18        #[cfg(not(feature = "std"))]
19        {
20            use crate::transporter::Wasip1Transporter;
21
22            Wasip1Transporter::process_abort(code as u32);
23        }
24    }
25}
26
27/// Plugs the process exit ecosystem by defining necessary handlers.
28///
29/// ```rust,no_run
30/// use wasi_virt_layer::prelude::*;
31///
32/// import_wasm!(test_wasm);
33///
34/// plug_process!(StandardProcess, test_wasm);
35/// ```
36#[macro_export]
37macro_rules! plug_process {
38    ($ty:ty, $($wasm:ident),+) => {
39        const _ : () = {
40            #[allow(unused)]
41            type __TYPE = $ty;
42        };
43
44        $crate::__private::paste::paste! {
45            $(
46                #[unsafe(no_mangle)]
47                #[cfg(target_os = "wasi")]
48                pub unsafe extern "C" fn [<__wasip1_vfs_ $wasm _proc_exit>](
49                    code: i32
50                ) {
51                    $crate::__as_t!(@as_t, $wasm);
52                    <$ty as $crate::process::ProcessExit>::proc_exit::<T>(code)
53                }
54            )*
55        }
56    };
57    ($($wasm:ident),*) => {
58        $crate::__as_t!(@through, $($wasm),* => $crate::plug_process, @inner);
59    };
60    (@inner, $($wasm:ident),*) => {
61        $crate::plug_process!($crate::process::StandardProcess, $($wasm),*);
62    };
63}