wasi_virt_layer-cli 0.6.0

CLI for the wasi_virt_layer crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
use eyre::Result;
use wasm_encoder::{
    CodeSection, ConstExpr, Function, FunctionSection, GlobalSection, Instruction, MemoryType,
    Module, RawSection, TypeSection, ValType,
};
use wasmparser::{ExternalKind, Payload, TypeRef};

use crate::wasm_stream::{
    pipeline::StreamPass,
    translator::{
        DefaultRebinder, Rebind, translate, translate_global_type, translate_sub_type,
        translate_val_type,
    },
};

struct OffsetRebinder {
    imported_funcs: u32,
    extra_funcs: u32,
}

impl Rebind for OffsetRebinder {
    fn function(&self, index: u32) -> u32 {
        if index < self.imported_funcs {
            index
        } else {
            index + self.extra_funcs
        }
    }
}

/// Inserts a fixed-size stack arena prefix into a multi-memory target module,
/// offsets all memory accesses, and virtualizes memory.size / memory.grow.
pub struct ExportStackArenaStreamPass {
    stack_size: u32,
    slots: u32,
}

impl ExportStackArenaStreamPass {
    pub const fn new(stack_size: u32, slots: u32) -> Self {
        Self { stack_size, slots }
    }

    pub fn arena_pages(&self) -> u32 {
        let bitmap_words = (self.slots + 31) / 32;
        let bitmap_bytes = bitmap_words * 4;
        let slots_bytes = self.stack_size * self.slots;
        (bitmap_bytes + slots_bytes).div_ceil(65536)
    }

    pub fn arena_offset(&self) -> u64 {
        (self.arena_pages() as u64) * 65536
    }
}

/// Temp locals used for saving value operands during address adjustment.
struct Temps {
    i32_idx: u32,
    i64_idx: u32,
    /// First additional local index (beyond orig locals + 2 temp locals)
    total_locals: u32,
}

fn tmp_local_for_type(ty: wasmparser::ValType, temps: &Temps) -> u32 {
    match ty {
        wasmparser::ValType::I32 | wasmparser::ValType::F32 => temps.i32_idx,
        wasmparser::ValType::I64 | wasmparser::ValType::F64 => temps.i64_idx,
        _ => temps.i32_idx,
    }
}

fn local_set_for(ty: ValType, temps: &Temps) -> Instruction<'static> {
    match ty {
        ValType::I32 | ValType::F32 | ValType::V128 | ValType::Ref(..) => {
            Instruction::LocalSet(temps.i32_idx)
        }
        ValType::I64 | ValType::F64 => Instruction::LocalSet(temps.i64_idx),
    }
}

fn local_get_for(ty: ValType, temps: &Temps) -> Instruction<'static> {
    match ty {
        ValType::I32 | ValType::F32 | ValType::V128 | ValType::Ref(..) => {
            Instruction::LocalGet(temps.i32_idx)
        }
        ValType::I64 | ValType::F64 => Instruction::LocalGet(temps.i64_idx),
    }
}

fn find_i32_result_type(types: &[wasmparser::SubType]) -> Option<u32> {
    types
        .iter()
        .position(|ty| {
            matches!(
                &ty.composite_type.inner,
                wasmparser::CompositeInnerType::Func(f)
                    if f.params().is_empty() && f.results() == [wasmparser::ValType::I32]
            )
        })
        .map(|i| i as u32)
}

fn find_i32_param_i32_result(types: &[wasmparser::SubType]) -> Option<u32> {
    types
        .iter()
        .position(|ty| {
            matches!(
                &ty.composite_type.inner,
                wasmparser::CompositeInnerType::Func(f)
                    if f.params() == [wasmparser::ValType::I32]
                        && f.results() == [wasmparser::ValType::I32]
            )
        })
        .map(|i| i as u32)
}

fn find_i64_result_type(types: &[wasmparser::SubType]) -> Option<u32> {
    types
        .iter()
        .position(|ty| {
            matches!(
                &ty.composite_type.inner,
                wasmparser::CompositeInnerType::Func(f)
                    if f.params().is_empty()
                        && f.results() == [wasmparser::ValType::I64]
            )
        })
        .map(|i| i as u32)
}

