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#[derive(Debug, strum::AsRefStr, strum::EnumCount, Hash, PartialEq, Eq)]
18#[strum(serialize_all = "snake_case")]
19pub enum ThreadsSpawnName<'a> {
20 ImportAnchor(&'a str),
22 IsRootSpawn,
24 #[strum(serialize = "wasi_thread_spawn___self")]
25 WasiThreadSpawnSelf,
27 #[strum(serialize = "__self_wasi_thread_start")]
28 SelfWasiThreadStart,
30 #[strum(serialize = "__self_wasi_thread_start_anchor")]
31 SelfWasiThreadStartAnchor,
33 RealThreadSpawnFn,
35 WasiThreadStartEntry,
37 WasiThreadStart(&'a WasmName),
39 #[strum(serialize = "wasi_thread_start")]
40 WasiThreadStartDestination(&'a WasmName),
42 WasiThreadSpawn(&'a WasmName),
44 WasiThreadStartAnchor(&'a WasmName),
46 ThreadInitializer,
48 OldStart,
50}
51
52#[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")?; 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]) .call(real_thread_spawn_fn_id);
113 },
114 |else_| {
115 else_
116 .local_get(args[0]) .call(self_thread_spawn_fn_id); },
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")?; 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 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 }
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")?; module
230 .imports
231 .find_mut((UniqueName::WASIP1_THREADS_ABI_MODULE, start_name))
232 .ok()
233 .map(|import| {
234 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")?; 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#[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#[derive(Debug, Default)]
297pub struct AtomicPatch;
298
299impl AtomicPatch {
300 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 body.i32_const(wasm_id as i32);
323 body.local_get(args[0]);
325 if offset != 0 {
326 body.i32_const(offset as i32)
327 .binop(walrus::ir::BinaryOp::I32Add);
328 }
329 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 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 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 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 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}