Skip to main content

wasi_virt_layer_cli/generator/
threads.rs

1use eyre::Context;
2use itertools::Itertools;
3use strum::VariantNames;
4
5use crate::{
6    abi::{Wasip1ThreadsABIExportFunc, Wasip1ThreadsABIFunc},
7    generator::{Generator, GeneratorCtx},
8    unique_name::UniqueName,
9    util::{
10        WalrusFID as _, WalrusUtilExport as _, WalrusUtilImport as _, WalrusUtilModule as _,
11        WasmName, gen_component_name,
12    },
13};
14
15#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
16#[strum(serialize_all = "snake_case")]
17pub enum ThreadsSpawnName<'a> {
18    ImportAnchor(&'a str),
19    IsRootSpawn,
20    #[strum(serialize = "wasi_thread_spawn___self")]
21    WasiThreadSpawnSelf,
22    #[strum(serialize = "__self_wasi_thread_start")]
23    SelfWasiThreadStart,
24    #[strum(serialize = "__self_wasi_thread_start_anchor")]
25    SelfWasiThreadStartAnchor,
26    RealThreadSpawnFn,
27    WasiThreadStartEntry,
28    WasiThreadStart(&'a WasmName),
29    #[strum(serialize = "wasi_thread_start")]
30    WasiThreadStartDestination(&'a WasmName),
31    WasiThreadSpawn(&'a WasmName),
32    WasiThreadStartAnchor(&'a WasmName),
33    ThreadInitializer,
34    OldStart,
35}
36
37/// The thread spawn process itself within the VFS is also caught,
38/// but processing is performed to exclude only the root spawn from this.
39/// Relocate thread creation from root spawn to the outer layer
40#[derive(Debug, Default)]
41pub struct ThreadsSpawn;
42
43impl Generator for ThreadsSpawn {
44    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
45        if !ctx.threads {
46            return Ok(());
47        }
48
49        let name = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
50            .iter()
51            .exactly_one()
52            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIFunc")?; // thread-spawn
53
54        let component_name = gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, name);
55
56        module.exports.erase_with(
57            &UniqueName::ThreadsSpawn(&ThreadsSpawnName::ImportAnchor(name)),
58            ctx.unstable_print_debug,
59        )?;
60
61        let real_thread_spawn_fn_id =
62            (UniqueName::THREADS_MODULE_ROOT, &component_name).get_fid(&module.imports)?;
63
64        let branch_fid =
65            UniqueName::ThreadsSpawn(&ThreadsSpawnName::IsRootSpawn).get_fid(&module.exports)?;
66
67        if let Some(normal_thread_spawn_fn_id) = (UniqueName::WASIP1_THREADS_ABI_MODULE, name)
68            .get_fid(&module.imports)
69            .ok()
70        {
71            let self_thread_spawn_fn_id =
72                UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawnSelf)
73                    .get_fid(&module.exports)?;
74
75            module
76                .exports
77                .erase_with(self_thread_spawn_fn_id, ctx.unstable_print_debug)?;
78
79            use walrus::ValType::I32;
80            let real_thread_spawn_fn_id = module
81                .add_func(&[I32], &[I32], |builder, args| {
82                    let mut body = builder.func_body();
83                    body.call(branch_fid)
84                        .if_else(
85                            I32,
86                            |then| {
87                                then.local_get(args[0]) // pass the argument to thread-spawn
88                                    .call(real_thread_spawn_fn_id);
89                            },
90                            |else_| {
91                                else_
92                                    .local_get(args[0]) // pass the argument to thread-spawn
93                                    .call(self_thread_spawn_fn_id); // call thread-spawn
94                            },
95                        )
96                        .return_();
97
98                    Ok(())
99                })
100                .wrap_err("Failed to add real thread spawn function")?;
101
102            module
103                .renew_call_fn(normal_thread_spawn_fn_id, real_thread_spawn_fn_id)
104                .wrap_err("Failed to rewrite thread-spawn call")?;
105
106            let start_name = Wasip1ThreadsABIExportFunc::VARIANTS
107                .iter()
108                .exactly_one()
109                .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // wasi-thread-start
110
111            let exporting_thread_starter_id = start_name.get_fid(&module.exports)?;
112
113            module
114                .connect_func_alt_with_remove_export(
115                    (
116                        UniqueName::NAMESPACE,
117                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::SelfWasiThreadStart),
118                    ),
119                    start_name,
120                    ctx.unstable_print_debug,
121                )
122                .wrap_err("Failed to rewrite self_wasi_thread_start call in root spawn")?;
123
124            module.exports.erase_with(
125                &UniqueName::ThreadsSpawn(&ThreadsSpawnName::SelfWasiThreadStartAnchor),
126                ctx.unstable_print_debug,
127            )?;
128
129            if ctx.unstable_print_debug {
130                module.exports.add(
131                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::RealThreadSpawnFn).to_string(),
132                    real_thread_spawn_fn_id,
133                );
134            }
135
136            // __wasip1_vfs_self_wasi_thread_start
137            module
138                .renew_call_fn(
139                    (
140                        UniqueName::NAMESPACE,
141                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartEntry),
142                    ),
143                    exporting_thread_starter_id,
144                )
145                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
146
147            module
148                .exports
149                .erase_with(branch_fid, ctx.unstable_print_debug)?;
150        } else {
151            log::warn!("No normal thread-spawn found, why are you not using threads?");
152
153            let component_name =
154                gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, name);
155
156            let real_thread_spawn_fn_id =
157                (UniqueName::THREADS_MODULE_ROOT, &component_name).get_fid(&module.imports)?;
158
159            module.exports.erase_with(
160                &UniqueName::ThreadsSpawn(&ThreadsSpawnName::IsRootSpawn),
161                ctx.unstable_print_debug,
162            )?;
163
164            let fake_start = module
165                .add_func(
166                    &[walrus::ValType::I32, walrus::ValType::I32],
167                    &[],
168                    |_, _| Ok(()),
169                )
170                .wrap_err("Failed to add fake thread spawn function")?;
171
172            module
173                .renew_call_fn(
174                    (
175                        UniqueName::NAMESPACE,
176                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartEntry),
177                    ),
178                    fake_start,
179                )
180                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
181
182            // println!("unstable_print_debug: {}", ctx.unstable_print_debug);
183        }
184
185        Ok(())
186    }
187
188    fn pre_target(
189        &mut self,
190        module: &mut walrus::Module,
191        ctx: &GeneratorCtx,
192        external: &crate::generator::ModuleExternal,
193    ) -> eyre::Result<()> {
194        if !ctx.threads {
195            return Ok(());
196        }
197
198        let wasm = &external.name;
199
200        let start_name = Wasip1ThreadsABIFunc::VARIANTS
201            .iter()
202            .exactly_one()
203            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // thread-spawn
204
205        module
206            .imports
207            .find_mut((UniqueName::WASIP1_THREADS_ABI_MODULE, start_name))
208            .ok()
209            .map(|import| {
210                // import.name = format!("__wasip1_vfs_wasi_thread_spawn_{name}");
211                import.name =
212                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
213            });
214
215        let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
216            .iter()
217            .exactly_one()
218            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // wasi_thread_start
219
220        module
221            .exports
222            .iter_mut()
223            .find(|export| export.name == *export_name)
224            .map(|export| {
225                export.name =
226                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
227                        .to_string();
228            });
229
230        Ok(())
231    }
232}
233
234/// https://github.com/rust-lang/rust/issues/146843
235/// thread spawn is broken on wasm32-wasip1-threads for building library
236#[derive(Debug, Default)]
237pub struct ThreadsSpawnPatch;
238
239impl Generator for ThreadsSpawnPatch {
240    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
241        let initializer = UniqueName::ThreadsSpawn(&ThreadsSpawnName::ThreadInitializer)
242            .get_fid(&module.exports)
243            .ok();
244
245        if let Some(_) = initializer {
246            module
247                .exports
248                .erase_with(initializer.unwrap(), ctx.unstable_print_debug)?;
249        }
250
251        let old_start = module.start;
252        let new_start = module.add_func(&[], &[], |builder, _| {
253            let mut body = builder.func_body();
254            if let Some(old_start) = old_start {
255                body.call(old_start);
256            }
257            if let Some(initializer) = initializer {
258                body.call(initializer);
259            }
260            Ok(())
261        })?;
262
263        module.start = Some(new_start);
264
265        if ctx.unstable_print_debug {
266            if let Some(old_start) = old_start {
267                module.exports.add(
268                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::OldStart).to_string(),
269                    old_start,
270                );
271            }
272        }
273
274        Ok(())
275    }
276}