Skip to main content

wasi_virt_layer_cli/generator/
anonymous.rs

1//! If `<anonymous>` is specified,
2//! and there is only one target WASM,
3//! it will be automatically assigned.
4
5use smallvec::SmallVec;
6use strum::VariantNames;
7
8use crate::{
9    abi::Wasip1ABIFunc,
10    generator::{Generator, GeneratorCtx, memory::MemoryUniqueName},
11    unique_name::UniqueName,
12};
13
14/// Generator component translating un-named single targets into explicit generic bindings.
15#[derive(Debug, Default)]
16pub struct Anonymous;
17
18// TODO: Check thourgh with threads feature.
19impl Generator for Anonymous {
20    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
21        // If vfs include anonymous, and there is only one target, assign it to the target.
22
23        // To find the all library which VFS wasm required.
24        // Check export function `__wasip1_vfs_<anonymous>__start_anchor`.
25        let anonymous_targets = module
26            .exports
27            .iter()
28            .filter_map(|e| {
29                e.name
30                    .strip_prefix("__wasip1_vfs_")?
31                    .strip_suffix("__start_anchor")
32                    .map(|s| s.to_string())
33            })
34            .inspect(|targets| {
35                log::info!("Found target which VFS wasm required: {targets}");
36            })
37            .collect::<Vec<_>>();
38
39        let collected = ctx
40            .target_names
41            .iter()
42            .filter(|t| !anonymous_targets.iter().any(|at| at == t.as_ref()))
43            .collect::<SmallVec<[_; 1]>>();
44
45        const PREFIX: &str = UniqueName::PREFIX;
46
47        if collected.len() == 0 {
48            // Check this library use anonymous.
49            // If use anonymous but there is no target, it is an error.
50
51            // check anonymous export.
52            if module
53                .exports
54                .iter()
55                .any(|e| e.name == format!("{PREFIX}anonymous__start_anchor"))
56            {
57                // The target does not exist, even though “anonymous” is specified.
58                eyre::bail!(
59                    "The target which VFS wasm required from `<anonymous>` does not exist. Please add argument `<target_wasm>` or remove `<anonymous>` if you do not want to use VFS wasm.",
60                );
61            } else {
62                return Ok(());
63            }
64        }
65        if collected.len() > 1 {
66            eyre::bail!(
67                "There are multiple targets which VFS wasm required but not assigned: {:?}. Please specify the target explicitly instead of `<anonymous>`.",
68                collected
69            );
70        }
71
72        // Replace VFS from `<anonymous>` to the only one target.
73        let only_target = &collected[0];
74
75        // Rewrite <anonymous> to the only one target.
76        const EXPORT_POSTFIXS: &[&str] = &[
77            "__start_anchor",
78            "_memory_trap_anchor",
79            "_wasi_thread_start_anchor",
80        ];
81
82        for postfix in EXPORT_POSTFIXS {
83            let anonymous_export_name = format!("{PREFIX}anonymous{postfix}");
84            let target_export_name = format!("{PREFIX}{only_target}{postfix}");
85            if let Some(export) = module
86                .exports
87                .iter_mut()
88                .find(|e| e.name == anonymous_export_name)
89            {
90                export.name = target_export_name;
91            }
92        }
93
94        for export in module.exports.iter_mut() {
95            if let Some(anonymous_suffix) = export
96                .name
97                .strip_prefix(PREFIX)
98                .and_then(|s| s.strip_prefix("anonymous_"))
99            {
100                if let Some(f) = Wasip1ABIFunc::VARIANTS
101                    .iter()
102                    .find(|v| anonymous_suffix == **v)
103                {
104                    export.name = format!("{PREFIX}{only_target}_{f}");
105                }
106            }
107        }
108
109        if let Some(special_anonymous_export) = module
110            .exports
111            .iter_mut()
112            .find(|e| e.name == format!("{PREFIX}wasi_thread_spawn_anonymous"))
113        {
114            special_anonymous_export.name = format!("{PREFIX}wasi_thread_spawn_{only_target}");
115        }
116
117        const NAMESPACE: &str = UniqueName::NAMESPACE;
118
119        // TODO! Implement in `<>UniqueName` and use it.
120        const EXTRA_IMPORTS: &[&str] = &[
121            "_start",
122            "memory_trap",
123            "__main_void",
124            "reset",
125            "wasi_thread_start",
126        ];
127
128        for import in module
129            .imports
130            .iter_mut()
131            .filter(|import| import.module == NAMESPACE)
132        {
133            if let Some(anonymous_suffix) = import
134                .name
135                .strip_prefix(PREFIX)
136                .and_then(|s| s.strip_prefix("anonymous_"))
137            {
138                if let Some(f) = MemoryUniqueName::VARIANTS
139                    .iter()
140                    .chain(EXTRA_IMPORTS)
141                    .find(|v| anonymous_suffix == **v)
142                {
143                    import.name = format!("{PREFIX}{only_target}_{f}");
144                }
145            }
146        }
147
148        // Print all exports
149        for export in module.exports.iter() {
150            log::info!("Export: {}", export.name);
151        }
152
153        // Print all imports
154        for import in module.imports.iter() {
155            log::info!("Import: {}.{}", import.module, import.name);
156        }
157
158        Ok(())
159    }
160}