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