wasi_virt_layer_cli/generator/
threads.rs

1use eyre::Context;
2use itertools::Itertools;
3use strum::VariantNames;
4
5use crate::{
6    abi::Wasip1ThreadsABIFunc,
7    generator::{Generator, GeneratorCtx},
8    util::{
9        NAMESPACE, THREADS_MODULE_ROOT, WalrusFID as _, WalrusUtilExport as _,
10        WalrusUtilImport as _, WalrusUtilModule as _,
11    },
12};
13
14fn gen_component_name(namespace: &str, name: &str) -> String {
15    format!("[static]{namespace}.{}-import", name.replace("_", "-"))
16}
17
18/// The thread spawn process itself within the VFS is also caught,
19/// but processing is performed to exclude only the root spawn from this.
20/// Relocate thread creation from root spawn to the outer layer
21#[derive(Debug, Default)]
22pub struct ThreadsSpawn;
23
24impl Generator for ThreadsSpawn {
25    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
26        if !ctx.threads {
27            return Ok(());
28        }
29
30        let namespace = "wasip1-threads";
31        let root = THREADS_MODULE_ROOT;
32        let name = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
33            .iter()
34            .exactly_one()
35            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIFunc")?; // thread-spawn
36
37        let component_name = gen_component_name(namespace, name);
38
39        module
40            .exports
41            .erase_with(&format!("{name}_import_anchor"), ctx.unstable_print_debug)?;
42
43        let real_thread_spawn_fn_id = (root, &component_name).get_fid(&module.imports)?;
44
45        let branch_fid = "__wasip1_vfs_is_root_spawn".get_fid(&module.exports)?;
46
47        if let Some(normal_thread_spawn_fn_id) =
48            ("wasi", "thread-spawn").get_fid(&module.imports).ok()
49        {
50            let self_thread_spawn_fn_id =
51                "__wasip1_vfs_wasi_thread_spawn___self".get_fid(&module.exports)?;
52
53            module
54                .exports
55                .erase_with(self_thread_spawn_fn_id, ctx.unstable_print_debug)?;
56
57            use walrus::ValType::I32;
58            let real_thread_spawn_fn_id = module
59                .add_func(&[I32], &[I32], |builder, args| {
60                    let mut body = builder.func_body();
61                    body.call(branch_fid)
62                        .if_else(
63                            I32,
64                            |then| {
65                                then.local_get(args[0]) // pass the argument to thread-spawn
66                                    .call(real_thread_spawn_fn_id);
67                            },
68                            |else_| {
69                                else_
70                                    .local_get(args[0]) // pass the argument to thread-spawn
71                                    .call(self_thread_spawn_fn_id); // call thread-spawn
72                            },
73                        )
74                        .return_();
75
76                    Ok(())
77                })
78                .wrap_err("Failed to add real thread spawn function")?;
79
80            module
81                .renew_call_fn(normal_thread_spawn_fn_id, real_thread_spawn_fn_id)
82                .wrap_err("Failed to rewrite thread-spawn call")?;
83
84            let exporting_thread_starter_name = "wasi_thread_start".to_string();
85            let exporting_thread_starter_id =
86                exporting_thread_starter_name.get_fid(&module.exports)?;
87
88            module
89                .connect_func_alt_with_remove_export(
90                    (NAMESPACE, "__wasip1_vfs___self_wasi_thread_start"),
91                    exporting_thread_starter_name,
92                    ctx.unstable_print_debug,
93                )
94                .wrap_err("Failed to rewrite self_wasi_thread_start call in root spawn")?;
95
96            module.exports.erase_with(
97                "__wasip1_vfs___self_wasi_thread_start_anchor",
98                ctx.unstable_print_debug,
99            )?;
100
101            if ctx.unstable_print_debug {
102                module
103                    .exports
104                    .add("real_thread_spawn_fn", real_thread_spawn_fn_id);
105            }
106
107            // __wasip1_vfs_self_wasi_thread_start
108            module
109                .renew_call_fn(
110                    (NAMESPACE, "__wasip1_vfs_wasi_thread_start_entry"),
111                    exporting_thread_starter_id,
112                )
113                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
114
115            module
116                .exports
117                .erase_with(branch_fid, ctx.unstable_print_debug)?;
118        } else {
119            log::warn!("No normal thread-spawn found, why are you not using threads?");
120
121            let component_name = gen_component_name(namespace, name);
122
123            let real_thread_spawn_fn_id = (root, &component_name).get_fid(&module.imports)?;
124
125            module
126                .exports
127                .erase_with("__wasip1_vfs_is_root_spawn", ctx.unstable_print_debug)?;
128
129            let fake_start = module
130                .add_func(
131                    &[walrus::ValType::I32, walrus::ValType::I32],
132                    &[],
133                    |_, _| Ok(()),
134                )
135                .wrap_err("Failed to add fake thread spawn function")?;
136
137            module
138                .renew_call_fn(
139                    (NAMESPACE, "__wasip1_vfs_wasi_thread_start_entry"),
140                    fake_start,
141                )
142                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
143
144            println!("unstable_print_debug: {}", ctx.unstable_print_debug);
145        }
146
147        Ok(())
148    }
149
150    fn pre_target(
151        &mut self,
152        module: &mut walrus::Module,
153        ctx: &GeneratorCtx,
154        external: &crate::generator::ModuleExternal,
155    ) -> eyre::Result<()> {
156        if !ctx.threads {
157            return Ok(());
158        }
159
160        let name = &external.name;
161
162        module
163            .imports
164            .find_mut(("wasi", "thread-spawn"))
165            .ok()
166            .map(|import| {
167                import.name = format!("__wasip1_vfs_wasi_thread_spawn_{name}");
168            });
169
170        module
171            .exports
172            .iter_mut()
173            .find(|export| export.name == "wasi_thread_start")
174            .map(|export| {
175                export.name = format!("__wasip1_vfs_wasi_thread_start_{name}");
176            });
177
178        Ok(())
179    }
180}
181
182/// https://github.com/rust-lang/rust/issues/146843
183/// thread spawn is broken on wasm32-wasip1-threads for building library
184#[derive(Debug, Default)]
185pub struct ThreadsSpawnPatch;
186
187impl Generator for ThreadsSpawnPatch {
188    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
189        let initializer = "__wasip1_vfs_thread_initializer"
190            .get_fid(&module.exports)
191            .ok();
192
193        if let Some(_) = initializer {
194            module
195                .exports
196                .erase_with(initializer.unwrap(), ctx.unstable_print_debug)?;
197        }
198
199        let old_start = module.start;
200        let new_start = module.add_func(&[], &[], |builder, _| {
201            let mut body = builder.func_body();
202            if let Some(old_start) = old_start {
203                body.call(old_start);
204            }
205            if let Some(initializer) = initializer {
206                body.call(initializer);
207            }
208            Ok(())
209        })?;
210
211        module.start = Some(new_start);
212
213        if ctx.unstable_print_debug {
214            if let Some(old_start) = old_start {
215                module.exports.add("__vfs_old_start", old_start);
216            }
217        }
218
219        Ok(())
220    }
221}