Skip to main content

wasi_virt_layer_cli/wasm_stream/passes/
atomic_patch.rs

1use 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    pub detect_deadlock: bool,
20}
21
22#[cfg(test)]
23mod tests {
24    use super::AtomicPatchStreamPass;
25    use crate::wasm_stream::passes::deadlock_thread_id::DeadlockThreadIdPreTargetStreamPass;
26    use crate::wasm_stream::pipeline::StreamPass;
27
28    fn import_func_type(bytes: &[u8], import_name: &str) -> Option<u32> {
29        for payload in wasmparser::Parser::new(0).parse_all(bytes) {
30            if let Ok(wasmparser::Payload::ImportSection(section)) = payload {
31                for group in section.into_iter().flatten() {
32                    for import in group.into_iter().flatten() {
33                        let (_, import) = import;
34                        if import.name == import_name {
35                            if let wasmparser::TypeRef::Func(type_idx) = import.ty {
36                                return Some(type_idx);
37                            }
38                        }
39                    }
40                }
41            }
42        }
43        None
44    }
45
46    fn func_param_count(bytes: &[u8], type_idx: u32) -> Option<usize> {
47        let mut current = 0;
48        for payload in wasmparser::Parser::new(0).parse_all(bytes) {
49            if let Ok(wasmparser::Payload::TypeSection(section)) = payload {
50                for ty in section.into_iter().flatten() {
51                    for sub_ty in ty.into_types() {
52                        if current == type_idx {
53                            if let wasmparser::CompositeInnerType::Func(func) =
54                                sub_ty.composite_type.inner
55                            {
56                                return Some(func.params().len());
57                            }
58                        }
59                        current += 1;
60                    }
61                }
62            }
63        }
64        None
65    }
66
67    #[test]
68    fn detector_enabled_wait32_import_includes_thread_id_param() {
69        let input = wat::parse_str(
70            r#"
71            (module
72              (memory 1 1 shared)
73              (func $wasi_thread_start (param i32 i32))
74              (func $_start
75                (drop
76                  (memory.atomic.wait32 align=4
77                    (i32.const 0)
78                    (i32.const 0)
79                    (i64.const -1))))
80              (export "memory" (memory 0))
81              (export "wasi_thread_start" (func $wasi_thread_start))
82              (export "_start" (func $_start)))
83            "#,
84        )
85        .unwrap();
86        let with_thread_id = DeadlockThreadIdPreTargetStreamPass::new(true)
87            .run(&input)
88            .unwrap();
89        let output = AtomicPatchStreamPass::new(true, 3, true)
90            .run(&with_thread_id)
91            .unwrap();
92
93        let type_idx = import_func_type(&output, "__vfs_atomic_wait32").unwrap();
94        assert_eq!(func_param_count(&output, type_idx), Some(5));
95    }
96
97    #[test]
98    fn detector_enabled_atomic_store_imports_write_observer() {
99        let input = wat::parse_str(
100            r#"
101            (module
102              (memory 1 1 shared)
103              (func $wasi_thread_start (param i32 i32))
104              (func $_start
105                (i32.atomic.store align=4
106                  (i32.const 0)
107                  (i32.const 1)))
108              (export "memory" (memory 0))
109              (export "wasi_thread_start" (func $wasi_thread_start))
110              (export "_start" (func $_start)))
111            "#,
112        )
113        .unwrap();
114        let with_thread_id = DeadlockThreadIdPreTargetStreamPass::new(true)
115            .run(&input)
116            .unwrap();
117        let output = AtomicPatchStreamPass::new(true, 3, true)
118            .run(&with_thread_id)
119            .unwrap();
120
121        assert!(import_func_type(&output, "__vfs_atomic_observe_write").is_some());
122        wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
123            .validate_all(&output)
124            .unwrap();
125    }
126
127    #[test]
128    fn detector_enabled_atomic_rmw_and_cmpxchg_validate() {
129        let input = wat::parse_str(
130            r#"
131            (module
132              (memory 1 1 shared)
133              (func $wasi_thread_start (param i32 i32))
134              (func $_start
135                (drop
136                  (i32.atomic.rmw.add align=4
137                    (i32.const 0)
138                    (i32.const 1)))
139                (drop
140                  (i64.atomic.rmw.cmpxchg align=8
141                    (i32.const 8)
142                    (i64.const 0)
143                    (i64.const 1))))
144              (export "memory" (memory 0))
145              (export "wasi_thread_start" (func $wasi_thread_start))
146              (export "_start" (func $_start)))
147            "#,
148        )
149        .unwrap();
150        let with_thread_id = DeadlockThreadIdPreTargetStreamPass::new(true)
151            .run(&input)
152            .unwrap();
153        let output = AtomicPatchStreamPass::new(true, 3, true)
154            .run(&with_thread_id)
155            .unwrap();
156
157        assert!(import_func_type(&output, "__vfs_atomic_observe_write").is_some());
158        wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
159            .validate_all(&output)
160            .unwrap();
161    }
162}
163
164impl AtomicPatchStreamPass {
165    pub fn new(threads: bool, target_index: u32, detect_deadlock: bool) -> Self {
166        Self {
167            threads,
168            target_index,
169            detect_deadlock,
170        }
171    }
172}
173
174#[derive(Clone, Copy)]
175struct FuncRebinder {
176    import_func_count: u32,
177    shift_offset: u32,
178}
179
180impl Rebind for FuncRebinder {
181    fn function(&self, index: u32) -> u32 {
182        if index < self.import_func_count {
183            index
184        } else {
185            index + self.shift_offset
186        }
187    }
188}
189
190#[derive(Clone, Copy)]
191enum AtomicWriteShape {
192    StoreI32 { width: i32 },
193    StoreI64 { width: i32 },
194    RmwI32 { width: i32 },
195    RmwI64 { width: i32 },
196    CmpxchgI32 { width: i32 },
197    CmpxchgI64 { width: i32 },
198}
199
200fn atomic_write_shape(
201    op: &wasmparser::Operator<'_>,
202) -> Option<(wasmparser::MemArg, AtomicWriteShape)> {
203    use wasmparser::Operator::*;
204    match op {
205        I32AtomicStore { memarg } => Some((*memarg, AtomicWriteShape::StoreI32 { width: 4 })),
206        I64AtomicStore { memarg } => Some((*memarg, AtomicWriteShape::StoreI64 { width: 8 })),
207        I32AtomicStore8 { memarg } => Some((*memarg, AtomicWriteShape::StoreI32 { width: 1 })),
208        I32AtomicStore16 { memarg } => Some((*memarg, AtomicWriteShape::StoreI32 { width: 2 })),
209        I64AtomicStore8 { memarg } => Some((*memarg, AtomicWriteShape::StoreI64 { width: 1 })),
210        I64AtomicStore16 { memarg } => Some((*memarg, AtomicWriteShape::StoreI64 { width: 2 })),
211        I64AtomicStore32 { memarg } => Some((*memarg, AtomicWriteShape::StoreI64 { width: 4 })),
212        I32AtomicRmwAdd { memarg }
213        | I32AtomicRmwSub { memarg }
214        | I32AtomicRmwAnd { memarg }
215        | I32AtomicRmwOr { memarg }
216        | I32AtomicRmwXor { memarg }
217        | I32AtomicRmwXchg { memarg } => Some((*memarg, AtomicWriteShape::RmwI32 { width: 4 })),
218        I64AtomicRmwAdd { memarg }
219        | I64AtomicRmwSub { memarg }
220        | I64AtomicRmwAnd { memarg }
221        | I64AtomicRmwOr { memarg }
222        | I64AtomicRmwXor { memarg }
223        | I64AtomicRmwXchg { memarg } => Some((*memarg, AtomicWriteShape::RmwI64 { width: 8 })),
224        I32AtomicRmw8AddU { memarg }
225        | I32AtomicRmw8SubU { memarg }
226        | I32AtomicRmw8AndU { memarg }
227        | I32AtomicRmw8OrU { memarg }
228        | I32AtomicRmw8XorU { memarg }
229        | I32AtomicRmw8XchgU { memarg } => Some((*memarg, AtomicWriteShape::RmwI32 { width: 1 })),
230        I32AtomicRmw16AddU { memarg }
231        | I32AtomicRmw16SubU { memarg }
232        | I32AtomicRmw16AndU { memarg }
233        | I32AtomicRmw16OrU { memarg }
234        | I32AtomicRmw16XorU { memarg }
235        | I32AtomicRmw16XchgU { memarg } => Some((*memarg, AtomicWriteShape::RmwI32 { width: 2 })),
236        I64AtomicRmw8AddU { memarg }
237        | I64AtomicRmw8SubU { memarg }
238        | I64AtomicRmw8AndU { memarg }
239        | I64AtomicRmw8OrU { memarg }
240        | I64AtomicRmw8XorU { memarg }
241        | I64AtomicRmw8XchgU { memarg } => Some((*memarg, AtomicWriteShape::RmwI64 { width: 1 })),
242        I64AtomicRmw16AddU { memarg }
243        | I64AtomicRmw16SubU { memarg }
244        | I64AtomicRmw16AndU { memarg }
245        | I64AtomicRmw16OrU { memarg }
246        | I64AtomicRmw16XorU { memarg }
247        | I64AtomicRmw16XchgU { memarg } => Some((*memarg, AtomicWriteShape::RmwI64 { width: 2 })),
248        I64AtomicRmw32AddU { memarg }
249        | I64AtomicRmw32SubU { memarg }
250        | I64AtomicRmw32AndU { memarg }
251        | I64AtomicRmw32OrU { memarg }
252        | I64AtomicRmw32XorU { memarg }
253        | I64AtomicRmw32XchgU { memarg } => Some((*memarg, AtomicWriteShape::RmwI64 { width: 4 })),
254        I32AtomicRmwCmpxchg { memarg } => {
255            Some((*memarg, AtomicWriteShape::CmpxchgI32 { width: 4 }))
256        }
257        I64AtomicRmwCmpxchg { memarg } => {
258            Some((*memarg, AtomicWriteShape::CmpxchgI64 { width: 8 }))
259        }
260        I32AtomicRmw8CmpxchgU { memarg } => {
261            Some((*memarg, AtomicWriteShape::CmpxchgI32 { width: 1 }))
262        }
263        I32AtomicRmw16CmpxchgU { memarg } => {
264            Some((*memarg, AtomicWriteShape::CmpxchgI32 { width: 2 }))
265        }
266        I64AtomicRmw8CmpxchgU { memarg } => {
267            Some((*memarg, AtomicWriteShape::CmpxchgI64 { width: 1 }))
268        }
269        I64AtomicRmw16CmpxchgU { memarg } => {
270            Some((*memarg, AtomicWriteShape::CmpxchgI64 { width: 2 }))
271        }
272        I64AtomicRmw32CmpxchgU { memarg } => {
273            Some((*memarg, AtomicWriteShape::CmpxchgI64 { width: 4 }))
274        }
275        _ => None,
276    }
277}
278
279fn function_param_count(types: &[wasmparser::SubType], type_idx: u32) -> u32 {
280    let Some(ty) = types.get(type_idx as usize) else {
281        return 0;
282    };
283    if let wasmparser::CompositeInnerType::Func(func) = &ty.composite_type.inner {
284        func.params().len() as u32
285    } else {
286        0
287    }
288}
289
290fn emit_observe_write(
291    func: &mut Function,
292    thread_id_global: Option<u32>,
293    observe_write_import_idx: Option<u32>,
294    target_id: i32,
295    addr_local: u32,
296    offset: u64,
297    width: i32,
298) {
299    let (Some(global), Some(import_idx)) = (thread_id_global, observe_write_import_idx) else {
300        return;
301    };
302    func.instruction(&Instruction::GlobalGet(global));
303    func.instruction(&Instruction::I32Const(target_id));
304    func.instruction(&Instruction::LocalGet(addr_local));
305    if offset > 0 {
306        func.instruction(&Instruction::I32Const(offset as i32));
307        func.instruction(&Instruction::I32Add);
308    }
309    func.instruction(&Instruction::I32Const(width));
310    func.instruction(&Instruction::Call(import_idx));
311}
312
313impl StreamPass for AtomicPatchStreamPass {
314    fn run(&mut self, input_wasm: &[u8]) -> Result<Vec<u8>> {
315        if !self.threads {
316            return Ok(input_wasm.to_vec());
317        }
318
319        let mut wait32_offsets = BTreeSet::new();
320        let mut wait64_offsets = BTreeSet::new();
321        let mut notify_offsets = BTreeSet::new();
322        let mut has_atomic_write = false;
323
324        let mut func_types = Vec::new();
325        let mut types = Vec::new();
326        let mut import_func_count = 0;
327        let mut thread_id_global = None;
328
329        for payload in Parser::new(0).parse_all(input_wasm) {
330            match payload? {
331                Payload::TypeSection(s) => {
332                    for t in s {
333                        for sub_ty in t?.into_types() {
334                            types.push(sub_ty);
335                        }
336                    }
337                }
338                Payload::FunctionSection(s) => {
339                    for f in s {
340                        func_types.push(f?);
341                    }
342                }
343                Payload::ImportSection(s) => {
344                    for group in s {
345                        for import in group? {
346                            let (_, import) = import?;
347                            if let wasmparser::TypeRef::Func(f) = import.ty {
348                                func_types.push(f);
349                                import_func_count += 1;
350                            }
351                        }
352                    }
353                }
354                Payload::CodeSectionStart { range, .. } => {
355                    let target_id = self.target_index as i32;
356                    let reader = wasmparser::BinaryReader::new(
357                        &input_wasm[range.start..range.end],
358                        range.start,
359                    );
360                    let s = wasmparser::CodeSectionReader::new(reader)?;
361                    for func_body in s {
362                        let mut reader = func_body?.get_operators_reader()?;
363                        while !reader.eof() {
364                            match reader.read()? {
365                                wasmparser::Operator::MemoryAtomicWait32 { memarg } => {
366                                    wait32_offsets.insert(memarg.offset);
367                                }
368                                wasmparser::Operator::MemoryAtomicWait64 { memarg } => {
369                                    wait64_offsets.insert(memarg.offset);
370                                }
371                                wasmparser::Operator::MemoryAtomicNotify { memarg } => {
372                                    notify_offsets.insert(memarg.offset);
373                                }
374                                op => {
375                                    has_atomic_write |= atomic_write_shape(&op).is_some();
376                                }
377                            }
378                        }
379                    }
380                }
381                Payload::CustomSection(section) => {
382                    if section.name()
383                        == crate::wasm_stream::passes::deadlock_thread_id::THREAD_ID_GLOBAL_SECTION
384                    {
385                        let data = section.data();
386                        if data.len() == 4 {
387                            thread_id_global = Some(u32::from_le_bytes(
388                                data.try_into().expect("metadata length checked"),
389                            ));
390                        }
391                    }
392                }
393                _ => {}
394            }
395        }
396
397        if wait32_offsets.is_empty()
398            && wait64_offsets.is_empty()
399            && notify_offsets.is_empty()
400            && !(self.detect_deadlock && has_atomic_write)
401        {
402            return Ok(input_wasm.to_vec());
403        }
404
405        let thread_id_global = if self.detect_deadlock {
406            Some(thread_id_global.ok_or_else(|| {
407                eyre::eyre!(
408                    "deadlock detection requires DeadlockThreadIdPreTargetStreamPass before AtomicPatchStreamPass"
409                )
410            })?)
411        } else {
412            None
413        };
414
415        let mut module = Module::new();
416
417        let mut wait32_import_ty = None;
418        let mut wait64_import_ty = None;
419        let mut notify_import_ty = None;
420        let mut observe_write_import_ty = None;
421
422        let mut wait32_wrap_ty = None;
423        let mut wait64_wrap_ty = None;
424        let mut notify_wrap_ty = None;
425
426        let mut type_sec = TypeSection::new();
427        for t in &types {
428            let enc_ty = crate::wasm_stream::translator::translate_sub_type(t, &DefaultRebinder);
429            type_sec.ty().subtype(&enc_ty);
430        }
431
432        let mut type_count = types.len() as u32;
433
434        let mut get_or_add_type = |params: &[ValType], results: &[ValType]| -> u32 {
435            for (i, t) in types.iter().enumerate() {
436                if let wasmparser::CompositeInnerType::Func(f) = &t.composite_type.inner {
437                    if f.params().len() == params.len() && f.results().len() == results.len() {
438                        let mut match_params = true;
439                        for (a, b) in f.params().iter().zip(params.iter()) {
440                            if crate::wasm_stream::translator::translate_val_type(
441                                *a,
442                                &DefaultRebinder,
443                            ) != *b
444                            {
445                                match_params = false;
446                                break;
447                            }
448                        }
449                        let mut match_results = true;
450                        for (a, b) in f.results().iter().zip(results.iter()) {
451                            if crate::wasm_stream::translator::translate_val_type(
452                                *a,
453                                &DefaultRebinder,
454                            ) != *b
455                            {
456                                match_results = false;
457                                break;
458                            }
459                        }
460                        if match_params && match_results {
461                            return i as u32;
462                        }
463                    }
464                }
465            }
466            type_sec
467                .ty()
468                .function(params.iter().cloned(), results.iter().cloned());
469            let idx = type_count;
470            type_count += 1;
471            idx
472        };
473
474        let mut new_imports_count = 0;
475
476        if !wait32_offsets.is_empty() {
477            let wait32_import_params: &[ValType] = if self.detect_deadlock {
478                &[
479                    ValType::I32,
480                    ValType::I32,
481                    ValType::I32,
482                    ValType::I32,
483                    ValType::I64,
484                ]
485            } else {
486                &[ValType::I32, ValType::I32, ValType::I32, ValType::I64]
487            };
488            wait32_import_ty = Some(get_or_add_type(wait32_import_params, &[ValType::I32]));
489            wait32_wrap_ty = Some(get_or_add_type(
490                &[ValType::I32, ValType::I32, ValType::I64],
491                &[ValType::I32],
492            ));
493            new_imports_count += 1;
494        }
495        if !wait64_offsets.is_empty() {
496            let wait64_import_params: &[ValType] = if self.detect_deadlock {
497                &[
498                    ValType::I32,
499                    ValType::I32,
500                    ValType::I32,
501                    ValType::I64,
502                    ValType::I64,
503                ]
504            } else {
505                &[ValType::I32, ValType::I32, ValType::I64, ValType::I64]
506            };
507            wait64_import_ty = Some(get_or_add_type(wait64_import_params, &[ValType::I32]));
508            wait64_wrap_ty = Some(get_or_add_type(
509                &[ValType::I32, ValType::I64, ValType::I64],
510                &[ValType::I32],
511            ));
512            new_imports_count += 1;
513        }
514        if !notify_offsets.is_empty() {
515            let notify_import_params: &[ValType] = if self.detect_deadlock {
516                &[ValType::I32, ValType::I32, ValType::I32, ValType::I32]
517            } else {
518                &[ValType::I32, ValType::I32, ValType::I32]
519            };
520            notify_import_ty = Some(get_or_add_type(notify_import_params, &[ValType::I32]));
521            notify_wrap_ty = Some(get_or_add_type(
522                &[ValType::I32, ValType::I32],
523                &[ValType::I32],
524            ));
525            new_imports_count += 1;
526        }
527        if self.detect_deadlock && has_atomic_write {
528            observe_write_import_ty = Some(get_or_add_type(
529                &[ValType::I32, ValType::I32, ValType::I32, ValType::I32],
530                &[],
531            ));
532            new_imports_count += 1;
533        }
534
535        module.section(&type_sec);
536
537        let mut func_count = import_func_count;
538        let mut wait32_import_idx = None;
539        let mut wait64_import_idx = None;
540        let mut notify_import_idx = None;
541        let mut observe_write_import_idx = None;
542        let mut imports_emitted = false;
543
544        let mut wait32_map = HashMap::new();
545        let mut wait64_map = HashMap::new();
546        let mut notify_map = HashMap::new();
547
548        let rebinder = FuncRebinder {
549            import_func_count,
550            shift_offset: new_imports_count,
551        };
552
553        for payload in Parser::new(0).parse_all(input_wasm) {
554            let payload = payload?;
555            match &payload {
556                Payload::ImportSection(s) => {
557                    let mut import_sec = ImportSection::new();
558                    for group in s.clone() {
559                        for import in group? {
560                            let (_, import) = import?;
561                            let ty = match import.ty {
562                                TypeRef::Func(f) => EntityType::Function(f),
563                                TypeRef::Table(t) => {
564                                    EntityType::Table(translate_table_type(t, &DefaultRebinder))
565                                }
566                                TypeRef::Memory(m) => EntityType::Memory(translate_memory_type(m)),
567                                TypeRef::Global(g) => {
568                                    EntityType::Global(translate_global_type(g, &DefaultRebinder))
569                                }
570                                TypeRef::Tag(t) => EntityType::Tag(
571                                    crate::wasm_stream::translator::translate_tag_type(t),
572                                ),
573                                _ => unreachable!(),
574                            };
575                            import_sec.import(import.module, import.name, ty);
576                        }
577                    }
578                    if let Some(ty) = wait32_import_ty {
579                        import_sec.import(
580                            "wasi_snapshot_preview1",
581                            "__vfs_atomic_wait32",
582                            EntityType::Function(ty),
583                        );
584                        wait32_import_idx = Some(func_count);
585                        func_count += 1;
586                    }
587                    if let Some(ty) = wait64_import_ty {
588                        import_sec.import(
589                            "wasi_snapshot_preview1",
590                            "__vfs_atomic_wait64",
591                            EntityType::Function(ty),
592                        );
593                        wait64_import_idx = Some(func_count);
594                        func_count += 1;
595                    }
596                    if let Some(ty) = notify_import_ty {
597                        import_sec.import(
598                            "wasi_snapshot_preview1",
599                            "__vfs_atomic_notify",
600                            EntityType::Function(ty),
601                        );
602                        notify_import_idx = Some(func_count);
603                        func_count += 1;
604                    }
605                    if let Some(ty) = observe_write_import_ty {
606                        import_sec.import(
607                            "wasi_snapshot_preview1",
608                            "__vfs_atomic_observe_write",
609                            EntityType::Function(ty),
610                        );
611                        observe_write_import_idx = Some(func_count);
612                        func_count += 1;
613                    }
614                    module.section(&import_sec);
615                    imports_emitted = true;
616                }
617                Payload::FunctionSection(s) => {
618                    if !imports_emitted {
619                        let mut import_sec = ImportSection::new();
620                        if let Some(ty) = wait32_import_ty {
621                            import_sec.import(
622                                "wasi_snapshot_preview1",
623                                "__vfs_atomic_wait32",
624                                EntityType::Function(ty),
625                            );
626                            wait32_import_idx = Some(func_count);
627                            func_count += 1;
628                        }
629                        if let Some(ty) = wait64_import_ty {
630                            import_sec.import(
631                                "wasi_snapshot_preview1",
632                                "__vfs_atomic_wait64",
633                                EntityType::Function(ty),
634                            );
635                            wait64_import_idx = Some(func_count);
636                            func_count += 1;
637                        }
638                        if let Some(ty) = notify_import_ty {
639                            import_sec.import(
640                                "wasi_snapshot_preview1",
641                                "__vfs_atomic_notify",
642                                EntityType::Function(ty),
643                            );
644                            notify_import_idx = Some(func_count);
645                            func_count += 1;
646                        }
647                        if let Some(ty) = observe_write_import_ty {
648                            import_sec.import(
649                                "wasi_snapshot_preview1",
650                                "__vfs_atomic_observe_write",
651                                EntityType::Function(ty),
652                            );
653                            observe_write_import_idx = Some(func_count);
654                            func_count += 1;
655                        }
656                        module.section(&import_sec);
657                        imports_emitted = true;
658                    }
659                    let mut func_sec = FunctionSection::new();
660                    for f in s.clone() {
661                        func_sec.function(f?);
662                        func_count += 1;
663                    }
664                    for offset in &wait32_offsets {
665                        func_sec.function(wait32_wrap_ty.unwrap());
666                        wait32_map.insert(*offset, func_count);
667                        func_count += 1;
668                    }
669                    for offset in &wait64_offsets {
670                        func_sec.function(wait64_wrap_ty.unwrap());
671                        wait64_map.insert(*offset, func_count);
672                        func_count += 1;
673                    }
674                    for offset in &notify_offsets {
675                        func_sec.function(notify_wrap_ty.unwrap());
676                        notify_map.insert(*offset, func_count);
677                        func_count += 1;
678                    }
679                    module.section(&func_sec);
680                }
681                Payload::TableSection(s) => {
682                    let mut sec = wasm_encoder::TableSection::new();
683                    for t in s.clone() {
684                        sec.table(translate_table_type(t?.ty, &rebinder));
685                    }
686                    module.section(&sec);
687                }
688                Payload::MemorySection(s) => {
689                    let mut sec = wasm_encoder::MemorySection::new();
690                    for m in s.clone() {
691                        sec.memory(translate_memory_type(m?));
692                    }
693                    module.section(&sec);
694                }
695                Payload::TagSection(s) => {
696                    let mut sec = wasm_encoder::TagSection::new();
697                    for t in s.clone() {
698                        let t = t?;
699                        sec.tag(wasm_encoder::TagType {
700                            kind: wasm_encoder::TagKind::Exception,
701                            func_type_idx: t.func_type_idx,
702                        });
703                    }
704                    module.section(&sec);
705                }
706                Payload::GlobalSection(s) => {
707                    let mut sec = GlobalSection::new();
708                    for g in s.clone() {
709                        let g = g?;
710                        let mut instrs = Vec::new();
711                        for op in g.init_expr.get_operators_reader() {
712                            let op = op?;
713                            if matches!(op, wasmparser::Operator::End) {
714                                continue;
715                            }
716                            instrs.push(translate(&op, &rebinder));
717                        }
718                        let init_expr = wasm_encoder::ConstExpr::extended(instrs);
719                        sec.global(translate_global_type(g.ty, &rebinder), &init_expr);
720                    }
721                    module.section(&sec);
722                }
723                Payload::ExportSection(s) => {
724                    let mut sec = ExportSection::new();
725                    for e in s.clone() {
726                        let e = e?;
727                        let kind = match e.kind {
728                            wasmparser::ExternalKind::Func
729                            | wasmparser::ExternalKind::FuncExact => wasm_encoder::ExportKind::Func,
730                            wasmparser::ExternalKind::Table => wasm_encoder::ExportKind::Table,
731                            wasmparser::ExternalKind::Memory => wasm_encoder::ExportKind::Memory,
732                            wasmparser::ExternalKind::Global => wasm_encoder::ExportKind::Global,
733                            wasmparser::ExternalKind::Tag => wasm_encoder::ExportKind::Tag,
734                        };
735                        let idx = match e.kind {
736                            wasmparser::ExternalKind::Func
737                            | wasmparser::ExternalKind::FuncExact => rebinder.function(e.index),
738                            _ => e.index,
739                        };
740                        sec.export(e.name, kind, idx);
741                    }
742                    module.section(&sec);
743                }
744                Payload::StartSection { func, .. } => {
745                    module.section(&StartSection {
746                        function_index: rebinder.function(*func),
747                    });
748                }
749                Payload::ElementSection(s) => {
750                    let mut sec = ElementSection::new();
751                    for elem in s.clone() {
752                        let elem = elem?;
753                        let items = match elem.items {
754                            wasmparser::ElementItems::Functions(f) => {
755                                let funcs_vec = f
756                                    .into_iter()
757                                    .map(|idx| Ok(rebinder.function(idx?)))
758                                    .collect::<Result<Vec<u32>, eyre::Error>>()?;
759                                wasm_encoder::Elements::Functions(std::borrow::Cow::Owned(
760                                    funcs_vec,
761                                ))
762                            }
763                            wasmparser::ElementItems::Expressions(ref_ty, exprs) => {
764                                let mut const_exprs = Vec::new();
765                                for expr in exprs {
766                                    let mut instrs = Vec::new();
767                                    for op in expr?.get_operators_reader() {
768                                        let op = op?;
769                                        if matches!(op, wasmparser::Operator::End) {
770                                            continue;
771                                        }
772                                        instrs.push(translate(&op, &rebinder));
773                                    }
774                                    const_exprs.push(wasm_encoder::ConstExpr::extended(instrs));
775                                }
776                                let enc_ref_ty = translate_ref_type(ref_ty, &rebinder);
777                                wasm_encoder::Elements::Expressions(
778                                    enc_ref_ty,
779                                    std::borrow::Cow::Owned(const_exprs),
780                                )
781                            }
782                        };
783                        match elem.kind {
784                            wasmparser::ElementKind::Passive => {
785                                sec.passive(items);
786                            }
787                            wasmparser::ElementKind::Active {
788                                table_index,
789                                offset_expr,
790                            } => {
791                                let mut instrs = Vec::new();
792                                for op in offset_expr.get_operators_reader() {
793                                    let op = op?;
794                                    if matches!(op, wasmparser::Operator::End) {
795                                        continue;
796                                    }
797                                    instrs.push(translate(&op, &rebinder));
798                                }
799                                let offset = wasm_encoder::ConstExpr::extended(instrs);
800                                sec.active(table_index, &offset, items);
801                            }
802                            wasmparser::ElementKind::Declared => {
803                                sec.declared(items);
804                            }
805                        }
806                    }
807                    module.section(&sec);
808                }
809                Payload::DataCountSection { count, .. } => {
810                    module.section(&DataCountSection { count: *count });
811                }
812                Payload::DataSection(s) => {
813                    let mut sec = DataSection::new();
814                    for d in s.clone() {
815                        let d = d?;
816                        match d.kind {
817                            wasmparser::DataKind::Passive => {
818                                sec.passive(d.data.iter().copied());
819                            }
820                            wasmparser::DataKind::Active {
821                                memory_index,
822                                offset_expr,
823                            } => {
824                                let mut instrs = Vec::new();
825                                for op in offset_expr.get_operators_reader() {
826                                    let op = op?;
827                                    if matches!(op, wasmparser::Operator::End) {
828                                        continue;
829                                    }
830                                    instrs.push(translate(&op, &rebinder));
831                                }
832                                let offset = wasm_encoder::ConstExpr::extended(instrs);
833                                sec.active(memory_index, &offset, d.data.iter().copied());
834                            }
835                        }
836                    }
837                    module.section(&sec);
838                }
839                Payload::CodeSectionStart { range, .. } => {
840                    let target_id = self.target_index as i32;
841                    let reader = wasmparser::BinaryReader::new(
842                        &input_wasm[range.start..range.end],
843                        range.start,
844                    );
845                    let s = wasmparser::CodeSectionReader::new(reader)?;
846                    let wait32_map_clone = wait32_map.clone();
847                    let wait64_map_clone = wait64_map.clone();
848                    let notify_map_clone = notify_map.clone();
849                    let types_for_params = types.clone();
850                    let func_types_for_params = func_types.clone();
851                    let observe_write_import_idx_for_body = observe_write_import_idx;
852                    let thread_id_global_for_body = thread_id_global;
853                    let mut code_sec = par_process_code_section(s, move |body_idx, func_body| {
854                        let mut locals = Vec::new();
855                        let mut locals_reader = func_body.get_locals_reader()?;
856                        let mut local_count = 0u32;
857                        for _ in 0..locals_reader.get_count() {
858                            let (count, ty) = locals_reader.read()?;
859                            local_count += count;
860                            locals.push((
861                                count,
862                                crate::wasm_stream::translator::translate_val_type(ty, &rebinder),
863                            ));
864                        }
865                        let func_idx = import_func_count + body_idx as u32;
866                        let type_idx = func_types_for_params[func_idx as usize];
867                        let param_count = function_param_count(&types_for_params, type_idx);
868                        let temp_addr = param_count + local_count;
869                        let temp_i32 = temp_addr + 1;
870                        let temp_i32_b = temp_addr + 2;
871                        let temp_i64 = temp_addr + 3;
872                        let temp_i64_b = temp_addr + 4;
873                        if observe_write_import_idx_for_body.is_some() {
874                            locals.push((3, ValType::I32));
875                            locals.push((2, ValType::I64));
876                        }
877                        let mut func = Function::new(locals);
878                        let mut reader = func_body.get_operators_reader()?;
879                        while !reader.eof() {
880                            let op = reader.read()?;
881                            match op {
882                                wasmparser::Operator::MemoryAtomicWait32 { memarg } => {
883                                    func.instruction(&Instruction::Call(
884                                        wait32_map_clone[&memarg.offset],
885                                    ));
886                                }
887                                wasmparser::Operator::MemoryAtomicWait64 { memarg } => {
888                                    func.instruction(&Instruction::Call(
889                                        wait64_map_clone[&memarg.offset],
890                                    ));
891                                }
892                                wasmparser::Operator::MemoryAtomicNotify { memarg } => {
893                                    func.instruction(&Instruction::Call(
894                                        notify_map_clone[&memarg.offset],
895                                    ));
896                                }
897                                _ if observe_write_import_idx_for_body.is_some()
898                                    && atomic_write_shape(&op).is_some() =>
899                                {
900                                    let (memarg, shape) = atomic_write_shape(&op).unwrap();
901                                    match shape {
902                                        AtomicWriteShape::StoreI32 { width } => {
903                                            func.instruction(&Instruction::LocalSet(temp_i32));
904                                            func.instruction(&Instruction::LocalTee(temp_addr));
905                                            func.instruction(&Instruction::LocalGet(temp_i32));
906                                            func.instruction(&translate(&op, &rebinder));
907                                            emit_observe_write(
908                                                &mut func,
909                                                thread_id_global_for_body,
910                                                observe_write_import_idx_for_body,
911                                                target_id,
912                                                temp_addr,
913                                                memarg.offset,
914                                                width,
915                                            );
916                                        }
917                                        AtomicWriteShape::StoreI64 { width } => {
918                                            func.instruction(&Instruction::LocalSet(temp_i64));
919                                            func.instruction(&Instruction::LocalTee(temp_addr));
920                                            func.instruction(&Instruction::LocalGet(temp_i64));
921                                            func.instruction(&translate(&op, &rebinder));
922                                            emit_observe_write(
923                                                &mut func,
924                                                thread_id_global_for_body,
925                                                observe_write_import_idx_for_body,
926                                                target_id,
927                                                temp_addr,
928                                                memarg.offset,
929                                                width,
930                                            );
931                                        }
932                                        AtomicWriteShape::RmwI32 { width } => {
933                                            func.instruction(&Instruction::LocalSet(temp_i32));
934                                            func.instruction(&Instruction::LocalTee(temp_addr));
935                                            func.instruction(&Instruction::LocalGet(temp_i32));
936                                            func.instruction(&translate(&op, &rebinder));
937                                            emit_observe_write(
938                                                &mut func,
939                                                thread_id_global_for_body,
940                                                observe_write_import_idx_for_body,
941                                                target_id,
942                                                temp_addr,
943                                                memarg.offset,
944                                                width,
945                                            );
946                                        }
947                                        AtomicWriteShape::RmwI64 { width } => {
948                                            func.instruction(&Instruction::LocalSet(temp_i64));
949                                            func.instruction(&Instruction::LocalTee(temp_addr));
950                                            func.instruction(&Instruction::LocalGet(temp_i64));
951                                            func.instruction(&translate(&op, &rebinder));
952                                            emit_observe_write(
953                                                &mut func,
954                                                thread_id_global_for_body,
955                                                observe_write_import_idx_for_body,
956                                                target_id,
957                                                temp_addr,
958                                                memarg.offset,
959                                                width,
960                                            );
961                                        }
962                                        AtomicWriteShape::CmpxchgI32 { width } => {
963                                            func.instruction(&Instruction::LocalSet(temp_i32_b));
964                                            func.instruction(&Instruction::LocalSet(temp_i32));
965                                            func.instruction(&Instruction::LocalTee(temp_addr));
966                                            func.instruction(&Instruction::LocalGet(temp_i32));
967                                            func.instruction(&Instruction::LocalGet(temp_i32_b));
968                                            func.instruction(&translate(&op, &rebinder));
969                                            emit_observe_write(
970                                                &mut func,
971                                                thread_id_global_for_body,
972                                                observe_write_import_idx_for_body,
973                                                target_id,
974                                                temp_addr,
975                                                memarg.offset,
976                                                width,
977                                            );
978                                        }
979                                        AtomicWriteShape::CmpxchgI64 { width } => {
980                                            func.instruction(&Instruction::LocalSet(temp_i64_b));
981                                            func.instruction(&Instruction::LocalSet(temp_i64));
982                                            func.instruction(&Instruction::LocalTee(temp_addr));
983                                            func.instruction(&Instruction::LocalGet(temp_i64));
984                                            func.instruction(&Instruction::LocalGet(temp_i64_b));
985                                            func.instruction(&translate(&op, &rebinder));
986                                            emit_observe_write(
987                                                &mut func,
988                                                thread_id_global_for_body,
989                                                observe_write_import_idx_for_body,
990                                                target_id,
991                                                temp_addr,
992                                                memarg.offset,
993                                                width,
994                                            );
995                                        }
996                                    }
997                                }
998                                _ => {
999                                    func.instruction(&translate(&op, &rebinder));
1000                                }
1001                            }
1002                        }
1003                        Ok(func)
1004                    })?;
1005
1006                    for offset in &wait32_offsets {
1007                        let mut func = Function::new(Vec::new());
1008                        if let Some(global) = thread_id_global {
1009                            func.instruction(&Instruction::GlobalGet(global));
1010                        }
1011                        func.instruction(&Instruction::I32Const(target_id));
1012                        func.instruction(&Instruction::LocalGet(0));
1013                        if *offset > 0 {
1014                            func.instruction(&Instruction::I32Const(*offset as i32));
1015                            func.instruction(&Instruction::I32Add);
1016                        }
1017                        func.instruction(&Instruction::LocalGet(1));
1018                        func.instruction(&Instruction::LocalGet(2));
1019                        func.instruction(&Instruction::Call(wait32_import_idx.unwrap()));
1020                        func.instruction(&Instruction::End);
1021                        code_sec.function(&func);
1022                    }
1023                    for offset in &wait64_offsets {
1024                        let mut func = Function::new(Vec::new());
1025                        if let Some(global) = thread_id_global {
1026                            func.instruction(&Instruction::GlobalGet(global));
1027                        }
1028                        func.instruction(&Instruction::I32Const(target_id));
1029                        func.instruction(&Instruction::LocalGet(0));
1030                        if *offset > 0 {
1031                            func.instruction(&Instruction::I32Const(*offset as i32));
1032                            func.instruction(&Instruction::I32Add);
1033                        }
1034                        func.instruction(&Instruction::LocalGet(1));
1035                        func.instruction(&Instruction::LocalGet(2));
1036                        func.instruction(&Instruction::Call(wait64_import_idx.unwrap()));
1037                        func.instruction(&Instruction::End);
1038                        code_sec.function(&func);
1039                    }
1040                    for offset in &notify_offsets {
1041                        let mut func = Function::new(Vec::new());
1042                        if let Some(global) = thread_id_global {
1043                            func.instruction(&Instruction::GlobalGet(global));
1044                        }
1045                        func.instruction(&Instruction::I32Const(target_id));
1046                        func.instruction(&Instruction::LocalGet(0));
1047                        if *offset > 0 {
1048                            func.instruction(&Instruction::I32Const(*offset as i32));
1049                            func.instruction(&Instruction::I32Add);
1050                        }
1051                        func.instruction(&Instruction::LocalGet(1));
1052                        func.instruction(&Instruction::Call(notify_import_idx.unwrap()));
1053                        func.instruction(&Instruction::End);
1054                        code_sec.function(&func);
1055                    }
1056
1057                    module.section(&code_sec);
1058                }
1059                Payload::CustomSection(c) => {
1060                    module.section(&CustomSection {
1061                        name: c.name().into(),
1062                        data: std::borrow::Cow::Borrowed(c.data()),
1063                    });
1064                }
1065                _ => {}
1066            }
1067        }
1068
1069        Ok(module.finish())
1070    }
1071}