wasi_virt_layer_cli/wasm_stream/passes/
atomic_patch.rs1use crate::wasm_stream::pipeline::{StreamPass, par_process_code_section};
2use eyre::Result;
3use std::collections::{BTreeSet, HashMap};
4use wasm_encoder::{
5 CustomSection, DataCountSection, DataSection, ElementSection, EntityType, ExportSection,
6 Function, FunctionSection, GlobalSection, ImportSection, Instruction, Module, StartSection,
7 TypeSection, ValType,
8};
9use wasmparser::{Parser, Payload, TypeRef};
10
11use crate::wasm_stream::translator::{
12 DefaultRebinder, Rebind, translate, translate_global_type, translate_memory_type,
13 translate_ref_type, translate_table_type,
14};
15
16pub struct AtomicPatchStreamPass {
17 pub threads: bool,
18 pub target_index: u32,
19}
20
21impl AtomicPatchStreamPass {
22 pub fn new(threads: bool, target_index: u32) -> Self {
23 Self {
24 threads,
25 target_index,
26 }
27 }
28}
29
30#[derive(Clone, Copy)]
31struct FuncRebinder {
32 import_func_count: u32,
33 shift_offset: u32,
34}
35
36impl Rebind for FuncRebinder {
37 fn function(&self, index: u32) -> u32 {
38 if index < self.import_func_count {
39 index
40 } else {
41 index + self.shift_offset
42 }
43 }
44}
45
46impl StreamPass for AtomicPatchStreamPass {
47 fn run(&mut self, input_wasm: &[u8]) -> Result<Vec<u8>> {
48 if !self.threads {
49 return Ok(input_wasm.to_vec());
50 }
51
52 let mut wait32_offsets = BTreeSet::new();
53 let mut wait64_offsets = BTreeSet::new();
54 let mut notify_offsets = BTreeSet::new();
55
56 let mut func_types = Vec::new();
57 let mut types = Vec::new();
58 let mut import_func_count = 0;
59
60 for payload in Parser::new(0).parse_all(input_wasm) {
61 match payload? {
62 Payload::TypeSection(s) => {
63 for t in s {
64 for sub_ty in t?.into_types() {
65 types.push(sub_ty);
66 }
67 }
68 }
69 Payload::FunctionSection(s) => {
70 for f in s {
71 func_types.push(f?);
72 }
73 }
74 Payload::ImportSection(s) => {
75 for group in s {
76 for import in group? {
77 let (_, import) = import?;
78 if let wasmparser::TypeRef::Func(f) = import.ty {
79 func_types.push(f);
80 import_func_count += 1;
81 }
82 }
83 }
84 }
85 Payload::CodeSectionStart { range, .. } => {
86 let reader = wasmparser::BinaryReader::new(
87 &input_wasm[range.start..range.end],
88 range.start,
89 );
90 let s = wasmparser::CodeSectionReader::new(reader)?;
91 for func_body in s {
92 let mut reader = func_body?.get_operators_reader()?;
93 while !reader.eof() {
94 match reader.read()? {
95 wasmparser::Operator::MemoryAtomicWait32 { memarg } => {
96 wait32_offsets.insert(memarg.offset);
97 }
98 wasmparser::Operator::MemoryAtomicWait64 { memarg } => {
99 wait64_offsets.insert(memarg.offset);
100 }
101 wasmparser::Operator::MemoryAtomicNotify { memarg } => {
102 notify_offsets.insert(memarg.offset);
103 }
104 _ => {}
105 }
106 }
107 }
108 }
109 _ => {}
110 }
111 }
112
113 if wait32_offsets.is_empty() && wait64_offsets.is_empty() && notify_offsets.is_empty() {
114 return Ok(input_wasm.to_vec());
115 }
116
117 let mut module = Module::new();
118
119 let mut wait32_import_ty = None;
120 let mut wait64_import_ty = None;
121 let mut notify_import_ty = None;
122
123 let mut wait32_wrap_ty = None;
124 let mut wait64_wrap_ty = None;
125 let mut notify_wrap_ty = None;
126
127 let mut type_sec = TypeSection::new();
128 for t in &types {
129 let enc_ty = crate::wasm_stream::translator::translate_sub_type(t, &DefaultRebinder);
130 type_sec.ty().subtype(&enc_ty);
131 }
132
133 let mut type_count = types.len() as u32;
134
135 let mut get_or_add_type = |params: &[ValType], results: &[ValType]| -> u32 {
136 for (i, t) in types.iter().enumerate() {
137 if let wasmparser::CompositeInnerType::Func(f) = &t.composite_type.inner {
138 if f.params().len() == params.len() && f.results().len() == results.len() {
139 let mut match_params = true;
140 for (a, b) in f.params().iter().zip(params.iter()) {
141 if crate::wasm_stream::translator::translate_val_type(
142 *a,
143 &DefaultRebinder,
144 ) != *b
145 {
146 match_params = false;
147 break;
148 }
149 }
150 let mut match_results = true;
151 for (a, b) in f.results().iter().zip(results.iter()) {
152 if crate::wasm_stream::translator::translate_val_type(
153 *a,
154 &DefaultRebinder,
155 ) != *b
156 {
157 match_results = false;
158 break;
159 }
160 }
161 if match_params && match_results {
162 return i as u32;
163 }
164 }
165 }
166 }
167 type_sec
168 .ty()
169 .function(params.iter().cloned(), results.iter().cloned());
170 let idx = type_count;
171 type_count += 1;
172 idx
173 };
174
175 let mut new_imports_count = 0;
176
177 if !wait32_offsets.is_empty() {
178 wait32_import_ty = Some(get_or_add_type(
179 &[ValType::I32, ValType::I32, ValType::I32, ValType::I64],
180 &[ValType::I32],
181 ));
182 wait32_wrap_ty = Some(get_or_add_type(
183 &[ValType::I32, ValType::I32, ValType::I64],
184 &[ValType::I32],
185 ));
186 new_imports_count += 1;
187 }
188 if !wait64_offsets.is_empty() {
189 wait64_import_ty = Some(get_or_add_type(
190 &[ValType::I32, ValType::I32, ValType::I64, ValType::I64],
191 &[ValType::I32],
192 ));
193 wait64_wrap_ty = Some(get_or_add_type(
194 &[ValType::I32, ValType::I64, ValType::I64],
195 &[ValType::I32],
196 ));
197 new_imports_count += 1;
198 }
199 if !notify_offsets.is_empty() {
200 notify_import_ty = Some(get_or_add_type(
201 &[ValType::I32, ValType::I32, ValType::I32],
202 &[ValType::I32],
203 ));
204 notify_wrap_ty = Some(get_or_add_type(
205 &[ValType::I32, ValType::I32],
206 &[ValType::I32],
207 ));
208 new_imports_count += 1;
209 }
210
211 module.section(&type_sec);
212
213 let mut func_count = import_func_count;
214 let mut wait32_import_idx = None;
215 let mut wait64_import_idx = None;
216 let mut notify_import_idx = None;
217
218 let mut wait32_map = HashMap::new();
219 let mut wait64_map = HashMap::new();
220 let mut notify_map = HashMap::new();
221
222 let rebinder = FuncRebinder {
223 import_func_count,
224 shift_offset: new_imports_count,
225 };
226
227 for payload in Parser::new(0).parse_all(input_wasm) {
228 let payload = payload?;
229 match &payload {
230 Payload::ImportSection(s) => {
231 let mut import_sec = ImportSection::new();
232 for group in s.clone() {
233 for import in group? {
234 let (_, import) = import?;
235 let ty = match import.ty {
236 TypeRef::Func(f) => EntityType::Function(f),
237 TypeRef::Table(t) => {
238 EntityType::Table(translate_table_type(t, &DefaultRebinder))
239 }
240 TypeRef::Memory(m) => EntityType::Memory(translate_memory_type(m)),
241 TypeRef::Global(g) => {
242 EntityType::Global(translate_global_type(g, &DefaultRebinder))
243 }
244 TypeRef::Tag(t) => EntityType::Tag(
245 crate::wasm_stream::translator::translate_tag_type(t),
246 ),
247 _ => unreachable!(),
248 };
249 import_sec.import(import.module, import.name, ty);
250 }
251 }
252 if let Some(ty) = wait32_import_ty {
253 import_sec.import(
254 "wasi_snapshot_preview1",
255 "__vfs_atomic_wait32",
256 EntityType::Function(ty),
257 );
258 wait32_import_idx = Some(func_count);
259 func_count += 1;
260 }
261 if let Some(ty) = wait64_import_ty {
262 import_sec.import(
263 "wasi_snapshot_preview1",
264 "__vfs_atomic_wait64",
265 EntityType::Function(ty),
266 );
267 wait64_import_idx = Some(func_count);
268 func_count += 1;
269 }
270 if let Some(ty) = notify_import_ty {
271 import_sec.import(
272 "wasi_snapshot_preview1",
273 "__vfs_atomic_notify",
274 EntityType::Function(ty),
275 );
276 notify_import_idx = Some(func_count);
277 func_count += 1;
278 }
279 module.section(&import_sec);
280 }
281 Payload::FunctionSection(s) => {
282 let mut func_sec = FunctionSection::new();
283 for f in s.clone() {
284 func_sec.function(f?);
285 func_count += 1;
286 }
287 for offset in &wait32_offsets {
288 func_sec.function(wait32_wrap_ty.unwrap());
289 wait32_map.insert(*offset, func_count);
290 func_count += 1;
291 }
292 for offset in &wait64_offsets {
293 func_sec.function(wait64_wrap_ty.unwrap());
294 wait64_map.insert(*offset, func_count);
295 func_count += 1;
296 }
297 for offset in ¬ify_offsets {
298 func_sec.function(notify_wrap_ty.unwrap());
299 notify_map.insert(*offset, func_count);
300 func_count += 1;
301 }
302 module.section(&func_sec);
303 }
304 Payload::TableSection(s) => {
305 let mut sec = wasm_encoder::TableSection::new();
306 for t in s.clone() {
307 sec.table(translate_table_type(t?.ty, &rebinder));
308 }
309 module.section(&sec);
310 }
311 Payload::MemorySection(s) => {
312 let mut sec = wasm_encoder::MemorySection::new();
313 for m in s.clone() {
314 sec.memory(translate_memory_type(m?));
315 }
316 module.section(&sec);
317 }
318 Payload::TagSection(s) => {
319 let mut sec = wasm_encoder::TagSection::new();
320 for t in s.clone() {
321 let t = t?;
322 sec.tag(wasm_encoder::TagType {
323 kind: wasm_encoder::TagKind::Exception,
324 func_type_idx: t.func_type_idx,
325 });
326 }
327 module.section(&sec);
328 }
329 Payload::GlobalSection(s) => {
330 let mut sec = GlobalSection::new();
331 for g in s.clone() {
332 let g = g?;
333 let mut instrs = Vec::new();
334 for op in g.init_expr.get_operators_reader() {
335 let op = op?;
336 if matches!(op, wasmparser::Operator::End) {
337 continue;
338 }
339 instrs.push(translate(&op, &rebinder));
340 }
341 let init_expr = wasm_encoder::ConstExpr::extended(instrs);
342 sec.global(translate_global_type(g.ty, &rebinder), &init_expr);
343 }
344 module.section(&sec);
345 }
346 Payload::ExportSection(s) => {
347 let mut sec = ExportSection::new();
348 for e in s.clone() {
349 let e = e?;
350 let kind = match e.kind {
351 wasmparser::ExternalKind::Func
352 | wasmparser::ExternalKind::FuncExact => wasm_encoder::ExportKind::Func,
353 wasmparser::ExternalKind::Table => wasm_encoder::ExportKind::Table,
354 wasmparser::ExternalKind::Memory => wasm_encoder::ExportKind::Memory,
355 wasmparser::ExternalKind::Global => wasm_encoder::ExportKind::Global,
356 wasmparser::ExternalKind::Tag => wasm_encoder::ExportKind::Tag,
357 };
358 let idx = match e.kind {
359 wasmparser::ExternalKind::Func
360 | wasmparser::ExternalKind::FuncExact => rebinder.function(e.index),
361 _ => e.index,
362 };
363 sec.export(e.name, kind, idx);
364 }
365 module.section(&sec);
366 }
367 Payload::StartSection { func, .. } => {
368 module.section(&StartSection {
369 function_index: rebinder.function(*func),
370 });
371 }
372 Payload::ElementSection(s) => {
373 let mut sec = ElementSection::new();
374 for elem in s.clone() {
375 let elem = elem?;
376 let items = match elem.items {
377 wasmparser::ElementItems::Functions(f) => {
378 let funcs_vec = f
379 .into_iter()
380 .map(|idx| Ok(rebinder.function(idx?)))
381 .collect::<Result<Vec<u32>, eyre::Error>>()?;
382 wasm_encoder::Elements::Functions(std::borrow::Cow::Owned(
383 funcs_vec,
384 ))
385 }
386 wasmparser::ElementItems::Expressions(ref_ty, exprs) => {
387 let mut const_exprs = Vec::new();
388 for expr in exprs {
389 let mut instrs = Vec::new();
390 for op in expr?.get_operators_reader() {
391 let op = op?;
392 if matches!(op, wasmparser::Operator::End) {
393 continue;
394 }
395 instrs.push(translate(&op, &rebinder));
396 }
397 const_exprs.push(wasm_encoder::ConstExpr::extended(instrs));
398 }
399 let enc_ref_ty = translate_ref_type(ref_ty, &rebinder);
400 wasm_encoder::Elements::Expressions(
401 enc_ref_ty,
402 std::borrow::Cow::Owned(const_exprs),
403 )
404 }
405 };
406 match elem.kind {
407 wasmparser::ElementKind::Passive => {
408 sec.passive(items);
409 }
410 wasmparser::ElementKind::Active {
411 table_index,
412 offset_expr,
413 } => {
414 let mut instrs = Vec::new();
415 for op in offset_expr.get_operators_reader() {
416 let op = op?;
417 if matches!(op, wasmparser::Operator::End) {
418 continue;
419 }
420 instrs.push(translate(&op, &rebinder));
421 }
422 let offset = wasm_encoder::ConstExpr::extended(instrs);
423 sec.active(table_index, &offset, items);
424 }
425 wasmparser::ElementKind::Declared => {
426 sec.declared(items);
427 }
428 }
429 }
430 module.section(&sec);
431 }
432 Payload::DataCountSection { count, .. } => {
433 module.section(&DataCountSection { count: *count });
434 }
435 Payload::DataSection(s) => {
436 let mut sec = DataSection::new();
437 for d in s.clone() {
438 let d = d?;
439 match d.kind {
440 wasmparser::DataKind::Passive => {
441 sec.passive(d.data.iter().copied());
442 }
443 wasmparser::DataKind::Active {
444 memory_index,
445 offset_expr,
446 } => {
447 let mut instrs = Vec::new();
448 for op in offset_expr.get_operators_reader() {
449 let op = op?;
450 if matches!(op, wasmparser::Operator::End) {
451 continue;
452 }
453 instrs.push(translate(&op, &rebinder));
454 }
455 let offset = wasm_encoder::ConstExpr::extended(instrs);
456 sec.active(memory_index, &offset, d.data.iter().copied());
457 }
458 }
459 }
460 module.section(&sec);
461 }
462 Payload::CodeSectionStart { range, .. } => {
463 let reader = wasmparser::BinaryReader::new(
464 &input_wasm[range.start..range.end],
465 range.start,
466 );
467 let s = wasmparser::CodeSectionReader::new(reader)?;
468 let wait32_map_clone = wait32_map.clone();
469 let wait64_map_clone = wait64_map.clone();
470 let notify_map_clone = notify_map.clone();
471 let mut code_sec = par_process_code_section(s, move |_, func_body| {
472 let mut locals = Vec::new();
473 let mut locals_reader = func_body.get_locals_reader()?;
474 for _ in 0..locals_reader.get_count() {
475 let (count, ty) = locals_reader.read()?;
476 locals.push((
477 count,
478 crate::wasm_stream::translator::translate_val_type(ty, &rebinder),
479 ));
480 }
481 let mut func = Function::new(locals);
482 let mut reader = func_body.get_operators_reader()?;
483 while !reader.eof() {
484 let op = reader.read()?;
485 match op {
486 wasmparser::Operator::MemoryAtomicWait32 { memarg } => {
487 func.instruction(&Instruction::Call(
488 wait32_map_clone[&memarg.offset],
489 ));
490 }
491 wasmparser::Operator::MemoryAtomicWait64 { memarg } => {
492 func.instruction(&Instruction::Call(
493 wait64_map_clone[&memarg.offset],
494 ));
495 }
496 wasmparser::Operator::MemoryAtomicNotify { memarg } => {
497 func.instruction(&Instruction::Call(
498 notify_map_clone[&memarg.offset],
499 ));
500 }
501 _ => {
502 func.instruction(&translate(&op, &rebinder));
503 }
504 }
505 }
506 Ok(func)
507 })?;
508
509 let target_id = self.target_index as i32;
510
511 for offset in &wait32_offsets {
512 let mut func = Function::new(Vec::new());
513 func.instruction(&Instruction::I32Const(target_id));
514 func.instruction(&Instruction::LocalGet(0));
515 if *offset > 0 {
516 func.instruction(&Instruction::I32Const(*offset as i32));
517 func.instruction(&Instruction::I32Add);
518 }
519 func.instruction(&Instruction::LocalGet(1));
520 func.instruction(&Instruction::LocalGet(2));
521 func.instruction(&Instruction::Call(wait32_import_idx.unwrap()));
522 func.instruction(&Instruction::End);
523 code_sec.function(&func);
524 }
525 for offset in &wait64_offsets {
526 let mut func = Function::new(Vec::new());
527 func.instruction(&Instruction::I32Const(target_id));
528 func.instruction(&Instruction::LocalGet(0));
529 if *offset > 0 {
530 func.instruction(&Instruction::I32Const(*offset as i32));
531 func.instruction(&Instruction::I32Add);
532 }
533 func.instruction(&Instruction::LocalGet(1));
534 func.instruction(&Instruction::LocalGet(2));
535 func.instruction(&Instruction::Call(wait64_import_idx.unwrap()));
536 func.instruction(&Instruction::End);
537 code_sec.function(&func);
538 }
539 for offset in ¬ify_offsets {
540 let mut func = Function::new(Vec::new());
541 func.instruction(&Instruction::I32Const(target_id));
542 func.instruction(&Instruction::LocalGet(0));
543 if *offset > 0 {
544 func.instruction(&Instruction::I32Const(*offset as i32));
545 func.instruction(&Instruction::I32Add);
546 }
547 func.instruction(&Instruction::LocalGet(1));
548 func.instruction(&Instruction::Call(notify_import_idx.unwrap()));
549 func.instruction(&Instruction::End);
550 code_sec.function(&func);
551 }
552
553 module.section(&code_sec);
554 }
555 Payload::CustomSection(c) => {
556 module.section(&CustomSection {
557 name: c.name().into(),
558 data: std::borrow::Cow::Borrowed(c.data()),
559 });
560 }
561 _ => {}
562 }
563 }
564
565 Ok(module.finish())
566 }
567}