Skip to main content

wasi_virt_layer_cli/generator/
threads.rs

1use eyre::Context;
2use itertools::Itertools;
3use strum::VariantNames;
4
5use crate::{
6    instrs::InstrRewrite,
7    abi::{Wasip1ThreadsABIExportFunc, Wasip1ThreadsABIFunc},
8    generator::{Generator, GeneratorCtx},
9    unique_name::UniqueName,
10    util::{
11        WalrusFID as _, WalrusUtilExport as _, WalrusUtilImport as _, WalrusUtilModule as _,
12        WasmName, gen_component_name,
13    },
14};
15
16/// Constants and format builders for renaming Thread spawn imports and exports during patching.
17#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
18#[strum(serialize_all = "snake_case")]
19pub enum ThreadsSpawnName<'a> {
20    /// Custom spawn anchor injected for bridging definitions.
21    ImportAnchor(&'a str),
22    /// Flag indicating whether the current instance is the root spawner thread.
23    IsRootSpawn,
24    #[strum(serialize = "wasi_thread_spawn___self")]
25    /// Function identifier for native WASI spawn capability.
26    WasiThreadSpawnSelf,
27    #[strum(serialize = "__self_wasi_thread_start")]
28    /// The starting routine mapping on thread creation execution.
29    SelfWasiThreadStart,
30    #[strum(serialize = "__self_wasi_thread_start_anchor")]
31    /// The underlying static bridge to anchor thread origins.
32    SelfWasiThreadStartAnchor,
33    /// Low level function signature to actually request system spawn.
34    RealThreadSpawnFn,
35    /// Entry stub function used when entering newly spawned routines.
36    WasiThreadStartEntry,
37    /// Specialized start function per WASM module target.
38    WasiThreadStart(&'a WasmName),
39    #[strum(serialize = "wasi_thread_start")]
40    /// Target resolving memory start capabilities per component.
41    WasiThreadStartDestination(&'a WasmName),
42    /// Wraps dynamic spawn allocations over components.
43    WasiThreadSpawn(&'a WasmName),
44    /// Cross-linking anchor marking a spawn location.
45    WasiThreadStartAnchor(&'a WasmName),
46    /// Initializer function for thread memory limits scaling.
47    ThreadInitializer,
48    /// Reference to the existing deprecated `_start` handling.
49    OldStart,
50}
51
52/// The thread spawn process itself within the VFS is also caught,
53/// but processing is performed to exclude only the root spawn from this.
54/// Relocate thread creation from root spawn to the outer layer
55///
56/// **Why this is needed:**
57/// Per `IMPORTS_EXPORTS_EVOLUTION_DETAILED.md`, `wasi-threads:spawn` requires special handling
58/// because thread creation from the "root spawn" (the original process invoking `_start`)
59/// differs from spawning within explicitly created WASI threads.
60///
61/// This generator ensures that only the root spawn initiates the true thread start sequence
62/// on the host by intercepting `wasi_thread_spawn`. Real execution is forwarded via
63/// `__wasip1_vfs_real_thread_spawn_fn`, avoiding recursive or improper initializations.
64#[derive(Debug, Default)]
65pub struct ThreadsSpawn;
66
67impl Generator for ThreadsSpawn {
68    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
69        if !ctx.threads {
70            return Ok(());
71        }
72
73        let name = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
74            .iter()
75            .exactly_one()
76            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIFunc")?; // thread-spawn
77
78        let component_name = gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, name);
79
80        module.exports.erase_with(
81            &UniqueName::ThreadsSpawn(&ThreadsSpawnName::ImportAnchor(name)),
82            ctx.unstable_print_debug,
83        )?;
84
85        let real_thread_spawn_fn_id =
86            (UniqueName::THREADS_MODULE_ROOT, &component_name).get_fid(&module.imports)?;
87
88        let branch_fid =
89            UniqueName::ThreadsSpawn(&ThreadsSpawnName::IsRootSpawn).get_fid(&module.exports)?;
90
91        if let Some(normal_thread_spawn_fn_id) = (UniqueName::WASIP1_THREADS_ABI_MODULE, name)
92            .get_fid(&module.imports)
93            .ok()
94        {
95            let self_thread_spawn_fn_id =
96                UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawnSelf)
97                    .get_fid(&module.exports)?;
98
99            module
100                .exports
101                .erase_with(self_thread_spawn_fn_id, ctx.unstable_print_debug)?;
102
103            use walrus::ValType::I32;
104            let real_thread_spawn_fn_id = module
105                .add_func(&[I32], &[I32], |builder, args| {
106                    let mut body = builder.func_body();
107                    body.call(branch_fid)
108                        .if_else(
109                            I32,
110                            |then| {
111                                then.local_get(args[0]) // pass the argument to thread-spawn
112                                    .call(real_thread_spawn_fn_id);
113                            },
114                            |else_| {
115                                else_
116                                    .local_get(args[0]) // pass the argument to thread-spawn
117                                    .call(self_thread_spawn_fn_id); // call thread-spawn
118                            },
119                        )
120                        .return_();
121
122                    Ok(())
123                })
124                .wrap_err("Failed to add real thread spawn function")?;
125
126            module
127                .renew_call_fn(normal_thread_spawn_fn_id, real_thread_spawn_fn_id)
128                .wrap_err("Failed to rewrite thread-spawn call")?;
129
130            let start_name = Wasip1ThreadsABIExportFunc::VARIANTS
131                .iter()
132                .exactly_one()
133                .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // wasi-thread-start
134
135            let exporting_thread_starter_id = start_name.get_fid(&module.exports)?;
136
137            module
138                .connect_func_alt_with_remove_export(
139                    (
140                        UniqueName::NAMESPACE,
141                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::SelfWasiThreadStart),
142                    ),
143                    start_name,
144                    ctx.unstable_print_debug,
145                )
146                .wrap_err("Failed to rewrite self_wasi_thread_start call in root spawn")?;
147
148            module.exports.erase_with(
149                &UniqueName::ThreadsSpawn(&ThreadsSpawnName::SelfWasiThreadStartAnchor),
150                ctx.unstable_print_debug,
151            )?;
152
153            if ctx.unstable_print_debug {
154                module.exports.add(
155                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::RealThreadSpawnFn).to_string(),
156                    real_thread_spawn_fn_id,
157                );
158            }
159
160            // __wasip1_vfs_self_wasi_thread_start
161            module
162                .renew_call_fn(
163                    (
164                        UniqueName::NAMESPACE,
165                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartEntry),
166                    ),
167                    exporting_thread_starter_id,
168                )
169                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
170
171            module
172                .exports
173                .erase_with(branch_fid, ctx.unstable_print_debug)?;
174        } else {
175            log::warn!("No normal thread-spawn found, why are you not using threads?");
176
177            let component_name =
178                gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, name);
179
180            let _real_thread_spawn_fn_id =
181                (UniqueName::THREADS_MODULE_ROOT, &component_name).get_fid(&module.imports)?;
182
183            module.exports.erase_with(
184                &UniqueName::ThreadsSpawn(&ThreadsSpawnName::IsRootSpawn),
185                ctx.unstable_print_debug,
186            )?;
187
188            let fake_start = module
189                .add_func(
190                    &[walrus::ValType::I32, walrus::ValType::I32],
191                    &[],
192                    |_, _| Ok(()),
193                )
194                .wrap_err("Failed to add fake thread spawn function")?;
195
196            module
197                .renew_call_fn(
198                    (
199                        UniqueName::NAMESPACE,
200                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartEntry),
201                    ),
202                    fake_start,
203                )
204                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
205
206            // println!("unstable_print_debug: {}", ctx.unstable_print_debug);
207        }
208
209        Ok(())
210    }
211
212    fn pre_target(
213        &mut self,
214        module: &mut walrus::Module,
215        ctx: &GeneratorCtx,
216        external: &crate::generator::ModuleExternal,
217    ) -> eyre::Result<()> {
218        if !ctx.threads {
219            return Ok(());
220        }
221
222        let wasm = &external.name;
223
224        let start_name = Wasip1ThreadsABIFunc::VARIANTS
225            .iter()
226            .exactly_one()
227            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // thread-spawn
228
229        module
230            .imports
231            .find_mut((UniqueName::WASIP1_THREADS_ABI_MODULE, start_name))
232            .ok()
233            .map(|import| {
234                // import.name = format!("__wasip1_vfs_wasi_thread_spawn_{name}");
235                import.name =
236                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
237            });
238
239        let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
240            .iter()
241            .exactly_one()
242            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // wasi_thread_start
243
244        module
245            .exports
246            .iter_mut()
247            .find(|export| export.name == *export_name)
248            .map(|export| {
249                export.name =
250                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
251                        .to_string();
252            });
253
254        Ok(())
255    }
256}
257
258/// https://github.com/rust-lang/rust/issues/146843
259/// thread spawn is broken on wasm32-wasip1-threads for building library
260///
261/// **Why this is needed:**
262/// Currently, thread initialization routines (e.g. `__wasm_init_tls`) can be improperly tied
263/// or omitted during WASM generation (see rust-lang/rust#146843). This patching strategy
264/// wraps the original `_start` with an injected `ThreadInitializer` call if one is exported.
265#[derive(Debug, Default)]
266pub struct ThreadsSpawnPatch;
267
268impl Generator for ThreadsSpawnPatch {
269    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
270        let initializer = UniqueName::ThreadsSpawn(&ThreadsSpawnName::ThreadInitializer)
271            .get_fid(&module.exports)
272            .ok();
273
274        if let Some(init_id) = initializer {
275            module
276                .exports
277                .erase_with(init_id, ctx.unstable_print_debug)?;
278
279            let init = ctx.starts.thread_patch.get_fid(&module.exports)?;
280            module
281                .funcs
282                .get_mut(init)
283                .kind
284                .unwrap_local_mut()
285                .builder_mut()
286                .func_body()
287                .call(init_id);
288        }
289
290        Ok(())
291    }
292}
293
294/// Rewrites `memory.atomic.wait` and `memory.atomic.notify` in target modules 
295/// to VFS alternate implementations to handle offset shifts during memory growth safely.
296#[derive(Debug, Default)]
297pub struct AtomicPatch;
298
299impl Generator for AtomicPatch {
300    fn pre_target(
301        &mut self,
302        module: &mut walrus::Module,
303        ctx: &GeneratorCtx,
304        _external: &crate::generator::ModuleExternal,
305    ) -> eyre::Result<()> {
306        if !ctx.threads {
307            return Ok(());
308        }
309
310        use walrus::ValType::{I32, I64};
311
312        let wait32_ty = module.types.add(&[I32, I32, I64], &[I32]);
313        let (wait32_import, _) = module.add_import_func("wasi_snapshot_preview1", "__vfs_atomic_wait32", wait32_ty);
314
315        let wait64_ty = module.types.add(&[I32, I64, I64], &[I32]);
316        let (wait64_import, _) = module.add_import_func("wasi_snapshot_preview1", "__vfs_atomic_wait64", wait64_ty);
317
318        let notify_ty = module.types.add(&[I32, I32], &[I32]);
319        let (notify_import, _) = module.add_import_func("wasi_snapshot_preview1", "__vfs_atomic_notify", notify_ty);
320
321        for (_fid, func) in module.funcs.iter_local_mut() {
322            let mut builder = func.builder_mut();
323            let mut body = builder.func_body();
324            
325            body.rewrite(|instr, _pos| {
326                let new_instr = match instr {
327                    walrus::ir::Instr::AtomicWait(w) => {
328                        if w.arg.offset != 0 {
329                            log::warn!("AtomicWait with non-zero offset is not supported yet! offset: {}", w.arg.offset);
330                        }
331                        if !w.sixty_four {
332                            Some(walrus::ir::Instr::Call(walrus::ir::Call { func: wait32_import }))
333                        } else {
334                            Some(walrus::ir::Instr::Call(walrus::ir::Call { func: wait64_import }))
335                        }
336                    }
337                    walrus::ir::Instr::AtomicNotify(n) => {
338                        if n.arg.offset != 0 {
339                            log::warn!("AtomicNotify with non-zero offset is not supported yet! offset: {}", n.arg.offset);
340                        }
341                        Some(walrus::ir::Instr::Call(walrus::ir::Call { func: notify_import }))
342                    }
343                    _ => None
344                };
345                if let Some(n) = new_instr {
346                    *instr = n;
347                }
348            }).map_err(|e| eyre::eyre!("{e}"))?;
349        }
350
351        Ok(())
352    }
353
354    fn post_combine(
355        &mut self,
356        module: &mut walrus::Module,
357        ctx: &GeneratorCtx,
358    ) -> eyre::Result<()> {
359        if !ctx.threads {
360            return Ok(());
361        }
362
363        let vfs_mem = ctx.vfs_used_memory_id.unwrap();
364        let target_mem = ctx.target_names.first()
365            .and_then(|n| ctx.target_used_memory_id.as_ref().unwrap().get(n).copied());
366
367        use crate::util::{WalrusFID, WalrusUtilModule};
368
369        if let Some(id) = ("wvl_atomic", "__wvl_atomic_wait32_vfs").get_fid(&module.imports).ok() {
370            module.replace_imported_func(id, |(builder, args)| {
371                builder.func_body()
372                    .local_get(args[0])
373                    .local_get(args[1])
374                    .local_get(args[2])
375                    .atomic_wait(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 }, false);
376            }).map_err(|e| eyre::eyre!("{e}"))?;
377        }
378
379        if let Some(id) = ("wvl_atomic", "__wvl_atomic_notify_vfs").get_fid(&module.imports).ok() {
380            module.replace_imported_func(id, |(builder, args)| {
381                builder.func_body()
382                    .local_get(args[0])
383                    .local_get(args[1])
384                    .atomic_notify(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 });
385            }).map_err(|e| eyre::eyre!("{e}"))?;
386        }
387
388        if let Some(id) = ("wvl_atomic", "__wvl_atomic_cmpxchg32_vfs").get_fid(&module.imports).ok() {
389            module.replace_imported_func(id, |(builder, args)| {
390                builder.func_body()
391                    .local_get(args[0])
392                    .local_get(args[1])
393                    .local_get(args[2])
394                    .cmpxchg(vfs_mem, walrus::ir::AtomicWidth::I32, walrus::ir::MemArg { align: 4, offset: 0 });
395            }).map_err(|e| eyre::eyre!("{e}"))?;
396        }
397
398        if let Some(id) = ("wvl_atomic", "__wvl_atomic_store32_vfs").get_fid(&module.imports).ok() {
399            module.replace_imported_func(id, |(builder, args)| {
400                builder.func_body()
401                    .local_get(args[0])
402                    .local_get(args[1])
403                    .store(vfs_mem, walrus::ir::StoreKind::I32 { atomic: true }, walrus::ir::MemArg { align: 4, offset: 0 });
404            }).map_err(|e| eyre::eyre!("{e}"))?;
405        }
406
407        if let Some(target_mem) = target_mem {
408            if let Some(id) = ("wvl_atomic", "__wvl_atomic_load32_target").get_fid(&module.imports).ok() {
409                module.replace_imported_func(id, |(builder, args)| {
410                    builder.func_body()
411                        .local_get(args[0])
412                        .load(target_mem, walrus::ir::LoadKind::I32 { atomic: true }, walrus::ir::MemArg { align: 4, offset: 0 });
413                }).map_err(|e| eyre::eyre!("{e}"))?;
414            }
415
416            if let Some(id) = ("wvl_atomic", "__wvl_atomic_load64_target").get_fid(&module.imports).ok() {
417                module.replace_imported_func(id, |(builder, args)| {
418                    builder.func_body()
419                        .local_get(args[0])
420                        .load(target_mem, walrus::ir::LoadKind::I64 { atomic: true }, walrus::ir::MemArg { align: 8, offset: 0 });
421                }).map_err(|e| eyre::eyre!("{e}"))?;
422            }
423        }
424
425        Ok(())
426    }
427}