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/// Constants and format builders for renaming Thread spawn imports and exports during patching.
16#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
17#[strum(serialize_all = "snake_case")]
18pub enum ThreadsSpawnName<'a> {
19    /// Custom spawn anchor injected for bridging definitions.
20    ImportAnchor(&'a str),
21    /// Flag indicating whether the current instance is the root spawner thread.
22    IsRootSpawn,
23    #[strum(serialize = "wasi_thread_spawn___self")]
24    /// Function identifier for native WASI spawn capability.
25    WasiThreadSpawnSelf,
26    #[strum(serialize = "__self_wasi_thread_start")]
27    /// The starting routine mapping on thread creation execution.
28    SelfWasiThreadStart,
29    #[strum(serialize = "__self_wasi_thread_start_anchor")]
30    /// The underlying static bridge to anchor thread origins.
31    SelfWasiThreadStartAnchor,
32    /// Low level function signature to actually request system spawn.
33    RealThreadSpawnFn,
34    /// Entry stub function used when entering newly spawned routines.
35    WasiThreadStartEntry,
36    /// Specialized start function per WASM module target.
37    WasiThreadStart(&'a WasmName),
38    #[strum(serialize = "wasi_thread_start")]
39    /// Target resolving memory start capabilities per component.
40    WasiThreadStartDestination(&'a WasmName),
41    /// Wraps dynamic spawn allocations over components.
42    WasiThreadSpawn(&'a WasmName),
43    /// Cross-linking anchor marking a spawn location.
44    WasiThreadStartAnchor(&'a WasmName),
45    /// Initializer function for thread memory limits scaling.
46    ThreadInitializer,
47    /// Reference to the existing deprecated `_start` handling.
48    OldStart,
49}
50
51/// The thread spawn process itself within the VFS is also caught,
52/// but processing is performed to exclude only the root spawn from this.
53/// Relocate thread creation from root spawn to the outer layer
54///
55/// **Why this is needed:**
56/// Per `IMPORTS_EXPORTS_EVOLUTION_DETAILED.md`, `wasi-threads:spawn` requires special handling
57/// because thread creation from the "root spawn" (the original process invoking `_start`)
58/// differs from spawning within explicitly created WASI threads.
59///
60/// This generator ensures that only the root spawn initiates the true thread start sequence
61/// on the host by intercepting `wasi_thread_spawn`. Real execution is forwarded via
62/// `__wasip1_vfs_real_thread_spawn_fn`, avoiding recursive or improper initializations.
63#[derive(Debug, Default)]
64pub struct ThreadsSpawn;
65
66impl Generator for ThreadsSpawn {
67    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
68        if !ctx.threads {
69            return Ok(());
70        }
71
72        let name = <Wasip1ThreadsABIFunc as VariantNames>::VARIANTS
73            .iter()
74            .exactly_one()
75            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIFunc")?; // thread-spawn
76
77        let component_name = gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, name);
78
79        module.exports.erase_with(
80            &UniqueName::ThreadsSpawn(&ThreadsSpawnName::ImportAnchor(name)),
81            ctx.unstable_print_debug,
82        )?;
83
84        let real_thread_spawn_fn_id =
85            (UniqueName::THREADS_MODULE_ROOT, &component_name).get_fid(&module.imports)?;
86
87        let branch_fid =
88            UniqueName::ThreadsSpawn(&ThreadsSpawnName::IsRootSpawn).get_fid(&module.exports)?;
89
90        if let Some(normal_thread_spawn_fn_id) = (UniqueName::WASIP1_THREADS_ABI_MODULE, name)
91            .get_fid(&module.imports)
92            .ok()
93        {
94            let self_thread_spawn_fn_id =
95                UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawnSelf)
96                    .get_fid(&module.exports)?;
97
98            module
99                .exports
100                .erase_with(self_thread_spawn_fn_id, ctx.unstable_print_debug)?;
101
102            use walrus::ValType::I32;
103            let real_thread_spawn_fn_id = module
104                .add_func(&[I32], &[I32], |builder, args| {
105                    let mut body = builder.func_body();
106                    body.call(branch_fid)
107                        .if_else(
108                            I32,
109                            |then| {
110                                then.local_get(args[0]) // pass the argument to thread-spawn
111                                    .call(real_thread_spawn_fn_id);
112                            },
113                            |else_| {
114                                else_
115                                    .local_get(args[0]) // pass the argument to thread-spawn
116                                    .call(self_thread_spawn_fn_id); // call thread-spawn
117                            },
118                        )
119                        .return_();
120
121                    Ok(())
122                })
123                .wrap_err("Failed to add real thread spawn function")?;
124
125            module
126                .renew_call_fn(normal_thread_spawn_fn_id, real_thread_spawn_fn_id)
127                .wrap_err("Failed to rewrite thread-spawn call")?;
128
129            let start_name = Wasip1ThreadsABIExportFunc::VARIANTS
130                .iter()
131                .exactly_one()
132                .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // wasi-thread-start
133
134            let exporting_thread_starter_id = start_name.get_fid(&module.exports)?;
135
136            module
137                .connect_func_alt_with_remove_export(
138                    (
139                        UniqueName::NAMESPACE,
140                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::SelfWasiThreadStart),
141                    ),
142                    start_name,
143                    ctx.unstable_print_debug,
144                )
145                .wrap_err("Failed to rewrite self_wasi_thread_start call in root spawn")?;
146
147            module.exports.erase_with(
148                &UniqueName::ThreadsSpawn(&ThreadsSpawnName::SelfWasiThreadStartAnchor),
149                ctx.unstable_print_debug,
150            )?;
151
152            if ctx.unstable_print_debug {
153                module.exports.add(
154                    &UniqueName::ThreadsSpawn(&ThreadsSpawnName::RealThreadSpawnFn).to_string(),
155                    real_thread_spawn_fn_id,
156                );
157            }
158
159            // __wasip1_vfs_self_wasi_thread_start
160            module
161                .renew_call_fn(
162                    (
163                        UniqueName::NAMESPACE,
164                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartEntry),
165                    ),
166                    exporting_thread_starter_id,
167                )
168                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
169
170            module
171                .exports
172                .erase_with(branch_fid, ctx.unstable_print_debug)?;
173        } else {
174            log::warn!("No normal thread-spawn found, why are you not using threads?");
175
176            let component_name =
177                gen_component_name(UniqueName::WASIP1_THREADS_ABI_MODULE_ALT, name);
178
179            let _real_thread_spawn_fn_id =
180                (UniqueName::THREADS_MODULE_ROOT, &component_name).get_fid(&module.imports)?;
181
182            module.exports.erase_with(
183                &UniqueName::ThreadsSpawn(&ThreadsSpawnName::IsRootSpawn),
184                ctx.unstable_print_debug,
185            )?;
186
187            let fake_start = module
188                .add_func(
189                    &[walrus::ValType::I32, walrus::ValType::I32],
190                    &[],
191                    |_, _| Ok(()),
192                )
193                .wrap_err("Failed to add fake thread spawn function")?;
194
195            module
196                .renew_call_fn(
197                    (
198                        UniqueName::NAMESPACE,
199                        &UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartEntry),
200                    ),
201                    fake_start,
202                )
203                .wrap_err("Failed to connect wasip1-vfs.wasi_thread_start")?;
204
205            // println!("unstable_print_debug: {}", ctx.unstable_print_debug);
206        }
207
208        Ok(())
209    }
210
211    fn pre_target(
212        &mut self,
213        module: &mut walrus::Module,
214        ctx: &GeneratorCtx,
215        external: &crate::generator::ModuleExternal,
216    ) -> eyre::Result<()> {
217        if !ctx.threads {
218            return Ok(());
219        }
220
221        let wasm = &external.name;
222
223        let start_name = Wasip1ThreadsABIFunc::VARIANTS
224            .iter()
225            .exactly_one()
226            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // thread-spawn
227
228        module
229            .imports
230            .find_mut((UniqueName::WASIP1_THREADS_ABI_MODULE, start_name))
231            .ok()
232            .map(|import| {
233                // import.name = format!("__wasip1_vfs_wasi_thread_spawn_{name}");
234                import.name =
235                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadSpawn(wasm)).to_string();
236            });
237
238        let export_name = Wasip1ThreadsABIExportFunc::VARIANTS
239            .iter()
240            .exactly_one()
241            .wrap_err("Expected exactly one variant for Wasip1ThreadsABIExportFunc")?; // wasi_thread_start
242
243        module
244            .exports
245            .iter_mut()
246            .find(|export| export.name == *export_name)
247            .map(|export| {
248                export.name =
249                    UniqueName::ThreadsSpawn(&ThreadsSpawnName::WasiThreadStartDestination(wasm))
250                        .to_string();
251            });
252
253        Ok(())
254    }
255}
256
257/// https://github.com/rust-lang/rust/issues/146843
258/// thread spawn is broken on wasm32-wasip1-threads for building library
259///
260/// **Why this is needed:**
261/// Currently, thread initialization routines (e.g. `__wasm_init_tls`) can be improperly tied
262/// or omitted during WASM generation (see rust-lang/rust#146843). This patching strategy
263/// wraps the original `_start` with an injected `ThreadInitializer` call if one is exported.
264#[derive(Debug, Default)]
265pub struct ThreadsSpawnPatch;
266
267impl Generator for ThreadsSpawnPatch {
268    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
269        let initializer = UniqueName::ThreadsSpawn(&ThreadsSpawnName::ThreadInitializer)
270            .get_fid(&module.exports)
271            .ok();
272
273        if let Some(init_id) = initializer {
274            module
275                .exports
276                .erase_with(init_id, ctx.unstable_print_debug)?;
277
278            let init = ctx.starts.thread_patch.get_fid(&module.exports)?;
279            module
280                .funcs
281                .get_mut(init)
282                .kind
283                .unwrap_local_mut()
284                .builder_mut()
285                .func_body()
286                .call(init_id);
287        }
288
289        Ok(())
290    }
291}