fn find_i32_param_void_result(types: &[wasmparser::SubType]) -> Option<u32> {
    types
        .iter()
        .position(|ty| {
            matches!(
                &ty.composite_type.inner,
                wasmparser::CompositeInnerType::Func(f)
                    if f.params() == [wasmparser::ValType::I32]
                        && f.results().is_empty()
            )
        })
        .map(|i| i as u32)
}

fn build_slot_acquire(bitmap_bytes: u32, slot_count: u32, stack_size: u32) -> Function {
    // () -> i64: packed (base << 32) | end, or 0 if no free slots
    // Locals: bitmap(i32), slot(i32), base(i32)
    let mut f = Function::new([(3, ValType::I32)]);

    // Outer labels:
    //   Block $done = label 2 (or deeper depending on nesting)
    //     Loop $retry = label 1
    //       Loop $try_slot = label 0 (inside $retry, directly)

    f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty)); // $done
    f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty)); // $retry

    // Load bitmap atomically: local 0 = i32.atomic.load(0)
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::I32AtomicLoad(wasm_encoder::MemArg {
        offset: 0,
        align: 2,
        memory_index: 0,
    }));
    f.instruction(&Instruction::LocalSet(0));

    // slot = 0
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::LocalSet(1));

    // $try_slot loop
    f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty)); // $try_slot

    // If slot >= slot_count → no free slots, return 0
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::I32Const(slot_count as i32));
    f.instruction(&Instruction::I32GeU);
    f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
    f.instruction(&Instruction::I64Const(0));
    f.instruction(&Instruction::Return);
    f.instruction(&Instruction::End);

    // If (bitmap & (1 << slot)) != 0 → skip, try next
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::I32Shl);
    f.instruction(&Instruction::I32And);
    f.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
    // Slot taken — increment and retry
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::I32Add);
    f.instruction(&Instruction::LocalSet(1));
    f.instruction(&Instruction::Br(1)); // back to $try_slot
    f.instruction(&Instruction::End);

    // Slot is free. Try atomic CAS
    // cmpxchg(addr=0, expected=local0, replacement=local0 | (1 << slot))
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::I32Shl);
    f.instruction(&Instruction::I32Or);
    f.instruction(&Instruction::I32AtomicRmwCmpxchg(wasm_encoder::MemArg {
        offset: 0,
        align: 2,
        memory_index: 0,
    }));

    // If old != bitmap → CAS failed, retry from bitmap load
    f.instruction(&Instruction::LocalGet(0));
    f.instruction(&Instruction::I32Ne);
    f.instruction(&Instruction::BrIf(2)); // break to $retry (label 2)

    // CAS succeeded! Compute base = bitmap_bytes + slot * stack_size
    f.instruction(&Instruction::I32Const(bitmap_bytes as i32));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::I32Const(stack_size as i32));
    f.instruction(&Instruction::I32Mul);
    f.instruction(&Instruction::I32Add);
    f.instruction(&Instruction::LocalSet(2));

    // Return pack(base, base + size)
    f.instruction(&Instruction::LocalGet(2));
    f.instruction(&Instruction::I64ExtendI32U);
    f.instruction(&Instruction::I64Const(32));
    f.instruction(&Instruction::I64Shl);
    f.instruction(&Instruction::LocalGet(2));
    f.instruction(&Instruction::I32Const(stack_size as i32));
    f.instruction(&Instruction::I32Add);
    f.instruction(&Instruction::I64ExtendI32U);
    f.instruction(&Instruction::I64Or);
    f.instruction(&Instruction::Return);

    // End $try_slot, $retry
    f.instruction(&Instruction::End);
    f.instruction(&Instruction::End);

    // End $done
    f.instruction(&Instruction::End);

    // No free slots
    f.instruction(&Instruction::I64Const(0));
    f.instruction(&Instruction::End);
    f
}

