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 let funcs: Vec<(walrus::FunctionId, &mut walrus::LocalFunction)> = module.funcs.iter_local_mut().collect();
429 use rayon::prelude::*;
430 funcs.into_par_iter().try_for_each(|(_fid, func)| {
431 let mut body = func.builder_mut().func_body();
432
433 body.rewrite(|instr, _pos| {
434 let new_instr = match instr {
435 walrus::ir::Instr::AtomicWait(w) => {
436 if !w.sixty_four {
437 let target = wait32_map[&w.arg.offset];
438 Some(walrus::ir::Instr::Call(walrus::ir::Call { func: target }))
439 } else {
440 let target = wait64_map[&w.arg.offset];
441 Some(walrus::ir::Instr::Call(walrus::ir::Call { func: target }))
442 }
443 }
444 walrus::ir::Instr::AtomicNotify(n) => {
445 let target = notify_map[&n.arg.offset];
446 Some(walrus::ir::Instr::Call(walrus::ir::Call { func: target }))
447 }
448 _ => None
449 };
450 if let Some(n) = new_instr {
451 *instr = n;
452 }
453 }).map_err(|e| eyre::eyre!("{e}"))?;
454
455 eyre::Ok(())
456 })?;
457
458 Ok(())
459 }
460
461
462 fn post_combine(
463 &mut self,
464 module: &mut walrus::Module,
465 ctx: &GeneratorCtx,
466 ) -> eyre::Result<()> {
467 if !ctx.threads {
468 return Ok(());
469 }
470
471 let vfs_mem = ctx.vfs_used_memory_id.unwrap();
472
473 use crate::util::{WalrusFID, WalrusUtilModule};
474
475 if let Some(id) = ("wvl_atomic", "__wvl_atomic_wait32_vfs").get_fid(&module.imports).ok() {
476 module.replace_imported_func(id, |(builder, args)| {
477 builder.func_body()
478 .local_get(args[0])
479 .local_get(args[1])
480 .local_get(args[2])
481 .atomic_wait(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 }, false);
482 }).map_err(|e| eyre::eyre!("{e}"))?;
483 }
484
485 if let Some(id) = ("wvl_atomic", "__wvl_atomic_notify_vfs").get_fid(&module.imports).ok() {
486 module.replace_imported_func(id, |(builder, args)| {
487 builder.func_body()
488 .local_get(args[0])
489 .local_get(args[1])
490 .atomic_notify(vfs_mem, walrus::ir::MemArg { align: 4, offset: 0 });
491 }).map_err(|e| eyre::eyre!("{e}"))?;
492 }
493
494 if let Some(id) = ("wvl_atomic", "__wvl_atomic_cmpxchg32_vfs").get_fid(&module.imports).ok() {
495 module.replace_imported_func(id, |(builder, args)| {
496 builder.func_body()
497 .local_get(args[0])
498 .local_get(args[1])
499 .local_get(args[2])
500 .cmpxchg(vfs_mem, walrus::ir::AtomicWidth::I32, walrus::ir::MemArg { align: 4, offset: 0 });
501 }).map_err(|e| eyre::eyre!("{e}"))?;
502 }
503
504 if let Some(id) = ("wvl_atomic", "__wvl_atomic_store32_vfs").get_fid(&module.imports).ok() {
505 module.replace_imported_func(id, |(builder, args)| {
506 builder.func_body()
507 .local_get(args[0])
508 .local_get(args[1])
509 .store(vfs_mem, walrus::ir::StoreKind::I32 { atomic: true }, walrus::ir::MemArg { align: 4, offset: 0 });
510 }).map_err(|e| eyre::eyre!("{e}"))?;
511 }
512
513 if let Some(id) = ("wvl_atomic", "__wvl_atomic_load32_target").get_fid(&module.imports).ok() {
514 module.replace_imported_func(id, |(builder, args)| {
515 let mut body = builder.func_body();
516 for (i, name) in ctx.target_names.iter().enumerate() {
517 if let Some(&mem) = ctx.target_used_memory_id.as_ref().unwrap().get(name) {
518 body.local_get(args[0])
519 .i32_const(i as i32)
520 .binop(walrus::ir::BinaryOp::I32Eq)
521 .if_else(
522 None,
523 |then| {
524 then.local_get(args[1])
525 .load(mem, walrus::ir::LoadKind::I32 { atomic: true }, walrus::ir::MemArg { align: 4, offset: 0 })
526 .return_();
527 },
528 |_else| {}
529 );
530 }
531 }
532 body.unreachable();
533 }).map_err(|e| eyre::eyre!("{e}"))?;
534 }
535
536 if let Some(id) = ("wvl_atomic", "__wvl_atomic_load64_target").get_fid(&module.imports).ok() {
537 module.replace_imported_func(id, |(builder, args)| {
538 let mut body = builder.func_body();
539 for (i, name) in ctx.target_names.iter().enumerate() {
540 if let Some(&mem) = ctx.target_used_memory_id.as_ref().unwrap().get(name) {
541 body.local_get(args[0])
542 .i32_const(i as i32)
543 .binop(walrus::ir::BinaryOp::I32Eq)
544 .if_else(
545 None,
546 |then| {
547 then.local_get(args[1])
548 .load(mem, walrus::ir::LoadKind::I64 { atomic: true }, walrus::ir::MemArg { align: 8, offset: 0 })
549 .return_();
550 },
551 |_else| {}
552 );
553 }
554 }
555 body.unreachable();
556 }).map_err(|e| eyre::eyre!("{e}"))?;
557 }
558
559 Ok(())
560 }
561}