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        ];
89
90        for postfix in EXPORT_POSTFIXS {
91            let anonymous_export_name = format!("{PREFIX}anonymous{postfix}");
92            let target_export_name = format!("{PREFIX}{normalized_target}{postfix}");
93            if let Some(export) = module
94                .exports
95                .iter_mut()
96                .find(|e| e.name == anonymous_export_name)
97            {
98                export.name = target_export_name;
99            }
100        }
101
102        for export in module.exports.iter_mut() {
103            if let Some(anonymous_suffix) = export
104                .name
105                .strip_prefix(PREFIX)
106                .and_then(|s| s.strip_prefix("anonymous_"))
107            {
108                if let Some(f) = Wasip1ABIFunc::VARIANTS
109                    .iter()
110                    .find(|v| anonymous_suffix == **v)
111                {
112                    export.name = format!("{PREFIX}{normalized_target}_{f}");
113                }
114            }
115        }
116
117        if let Some(special_anonymous_export) = module
118            .exports
119            .iter_mut()
120            .find(|e| e.name == format!("{PREFIX}wasi_thread_spawn_anonymous"))
121        {
122            special_anonymous_export.name =
123                format!("{PREFIX}wasi_thread_spawn_{normalized_target}");
124        }
125
126        const NAMESPACE: &str = UniqueName::NAMESPACE;
127
128        // TODO! Implement in `<>UniqueName` and use it.
129        const EXTRA_IMPORTS: &[&str] = &[
130            "_start",
131            "memory_trap",
132            "__main_void",
133            "reset",
134            "wasi_thread_start",
135        ];
136
137        for import in module
138            .imports
139            .iter_mut()
140            .filter(|import| import.module == NAMESPACE)
141        {
142            if let Some(anonymous_suffix) = import
143                .name
144                .strip_prefix(PREFIX)
145                .and_then(|s| s.strip_prefix("anonymous_"))
146            {
147                if let Some(f) = MemoryUniqueName::VARIANTS
148                    .iter()
149                    .chain(EXTRA_IMPORTS)
150                    .find(|v| anonymous_suffix == **v)
151                {
152                    import.name = format!("{PREFIX}{normalized_target}_{f}");
153                }
154            }
155        }
156
157        // Print all exports
158        for export in module.exports.iter() {
159            log::info!("Export: {}", export.name);
160        }
161
162        // Print all imports
163        for import in module.imports.iter() {
164            log::info!("Import: {}.{}", import.module, import.name);
165        }
166
167        Ok(())
168    }
169}