fn build_slot_release(_bitmap_bytes: u32) -> Function {
    // (slot_index: i32) → ()
    // Locals: bitmap(i32), cleared(i32)
    let mut f = Function::new([(1, ValType::I32), (2, ValType::I32)]);

    f.instruction(&Instruction::Block(wasm_encoder::BlockType::Empty));
    f.instruction(&Instruction::Loop(wasm_encoder::BlockType::Empty));

    // Load bitmap atomically: [bitmap], local 1 = bitmap
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::I32AtomicLoad(wasm_encoder::MemArg {
        offset: 0,
        align: 2,
        memory_index: 0,
    }));
    f.instruction(&Instruction::LocalTee(1));

    // Compute cleared = bitmap & ~(1 << slot_index)
    f.instruction(&Instruction::I32Const(1));
    f.instruction(&Instruction::LocalGet(0)); // param = slot_index
    f.instruction(&Instruction::I32Shl);
    f.instruction(&Instruction::I32Const(-1));
    f.instruction(&Instruction::I32Xor);
    f.instruction(&Instruction::I32And);
    f.instruction(&Instruction::LocalSet(2));

    // CAS: cmpxchg(0, local1 (old bitmap), local2 (cleared))
    f.instruction(&Instruction::I32Const(0));
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::LocalGet(2));
    f.instruction(&Instruction::I32AtomicRmwCmpxchg(wasm_encoder::MemArg {
        offset: 0,
        align: 2,
        memory_index: 0,
    }));

    // Retry if old != bitmap
    f.instruction(&Instruction::LocalGet(1));
    f.instruction(&Instruction::I32Ne);
    f.instruction(&Instruction::BrIf(0));

    // Success
    f.instruction(&Instruction::Return);

    f.instruction(&Instruction::End);
    f.instruction(&Instruction::End);
    f.instruction(&Instruction::End);
    f
}

