Skip to main content

wasi_virt_layer_cli/
abi.rs

1/// Module for validating WASM modules against the expected WASI ABI.
2pub mod is_valid {
3    use crate::unique_name::UniqueName;
4
5    /// Validates if a WASM module is suitable for component transformation,
6    /// ensuring no un-plugged custom WASIP1 imports remain.
7    pub fn is_valid_wasm_for_component(
8        wasm_bytes: &[u8],
9        wasm_names: &[impl AsRef<str>],
10    ) -> eyre::Result<()> {
11        let module = walrus::Module::from_buffer(wasm_bytes)
12            .to_eyre()
13            .wrap_err_with(|| eyre::eyre!("Failed to load module from buffer"))?;
14
15        let import = module.imports;
16
17        if import
18        .iter()
19        .filter(|import| {
20            import.module == UniqueName::WASIP1_ABI_MODULE
21                && matches!(import.kind, walrus::ImportKind::Function(_))
22        })
23        .map(|import| {
24            let name = import.name.strip_prefix("__wasip1_vfs_")
25                .wrap_err_with(|| eyre::eyre!("This import is not a valid this library custom import. {name}", name = import.name))?;
26            wasm_names.iter().find_map(|n| {
27                name.strip_prefix(n.as_ref())?.strip_prefix("_")?.parse().ok()
28            })
29            .wrap_err("Failed to parse wasm target and WASI function name")
30        })
31        .filter_map(|v| v.inspect_err(|e| {
32            log::error!("Invalid import: {e}");
33        }).ok())
34        .map(|v| (Wasip1ABIPlugger::from_variant(&v).unwrap(), v))
35        .fold(HashMap::<_, Vec<_>>::new(), |mut acc, (plugger, v)| {
36            acc
37                .entry(plugger)
38                .or_default()
39                .push(v);
40            acc
41        })
42        .into_iter()
43        .map(|(name, variants)| {
44            // println!("Extra imports remain. You must use the `{name}!` macro plugger to export these functions.");
45            log::error!(
46                "Extra imports remain. You must use the `{name}!` macro plugger to export these functions: {}{}",
47                variants.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "),
48                format!("\nExtra message: {}", name.get_message().unwrap_or(""))
49            );
50        })
51        .count()
52        > 0
53        {
54            Err(eyre::eyre!(
55                "Extra imports remain. This is not allowed in a component"
56            ))
57        } else {
58            Ok(())
59        }
60    }
61
62    #[derive(
63        strum::EnumString,
64        strum::EnumIter,
65        Clone,
66        Copy,
67        Debug,
68        PartialEq,
69        Eq,
70        strum::Display,
71        Hash,
72        strum::EnumMessage,
73    )]
74    #[strum(serialize_all = "snake_case")]
75    /// Identifies specific WASI feature sets that need to be plugged during virtualization.
76    pub enum Wasip1ABIPlugger {
77        /// Plugins for command-line arguments.
78        PlugArgs,
79        /// Plugins for environment variables.
80        PlugEnv,
81        #[strum(
82            message = "Plug Fs is complex and difficult so you should see the documentation for more details."
83        )]
84        /// Plugins for file system operations.
85        PlugFs,
86        #[strum(message = "Plug Socks but this is not implemented")]
87        /// Plugins for socket operations (currently unimplemented).
88        PlugSocks,
89        #[strum(message = "Plug Clock but this is not implemented")]
90        /// Plugins for clock and timing operations (currently unimplemented).
91        PlugClock,
92        #[strum(message = "Plug Random but this is not implemented")]
93        /// Plugins for random number generation (currently unimplemented).
94        PlugRandom,
95        #[strum(message = "Plug Process is default so this message should not be shown")]
96        /// Plugins for process-related operations.
97        PlugProcess,
98        #[strum(message = "Plug Sched but this is not implemented")]
99        /// Plugins for scheduler operations (currently unimplemented).
100        PlugSched,
101        #[strum(message = "Plug Poll but this is not implemented")]
102        /// Plugins for polling operations (currently unimplemented).
103        PlugPoll,
104    }
105
106    use std::collections::HashMap;
107
108    use eyre::{Context as _, ContextCompat};
109    use strum::EnumMessage as _;
110
111    use crate::util::ResultUtil as _;
112
113    use super::{Wasip1ABIFunc, Wasip1ABIFunc::*};
114    impl Wasip1ABIPlugger {
115        const PLUG_ENV: &'static [Wasip1ABIFunc] = &[EnvironSizesGet, EnvironGet];
116        const PLUG_FS: &'static [Wasip1ABIFunc] = &[
117            FdAdvise,
118            FdAllocate,
119            FdDatasync,
120            FdFdstatSetFlags,
121            FdFdstatSetRights,
122            FdWrite,
123            FdPwrite,
124            FdReaddir,
125            FdClose,
126            FdPrestatGet,
127            FdPrestatDirName,
128            FdFilestatGet,
129            FdRead,
130            FdFdstatGet,
131            FdPread,
132            FdFilestatSetSize,
133            FdFilestatSetTimes,
134            FdRenumber,
135            FdSeek,
136            FdSync,
137            FdTell,
138            PathCreateDirectory,
139            PathFilestatGet,
140            PathFilestatSetTimes,
141            PathLink,
142            PathReadlink,
143            PathRemoveDirectory,
144            PathRename,
145            PathOpen,
146            PathSymlink,
147            PathUnlinkFile,
148        ];
149        const PLUG_ARGS: &'static [Wasip1ABIFunc] = &[ArgsGet, ArgsSizesGet];
150        const PLUG_SOCKS: &'static [Wasip1ABIFunc] =
151            &[SockAccept, SockRecv, SockSend, SockShutdown];
152        const PLUG_CLOCK: &'static [Wasip1ABIFunc] = &[ClockTimeGet, ClockResGet];
153        const PLUG_RANDOM: &'static [Wasip1ABIFunc] = &[RandomGet];
154        const PLUG_PROCESS: &'static [Wasip1ABIFunc] = &[ProcExit];
155        const PLUG_SCHED: &'static [Wasip1ABIFunc] = &[SchedYield];
156        const PLUG_POLL: &'static [Wasip1ABIFunc] = &[PollOneoff];
157
158        /// Returns the list of `Wasip1ABIFunc` variants associated with this plugger.
159        pub const fn variants(self) -> &'static [Wasip1ABIFunc] {
160            match self {
161                Wasip1ABIPlugger::PlugEnv => Self::PLUG_ENV,
162                Wasip1ABIPlugger::PlugFs => Self::PLUG_FS,
163                Wasip1ABIPlugger::PlugArgs => Self::PLUG_ARGS,
164                Wasip1ABIPlugger::PlugSocks => Self::PLUG_SOCKS,
165                Wasip1ABIPlugger::PlugClock => Self::PLUG_CLOCK,
166                Wasip1ABIPlugger::PlugRandom => Self::PLUG_RANDOM,
167                Wasip1ABIPlugger::PlugProcess => Self::PLUG_PROCESS,
168                Wasip1ABIPlugger::PlugSched => Self::PLUG_SCHED,
169                Wasip1ABIPlugger::PlugPoll => Self::PLUG_POLL,
170            }
171        }
172
173        /// Identifies the appropriate `Wasip1ABIPlugger` for a specific WASI function.
174        pub fn from_variant(func: &Wasip1ABIFunc) -> Option<Wasip1ABIPlugger> {
175            use strum::IntoEnumIterator;
176
177            for plugger in Self::iter() {
178                if plugger.variants().contains(func) {
179                    return Some(plugger);
180                }
181            }
182            None
183        }
184    }
185}
186
187#[derive(
188    strum::EnumString, strum::VariantArray, strum::VariantNames, PartialEq, strum::Display,
189)]
190#[strum(serialize_all = "snake_case")]
191/// Enumeration of all supported WASI preview1 functions.
192pub enum Wasip1ABIFunc {
193    /// environ_sizes_get
194    EnvironSizesGet,
195    /// environ_get
196    EnvironGet,
197    /// proc_exit
198    ProcExit,
199    /// random_get
200    RandomGet,
201    /// sched_yield
202    SchedYield,
203    /// clock_time_get
204    ClockTimeGet,
205    /// clock_res_get
206    ClockResGet,
207    /// fd_advise
208    FdAdvise,
209    /// fd_allocate
210    FdAllocate,
211    /// fd_datasync
212    FdDatasync,
213    /// fd_fdstat_set_flags
214    FdFdstatSetFlags,
215    /// fd_fdstat_set_rights
216    FdFdstatSetRights,
217    /// fd_fdstat_get
218    FdFdstatGet,
219    /// fd_write
220    FdWrite,
221    /// fd_pwrite
222    FdPwrite,
223    /// fd_readdir
224    FdReaddir,
225    /// fd_close
226    FdClose,
227    /// fd_prestat_get
228    FdPrestatGet,
229    /// fd_prestat_dir_name
230    FdPrestatDirName,
231    /// fd_filestat_get
232    FdFilestatGet,
233    /// fd_read
234    FdRead,
235    /// fd_pread
236    FdPread,
237    /// fd_filestat_set_size
238    FdFilestatSetSize,
239    /// fd_filestat_set_times
240    FdFilestatSetTimes,
241    /// fd_renumber
242    FdRenumber,
243    /// fd_seek
244    FdSeek,
245    /// fd_sync
246    FdSync,
247    /// fd_tell
248    FdTell,
249    /// path_create_directory
250    PathCreateDirectory,
251    /// path_filestat_get
252    PathFilestatGet,
253    /// path_filestat_set_times
254    PathFilestatSetTimes,
255    /// path_link
256    PathLink,
257    /// path_readlink
258    PathReadlink,
259    /// path_remove_directory
260    PathRemoveDirectory,
261    /// path_rename
262    PathRename,
263    /// path_open
264    PathOpen,
265    /// path_symlink
266    PathSymlink,
267    /// path_unlink_file
268    PathUnlinkFile,
269    /// poll_oneoff
270    PollOneoff,
271    /// args_get
272    ArgsGet,
273    /// args_sizes_get
274    ArgsSizesGet,
275    /// sock_accept
276    SockAccept,
277    /// sock_recv
278    SockRecv,
279    /// sock_send
280    SockSend,
281    /// sock_shutdown
282    SockShutdown,
283}
284
285#[derive(
286    strum::EnumString, strum::VariantArray, strum::VariantNames, PartialEq, strum::Display,
287)]
288#[strum(serialize_all = "kebab_case")]
289/// Enumeration of WASI threads functions.
290pub enum Wasip1ThreadsABIFunc {
291    /// thread_spawn
292    ThreadSpawn,
293}
294
295#[derive(
296    strum::EnumString, strum::VariantArray, strum::VariantNames, PartialEq, strum::Display,
297)]
298#[strum(serialize_all = "snake_case")]
299/// Enumeration of internal exports required by WASI threads.
300pub enum Wasip1ThreadsABIExportFunc {
301    /// wasi_thread_start
302    WasiThreadStart,
303}