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