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
18fn normalize_name(s: &str) -> String {
19    s.replace('-', "_")
20}
21
22impl Generator for Anonymous {
23    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
24        // If vfs include anonymous, and there is only one target, assign it to the target.
25
26        // To find the all library which VFS wasm required.
27        // Check export function `__wasip1_vfs_<anonymous>__start_anchor`.
28        let anonymous_targets = module
29            .exports
30            .iter()
31            .filter_map(|e| {
32                e.name
33                    .strip_prefix("__wasip1_vfs_")?
34                    .strip_suffix("__start_anchor")
35                    .map(|s| s.to_string())
36            })
37            .inspect(|targets| {
38                log::info!("Found target which VFS wasm required: {targets}");
39            })
40            .collect::<Vec<_>>();
41
42        let collected = ctx
43            .target_names
44            .iter()
45            .filter(|t| {
46                let normalized_t = normalize_name(t.as_ref());
47                !anonymous_targets.iter().any(|at| at == &normalized_t)
48            })
49            .collect::<SmallVec<[_; 1]>>();
50
51        const PREFIX: &str = UniqueName::PREFIX;
52
53        if collected.len() == 0 {
54            // Check this library use anonymous.
55            // If use anonymous but there is no target, it is an error.
56
57            // check anonymous export.
58            if module
59                .exports
60                .iter()
61                .any(|e| e.name == format!("{PREFIX}anonymous__start_anchor"))
62            {
63                // The target does not exist, even though “anonymous” is specified.
64                eyre::bail!(
65                    "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.",
66                );
67            } else {
68                return Ok(());
69            }
70        }
71        if collected.len() > 1 {
72            eyre::bail!(
73                "There are multiple targets which VFS wasm required but not assigned: {:?}. Please specify the target explicitly instead of `<anonymous>`.",
74                collected
75            );
76        }
77
78        // Replace VFS from `<anonymous>` to the only one target.
79        let only_target = &collected[0];
80        let normalized_target = normalize_name(only_target.as_ref());
81
82        // Rewrite <anonymous> to the only one target.
83        const EXPORT_POSTFIXS: &[&str] = &[
84            "__start",
85            "__start_anchor",
86            "_memory_trap_anchor",
87            "_wasi_thread_start_anchor",
88            "_memory_grow_global_alt_get",
89            "_memory_grow_global_alt_get_no_wait",
90            "_memory_grow_global_alt_init_once",
91            "_memory_grow_global_alt_pos",
92            "_memory_grow_global_alt_set",
93            "_memory_grow_global_alt_set_with_lock",
94        ];
95
96        for postfix in EXPORT_POSTFIXS {
97            let anonymous_export_name = format!("{PREFIX}anonymous{postfix}");
98            let target_export_name = format!("{PREFIX}{normalized_target}{postfix}");
99            if let Some(export) = module
100                .exports
101                .iter_mut()
102                .find(|e| e.name == anonymous_export_name)
103            {
104                export.name = target_export_name;
105            }
106        }
107
108        for export in module.exports.iter_mut() {
109            if let Some(anonymous_suffix) = export
110                .name
111                .strip_prefix(PREFIX)
112                .and_then(|s| s.strip_prefix("anonymous_"))
113            {
114                if let Some(f) = Wasip1ABIFunc::VARIANTS
115                    .iter()
116                    .find(|v| anonymous_suffix == **v)
117                {
118                    export.name = format!("{PREFIX}{normalized_target}_{f}");
119                }
120            }
121        }
122
123        if let Some(special_anonymous_export) = module
124            .exports
125            .iter_mut()
126            .find(|e| e.name == format!("{PREFIX}wasi_thread_spawn_anonymous"))
127        {
128            special_anonymous_export.name =
129                format!("{PREFIX}wasi_thread_spawn_{normalized_target}");
130        }
131
132        const NAMESPACE: &str = UniqueName::NAMESPACE;
133
134        // TODO! Implement in `<>UniqueName` and use it.
135        const EXTRA_IMPORTS: &[&str] = &[
136            "_start",
137            "memory_trap",
138            "__main_void",
139            "reset",
140            "wasi_thread_start",
141        ];
142
143        for import in module
144            .imports
145            .iter_mut()
146            .filter(|import| import.module == NAMESPACE)
147        {
148            if let Some(anonymous_suffix) = import
149                .name
150                .strip_prefix(PREFIX)
151                .and_then(|s| s.strip_prefix("anonymous_"))
152            {
153                if let Some(f) = MemoryUniqueName::VARIANTS
154                    .iter()
155                    .chain(EXTRA_IMPORTS)
156                    .find(|v| anonymous_suffix == **v)
157                {
158                    import.name = format!("{PREFIX}{normalized_target}_{f}");
159                }
160            }
161        }
162
163        // Print all exports
164        for export in module.exports.iter() {
165            log::info!("Export: {}", export.name);
166        }
167
168        // Print all imports
169        for import in module.imports.iter() {
170            log::info!("Import: {}.{}", import.module, import.name);
171        }
172
173        Ok(())
174    }
175}