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