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 AtomicPatch {
300    /// Creates a wrapper function that adds a constant offset to the address argument,
301    /// then delegates to the base VFS import function.
302    ///
303    /// For wait32/wait64: `(addr, expected, timeout) -> (addr+offset, expected, timeout)`
304    /// For notify:        `(addr, count)             -> (addr+offset, count)`
305    fn make_offset_wrapper(
306        module: &mut walrus::Module,
307        base_func: walrus::FunctionId,
308        offset: u64,
309        params: &[walrus::ValType],
310        results: &[walrus::ValType],
311    ) -> walrus::FunctionId {
312        use walrus::ValType::{I32, I64};
313
314        let mut builder = walrus::FunctionBuilder::new(&mut module.types, params, results);
315        let args: Vec<walrus::LocalId> = params
316            .iter()
317            .map(|ty| module.locals.add(*ty))
318            .collect();
319
320        {
321            let mut body = builder.func_body();
322            // addr + offset
323            body.local_get(args[0])
324                .i32_const(offset as i32)
325                .binop(walrus::ir::BinaryOp::I32Add);
326            // remaining args
327            for arg in &args[1..] {
328                body.local_get(*arg);
329            }
330            body.call(base_func);
331        }
332
333        builder.finish(args, &mut module.funcs)
334    }
335}
336
337impl Generator for AtomicPatch {
338    fn pre_target(
339        &mut self,
340        module: &mut walrus::Module,
341        ctx: &GeneratorCtx,
342        _external: &crate::generator::ModuleExternal,
343    ) -> eyre::Result<()> {
344        if !ctx.threads {
345            return Ok(());
346        }
347
348        use walrus::ValType::{I32, I64};
349
350        // Import base VFS atomic functions (offset=0 cases)
351        let wait32_ty = module.types.add(&[I32, I32, I64], &[I32]);
352        let (wait32_import, _) = module.add_import_func("wasi_snapshot_preview1", "__vfs_atomic_wait32", wait32_ty);
353
354        let wait64_ty = module.types.add(&[I32, I64, I64], &[I32]);
355        let (wait64_import, _) = module.add_import_func("wasi_snapshot_preview1", "__vfs_atomic_wait64", wait64_ty);
356
357        let notify_ty = module.types.add(&[I32, I32], &[I32]);
358        let (notify_import, _) = module.add_import_func("wasi_snapshot_preview1", "__vfs_atomic_notify", notify_ty);
359
360        // --- Pass 1: Collect unique non-zero offsets via DFS visitor ---
361        let mut wait32_offsets = std::collections::BTreeSet::new();
362        let mut wait64_offsets = std::collections::BTreeSet::new();
363        let mut notify_offsets = std::collections::BTreeSet::new();
364
365        {
366            struct OffsetCollector<'a> {
367                wait32: &'a mut std::collections::BTreeSet<u64>,
368                wait64: &'a mut std::collections::BTreeSet<u64>,
369                notify: &'a mut std::collections::BTreeSet<u64>,
370            }
371
372            impl<'instr> walrus::ir::Visitor<'instr> for OffsetCollector<'_> {
373                fn start_instr_seq(&mut self, seq: &'instr walrus::ir::InstrSeq) {
374                    for (instr, _) in seq.instrs.iter() {
375                        match instr {
376                            walrus::ir::Instr::AtomicWait(w) if w.arg.offset != 0 => {
377                                if w.sixty_four {
378                                    self.wait64.insert(w.arg.offset);
379                                } else {
380                                    self.wait32.insert(w.arg.offset);
381                                }
382                            }
383                            walrus::ir::Instr::AtomicNotify(n) if n.arg.offset != 0 => {
384                                self.notify.insert(n.arg.offset);
385                            }
386                            _ => {}
387                        }
388                    }
389                }
390            }
391
392            for (_fid, func) in module.funcs.iter_local() {
393                let entry = func.entry_block();
394                let mut visitor = OffsetCollector {
395                    wait32: &mut wait32_offsets,
396                    wait64: &mut wait64_offsets,
397                    notify: &mut notify_offsets,
398                };
399                walrus::ir::dfs_in_order(&mut visitor, func, entry);
400            }
401        }
402
403        // --- Create wrapper functions for each unique non-zero offset ---
404        let mut wait32_map: std::collections::HashMap<u64, walrus::FunctionId> = std::collections::HashMap::new();
405        let mut wait64_map: std::collections::HashMap<u64, walrus::FunctionId> = std::collections::HashMap::new();
406        let mut notify_map: std::collections::HashMap<u64, walrus::FunctionId> = std::collections::HashMap::new();
407
408        for offset in wait32_offsets {
409            let fid = Self::make_offset_wrapper(module, wait32_import, offset, &[I32, I32, I64], &[I32]);
410            log::info!("Created wait32 wrapper for offset {offset}");
411            wait32_map.insert(offset, fid);
412        }
413        for offset in wait64_offsets {
414            let fid = Self::make_offset_wrapper(module, wait64_import, offset, &[I32, I64, I64], &[I32]);
415            log::info!("Created wait64 wrapper for offset {offset}");
416            wait64_map.insert(offset, fid);
417        }
418        for offset in notify_offsets {
419            let fid = Self::make_offset_wrapper(module, notify_import, offset, &[I32, I32], &[I32]);
420            log::info!("Created notify wrapper for offset {offset}");
421            notify_map.insert(offset, fid);
422        }
423
424        // --- Pass 2: Rewrite all atomic.wait/notify to calls ---
425        for (_fid, func) in module.funcs.iter_local_mut() {
426            let mut builder = func.builder_mut();
427            let mut body = builder.func_body();
428            
429            body.rewrite(|instr, _pos| {
430                let new_instr = match instr {
431                    walrus::ir::Instr::AtomicWait(w) => {
432                        if !w.sixty_four {
433                            let target = if w.arg.offset == 0 {
434                                wait32_import
435                            } else {
436                                wait32_map[&w.arg.offset]
437                            };
438                            Some(walrus::ir::Instr::Call(walrus::ir::Call { func: target }))
439                        } else {
440                            let target = if w.arg.offset == 0 {
441                                wait64_import
442                            } else {
443                                wait64_map[&w.arg.offset]
444                            };
445                            Some(walrus::ir::Instr::Call(walrus::ir::Call { func: target }))
446                        }
447                    }
448                    walrus::ir::Instr::AtomicNotify(n) => {
449                        let target = if n.arg.offset == 0 {
450                            notify_import
451                        } else {
452                            notify_map[&n.arg.offset]
453                        };
454                        Some(walrus::ir::Instr::Call(walrus::ir::Call { func: target }))
455                    }
456                    _ => None
457                };
458                if let Some(n) = new_instr {
459                    *instr = n;
460                }
461            }).map_err(|e| eyre::eyre!("{e}"))?;
462        }
463
464        Ok(())
465    }
466
467
468    fn post_combine(
469        &mut self,
470        module: &mut walrus::Module,
471        ctx: &GeneratorCtx,
472    ) -> eyre::Result<()> {
473        if !ctx.threads {
474            return Ok(());
475        }
476
477        let vfs_mem = ctx.vfs_used_memory_id.unwrap();
478        let target_mem = ctx.target_names.first()
479            .and_then(|n| ctx.target_used_memory_id.as_ref().unwrap().get(n).copied());
480
481        use crate::util::{WalrusFID, WalrusUtilModule};
482
483        if let Some(id) = ("wvl_atomic", "__wvl_atomic_wait32_vfs").get_fid(&module.imports).ok() {
484            module.replace_imported_func(id, |(builder, args)| {
485                builder.func_body()
486                    .local_get(args[0])
487                    .local_get(args[1])
488                    .local_get(args[2])
489                    .atomic_wait(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 }, false);
490            }).map_err(|e| eyre::eyre!("{e}"))?;
491        }
492
493        if let Some(id) = ("wvl_atomic", "__wvl_atomic_notify_vfs").get_fid(&module.imports).ok() {
494            module.replace_imported_func(id, |(builder, args)| {
495                builder.func_body()
496                    .local_get(args[0])
497                    .local_get(args[1])
498                    .atomic_notify(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 });
499            }).map_err(|e| eyre::eyre!("{e}"))?;
500        }
501
502        if let Some(id) = ("wvl_atomic", "__wvl_atomic_cmpxchg32_vfs").get_fid(&module.imports).ok() {
503            module.replace_imported_func(id, |(builder, args)| {
504                builder.func_body()
505                    .local_get(args[0])
506                    .local_get(args[1])
507                    .local_get(args[2])
508                    .cmpxchg(vfs_mem, walrus::ir::AtomicWidth::I32, walrus::ir::MemArg { align: 4, offset: 0 });
509            }).map_err(|e| eyre::eyre!("{e}"))?;
510        }
511
512        if let Some(id) = ("wvl_atomic", "__wvl_atomic_store32_vfs").get_fid(&module.imports).ok() {
513            module.replace_imported_func(id, |(builder, args)| {
514                builder.func_body()
515                    .local_get(args[0])
516                    .local_get(args[1])
517                    .store(vfs_mem, walrus::ir::StoreKind::I32 { atomic: true }, walrus::ir::MemArg { align: 4, offset: 0 });
518            }).map_err(|e| eyre::eyre!("{e}"))?;
519        }
520
521        if let Some(target_mem) = target_mem {
522            if let Some(id) = ("wvl_atomic", "__wvl_atomic_load32_target").get_fid(&module.imports).ok() {
523                module.replace_imported_func(id, |(builder, args)| {
524                    builder.func_body()
525                        .local_get(args[0])
526                        .load(target_mem, walrus::ir::LoadKind::I32 { atomic: true }, walrus::ir::MemArg { align: 4, offset: 0 });
527                }).map_err(|e| eyre::eyre!("{e}"))?;
528            }
529
530            if let Some(id) = ("wvl_atomic", "__wvl_atomic_load64_target").get_fid(&module.imports).ok() {
531                module.replace_imported_func(id, |(builder, args)| {
532                    builder.func_body()
533                        .local_get(args[0])
534                        .load(target_mem, walrus::ir::LoadKind::I64 { atomic: true }, walrus::ir::MemArg { align: 8, offset: 0 });
535                }).map_err(|e| eyre::eyre!("{e}"))?;
536            }
537        }
538
539        Ok(())
540    }
541}