impl StreamPass for ExportStackArenaStreamPass {
    fn run(&mut self, input_wasm: &[u8]) -> Result<Vec<u8>> {
        if self.slots == 0 {
            return Ok(input_wasm.to_vec());
        }

        let arena_pages = self.arena_pages();
        let arena_offset = self.arena_offset();
        let arena_off_i32 = arena_offset as i32;

        let mut types = Vec::new();
        let mut function_types = Vec::new();
        let mut import_func_count = 0_u32;
        let mut defined_func_count = 0_u32;
        let mut mem_min = 0_u64;
        let mut mem_max = None;
        let mut mem_shared = false;
        let mut has_memory = false;

        for payload in wasmparser::Parser::new(0).parse_all(input_wasm) {
            match payload? {
                Payload::TypeSection(s) => {
                    for g in s {
                        types.extend(g?.into_types());
                    }
                }
                Payload::ImportSection(s) => {
                    for g in s {
                        for import in g?.into_iter() {
                            let (_, import) = import?;
                            match import.ty {
                                TypeRef::Func(i) | TypeRef::FuncExact(i) => {
                                    import_func_count += 1;
                                    function_types.push(i);
                                }
                                TypeRef::Memory(m) => {
                                    has_memory = true;
                                    mem_min = m.initial;
                                    mem_max = m.maximum;
                                    mem_shared = m.shared;
                                }
                                _ => {}
                            }
                        }
                    }
                }
                Payload::FunctionSection(s) => {
                    for idx in s {
                        function_types.push(idx?);
                        defined_func_count += 1;
                    }
                }
                Payload::MemorySection(s) => {
                    for m in s {
                        let m = m?;
                        has_memory = true;
                        mem_min = m.initial;
                        mem_max = m.maximum;
                        mem_shared = m.shared;
                    }
                }
                _ => {}
            }
        }

        if !has_memory {
            return Ok(input_wasm.to_vec());
        }

        let new_min = (mem_min as u64) + (arena_pages as u64);
        let new_max = mem_max.map(|m| m + (arena_pages as u64));

        let base_type_idx = types.len();
        let size_fn_type = find_i32_result_type(&types).unwrap_or_else(|| base_type_idx as u32);
        let append_size_type = size_fn_type >= base_type_idx as u32;
        let grow_fn_type = if append_size_type {
            (base_type_idx + 1) as u32
        } else {
            find_i32_param_i32_result(&types)
                .unwrap_or_else(|| (base_type_idx + usize::from(append_size_type)) as u32)
        };
        let append_grow_type = append_size_type
            || grow_fn_type >= (base_type_idx + usize::from(append_size_type)) as u32;
        let after_grow =
            base_type_idx + usize::from(append_size_type) + usize::from(append_grow_type);
        let slot_acquire_type = find_i64_result_type(&types).unwrap_or_else(|| after_grow as u32);
        let append_slot_acquire_type = slot_acquire_type >= after_grow as u32;
        let after_slot_acquire = after_grow + usize::from(append_slot_acquire_type);
        let slot_release_type =
            find_i32_param_void_result(&types).unwrap_or_else(|| after_slot_acquire as u32);
        let append_slot_release_type =
            append_slot_acquire_type || slot_release_type >= after_slot_acquire as u32;

        let extra_funcs = 4_u32;
        let rebinder = OffsetRebinder {
            imported_funcs: import_func_count,
            extra_funcs,
        };

        let size_fn_idx = import_func_count + defined_func_count;
        let grow_fn_idx = size_fn_idx + 1;
        let slot_acquire_idx = grow_fn_idx + 1;
        let slot_release_idx = slot_acquire_idx + 1;

        let mem_info_fn = crate::wasm_stream::mem_info::memory_op_info;

        let mut module = Module::new();
        let mut code_seen = false;

        for payload in wasmparser::Parser::new(0).parse_all(input_wasm) {
            let payload = payload?;
            match payload {
                Payload::TypeSection(s) => {
                    let mut out = TypeSection::new();
                    for g in s {
                        let g = g?;
                        for ty in g.into_types() {
                            out.ty().subtype(&translate_sub_type(&ty, &DefaultRebinder));
                        }
                    }
                    if append_size_type {
                        out.ty().function([], [ValType::I32]);
                    }
                    if append_grow_type {
                        out.ty().function([ValType::I32], [ValType::I32]);
                    }
                    if append_slot_acquire_type {
                        out.ty().function([], [ValType::I64]);
                    }
                    if append_slot_release_type {
                        out.ty().function([ValType::I32], []);
                    }
                    module.section(&out);
                }
                Payload::ImportSection(s) => {
                    let mut out = wasm_encoder::ImportSection::new();
                    for g in s {
                        for import in g?.into_iter() {
                            let (_, import) = import?;
                            let entity = match import.ty {
                                TypeRef::Memory(m) => {
                                    wasm_encoder::EntityType::Memory(MemoryType {
                                        minimum: new_min,
                                        maximum: new_max,
                                        memory64: m.memory64,
                                        shared: m.shared,
                                        page_size_log2: m.page_size_log2,
                                    })
                                }
                                TypeRef::Func(i) | TypeRef::FuncExact(i) => {
                                    wasm_encoder::EntityType::Function(i)
                                }
                                TypeRef::Table(t) => wasm_encoder::EntityType::Table(
                                    crate::wasm_stream::translator::translate_table_type(
                                        t,
                                        &DefaultRebinder,
                                    ),
                                ),
                                TypeRef::Global(g) => wasm_encoder::EntityType::Global(
                                    translate_global_type(g, &DefaultRebinder),
                                ),
                                TypeRef::Tag(t) => wasm_encoder::EntityType::Tag(
                                    crate::wasm_stream::translator::translate_tag_type(t),
                                ),
                            };
                            out.import(import.module, import.name, entity);
                        }
                    }
                    module.section(&out);
                }
                Payload::FunctionSection(s) => {
                    let mut out = FunctionSection::new();
                    for f in s {
                        out.function(f?);
                    }
                    out.function(size_fn_type);
                    out.function(grow_fn_type);
                    out.function(slot_acquire_type);
                    out.function(slot_release_type);
                    module.section(&out);
                }
                Payload::MemorySection(s) => {
                    let mut out = wasm_encoder::MemorySection::new();
                    for m in s {
                        let m = m?;
                        out.memory(MemoryType {
                            minimum: new_min,
                            maximum: new_max,
                            memory64: m.memory64,
                            shared: m.shared,
                            page_size_log2: m.page_size_log2,
                        });
                    }
                    module.section(&out);
                }
                Payload::GlobalSection(s) => {
                    let mut out = GlobalSection::new();
                    for global in s {
                        let global = global?;
                        let mut insts = Vec::new();
                        for op in global.init_expr.get_operators_reader() {
                            let op = op?;
                            if !matches!(op, wasmparser::Operator::End) {
                                insts.push(translate(&op, &DefaultRebinder));
                            }
                        }
                        out.global(
                            translate_global_type(global.ty, &DefaultRebinder),
                            &ConstExpr::extended(insts),
                        );
                    }
                    module.section(&out);
                }
                Payload::ExportSection(s) => {
                    let mut out = wasm_encoder::ExportSection::new();
                    for export in s {
                        let export = export?;
                        let index = match export.kind {
                            ExternalKind::Func | ExternalKind::FuncExact => {
                                rebinder.function(export.index)
                            }
                            _ => export.index,
                        };
                        let kind = match export.kind {
                            ExternalKind::Func | ExternalKind::FuncExact => {
                                wasm_encoder::ExportKind::Func
                            }
                            ExternalKind::Table => wasm_encoder::ExportKind::Table,
                            ExternalKind::Memory => wasm_encoder::ExportKind::Memory,
                            ExternalKind::Global => wasm_encoder::ExportKind::Global,
                            ExternalKind::Tag => wasm_encoder::ExportKind::Tag,
                        };
                        out.export(export.name, kind, index);
                    }
                    module.section(&out);
                }
                Payload::StartSection { func, .. } => {
                    module.section(&wasm_encoder::StartSection {
                        function_index: rebinder.function(func),
                    });
                }
                Payload::ElementSection(s) => {
                    let mut out = wasm_encoder::ElementSection::new();
                    for elem in s {
                        let elem = elem?;
                        let funcs_buf;
                        let expr_storage;
                        let items = match elem.items {
                            wasmparser::ElementItems::Functions(fs) => {
                                funcs_buf = fs
                                    .into_iter()
                                    .map(|idx| Ok(rebinder.function(idx?)))
                                    .collect::<Result<Vec<_>>>()?;
                                wasm_encoder::Elements::Functions(std::borrow::Cow::Borrowed(
                                    &funcs_buf,
                                ))
                            }
                            wasmparser::ElementItems::Expressions(rt, exps) => {
                                expr_storage = exps
                                    .into_iter()
                                    .map(|e| {
                                        let e = e?;
                                        let mut insts = Vec::new();
                                        for op in e.get_operators_reader() {
                                            let op = op?;
                                            if !matches!(op, wasmparser::Operator::End) {
                                                insts.push(translate(&op, &rebinder));
                                            }
                                        }
                                        Ok(ConstExpr::extended(insts))
                                    })
                                    .collect::<Result<Vec<_>>>()?;
                                wasm_encoder::Elements::Expressions(
                                    crate::wasm_stream::translator::translate_ref_type(
                                        rt,
                                        &DefaultRebinder,
                                    ),
                                    std::borrow::Cow::Borrowed(&expr_storage),
                                )
                            }
                        };
                        match elem.kind {
                            wasmparser::ElementKind::Passive => {
                                out.passive(items);
                            }
                            wasmparser::ElementKind::Declared => {
                                out.declared(items);
                            }
                            wasmparser::ElementKind::Active {
                                table_index,
                                offset_expr,
                            } => {
                                let mut insts = Vec::new();
                                for op in offset_expr.get_operators_reader() {
                                    let op = op?;
                                    if !matches!(op, wasmparser::Operator::End) {
                                        insts.push(translate(&op, &rebinder));
                                    }
                                }
                                out.active(table_index, &ConstExpr::extended(insts), items);
                            }
                        }
                    }
                    module.section(&out);
                }
                Payload::CodeSectionStart { range, .. } => {
                    code_seen = true;
                    let mut out = CodeSection::new();

                    let reader = wasmparser::BinaryReader::new(
                        &input_wasm[range.start..range.end],
                        range.start,
                    );
                    let code_reader = wasmparser::CodeSectionReader::new(reader)?;
                    for body in code_reader {
                        let body = body?;
                        let orig_locals = body
                            .get_locals_reader()?
                            .into_iter()
                            .map(|l| {
                                let (c, t) = l?;
                                Ok((c, translate_val_type(t, &DefaultRebinder)))
                            })
                            .collect::<Result<Vec<_>>>()?;

                        let orig_count: u32 = orig_locals.iter().map(|(c, _)| *c as u32).sum();
                        let mut locals = orig_locals.clone();
                        locals.push((1, ValType::I32)); // temp_i32
                        locals.push((1, ValType::I64)); // temp_i64
                        let temps = Temps {
                            i32_idx: orig_count,
                            i64_idx: orig_count + 1,
                            total_locals: orig_count + 2,
                        };

                        let mut func = Function::new(locals);
                        for operator in body.get_operators_reader()? {
                            let op = operator?;

                            if let Some(mem_info) = mem_info_fn(&op) {
                                if mem_info.memory == 0 {
                                    let val_ops = &mem_info.value_operands;

                                    // Save value operands to temp locals (in reverse)
                                    for ty in val_ops.iter().rev() {
                                        func.instruction(&local_set_for(*ty, &temps));
                                    }

                                    // Add arena offset to address
                                    func.instruction(&Instruction::I32Const(arena_off_i32));
                                    func.instruction(&Instruction::I32Add);

                                    // Restore value operands from temp locals (in original order)
                                    for ty in val_ops.iter() {
                                        func.instruction(&local_get_for(*ty, &temps));
                                    }
                                }
                            }

                            match op {
                                wasmparser::Operator::MemorySize { mem } if mem == 0 => {
                                    func.instruction(&Instruction::Call(size_fn_idx));
                                }
                                wasmparser::Operator::MemoryGrow { mem } if mem == 0 => {
                                    func.instruction(&Instruction::Call(grow_fn_idx));
                                }
                                _ => {
                                    func.instruction(&translate(&op, &rebinder));
                                }
                            }
                        }
                        out.function(&func);
                    }

                    let mut size_fn = Function::new([]);
                    size_fn.instruction(&Instruction::MemorySize(0));
                    size_fn.instruction(&Instruction::I32Const(arena_pages as i32));
                    size_fn.instruction(&Instruction::I32Sub);
                    size_fn.instruction(&Instruction::End);
                    out.function(&size_fn);

                    let mut grow_fn = Function::new([(1, ValType::I32)]);
                    grow_fn.instruction(&Instruction::LocalGet(0));
                    grow_fn.instruction(&Instruction::MemoryGrow(0));
                    grow_fn.instruction(&Instruction::End);
                    out.function(&grow_fn);

                    let bitmap_bytes = ((self.slots + 31) / 32) * 4;
                    out.function(&build_slot_acquire(
                        bitmap_bytes,
                        self.slots,
                        self.stack_size,
                    ));
                    out.function(&build_slot_release(bitmap_bytes));

                    module.section(&out);
                }
                Payload::CodeSectionEntry(_) => {}
                Payload::DataSection(s) => {
                    let mut out = wasm_encoder::DataSection::new();
                    for data in s {
                        let data = data?;
                        match data.kind {
                            wasmparser::DataKind::Passive => {
                                out.passive(data.data.iter().copied());
                            }
                            wasmparser::DataKind::Active {
                                memory_index,
                                offset_expr,
                            } => {
                                let mut insts = Vec::new();
                                for op in offset_expr.get_operators_reader() {
                                    let op = op?;
                                    if let wasmparser::Operator::I32Const { value } = op {
                                        insts.push(Instruction::I32Const(
                                            (value as u64 + arena_offset) as i32,
                                        ));
                                    } else if !matches!(op, wasmparser::Operator::End) {
                                        insts.push(translate(&op, &rebinder));
                                    }
                                }
                                out.active(
                                    memory_index,
                                    &ConstExpr::extended(insts),
                                    data.data.iter().copied(),
                                );
                            }
                        }
                    }
                    module.section(&out);
                }
                Payload::CustomSection(s) => {
                    module.section(&wasm_encoder::CustomSection {
                        name: s.name().into(),
                        data: std::borrow::Cow::Borrowed(s.data()),
                    });
                }
                _ => {
                    if let Some((id, range)) = payload.as_section() {
                        module.section(&RawSection {
                            id,
                            data: &input_wasm[range],
                        });
                    }
                }
            }
        }

        if !code_seen {
            eyre::bail!("target has no code section");
        }

        Ok(module.finish())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn simple_target() -> Vec<u8> {
        let mut module = Module::new();

        let mut types = TypeSection::new();
        types.ty().function([], [ValType::I32]);
        module.section(&types);

        let mut functions = FunctionSection::new();
        functions.function(0);
        functions.function(0);
        module.section(&functions);

        let mut memories = wasm_encoder::MemorySection::new();
        memories.memory(MemoryType {
            minimum: 1,
            maximum: Some(4),
            memory64: false,
            shared: false,
            page_size_log2: None,
        });
        module.section(&memories);

        let mut exports = wasm_encoder::ExportSection::new();
        exports.export("run", wasm_encoder::ExportKind::Func, 0);
        exports.export("memory", wasm_encoder::ExportKind::Memory, 0);
        module.section(&exports);

        let mut code = CodeSection::new();
        // Function 0: load from memory, return loaded value
        let mut f0 = Function::new([]);
        f0.instruction(&Instruction::I32Const(0));
        f0.instruction(&Instruction::I32Load(wasm_encoder::MemArg {
            offset: 0,
            align: 2,
            memory_index: 0,
        }));
        f0.instruction(&Instruction::End);
        code.function(&f0);
        // Function 1: store 42 at offset, return loaded value from same addr
        let mut f1 = Function::new([]);
        f1.instruction(&Instruction::I32Const(0));
        f1.instruction(&Instruction::I32Const(42));
        f1.instruction(&Instruction::I32Store(wasm_encoder::MemArg {
            offset: 0,
            align: 2,
            memory_index: 0,
        }));
        f1.instruction(&Instruction::I32Const(0));
        f1.instruction(&Instruction::I32Load(wasm_encoder::MemArg {
            offset: 0,
            align: 2,
            memory_index: 0,
        }));
        f1.instruction(&Instruction::End);
        code.function(&f1);
        module.section(&code);

        module.finish()
    }

    #[test]
    fn arena_pages_computation() {
        let pass = ExportStackArenaStreamPass::new(2 * 1024 * 1024, 32); // 2MB, 32 slots
        let arena_pages = pass.arena_pages();
        // 32 slots * 2MB + bitmap = 64MB + 4 bytes → ceil(67108868/65536) = 1025 pages
        assert_eq!(arena_pages, 1025);
    }

    #[test]
    fn arena_pass_memory_expanded() -> Result<()> {
        let mut pass = ExportStackArenaStreamPass::new(65536, 2);
        let output = pass.run(&simple_target())?;

        let mut mem_pages = 0u64;
        for payload in wasmparser::Parser::new(0).parse_all(&output) {
            if let Payload::MemorySection(s) = payload? {
                for m in s {
                    mem_pages = m?.initial;
                }
            }
        }
        // 1 original + 3 arena pages (2 slots * 64KB + 4B bitmap = 131076B → 3 pages)
        assert_eq!(mem_pages, 4);
        Ok(())
    }

    #[test]
    fn arena_pass_validates() -> Result<()> {
        let mut pass = ExportStackArenaStreamPass::new(65536, 2);
        let output = pass.run(&simple_target())?;
        wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
            .validate_all(&output)?;
        Ok(())
    }

    #[test]
    fn arena_pass_no_op_without_slots() -> Result<()> {
        let mut pass = ExportStackArenaStreamPass::new(65536, 0);
        let input = simple_target();
        let output = pass.run(&input)?;
        assert_eq!(output, input);
        Ok(())
    }
}