canfuzz 0.5.0

A coverage-guided fuzzing framework for Internet Computer canisters, built on `libafl` and `pocket-ic`
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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
//! This module provides functionality to instrument WebAssembly (Wasm) modules
//! for coverage-guided fuzzing, specifically implementing an AFL-style instrumentation.
//!
//! The primary goal is to inject code into a Wasm module that tracks execution paths.
//! This is achieved by:
//! 1.  Injecting global variables to maintain state, such as the previous location.
//! 2.  Injecting a helper function that contains the core instrumentation logic.
//! 3.  Instrumenting the Wasm bytecode by inserting calls to the helper function at the
//!     start of each function and before every branch, effectively covering all basic blocks.
//! 4.  Exporting a coverage function that allows the fuzzer to retrieve the
//!     coverage map from the canister.

use anyhow::Result;
use rand::Rng;
use rand::RngCore;
use rand::SeedableRng;
use wirm::ir::function::FunctionBuilder;
use wirm::ir::id::{FunctionID, GlobalID, LocalID, MemoryID};
use wirm::ir::module::module_functions::FuncKind;
use wirm::ir::types::{InitExpr, Instructions, Value};
use wirm::module_builder::AddLocal;
use wirm::opcode::Inject;
use wirm::wasmparser::{MemArg, Operator, Validator};
use wirm::{DataType, InitInstr, Module, Opcode};

use crate::constants::{AFL_COVERAGE_MAP_SIZE, API_VERSION_IC0, COVERAGE_FN_EXPORT_NAME};

/// Arguments for configuring the Wasm instrumentation process.
pub struct InstrumentationArgs {
    /// The raw Wasm module to instrument.
    pub wasm_bytes: Vec<u8>,
    /// The number of previous locations to track (must be 1, 2, 4, or 8).
    pub history_size: usize,
    /// The seed to use for instrumentation.
    pub seed: Seed,
}

/// Specifies the seed for the random number generator used during instrumentation.
///
/// Using a static seed allows for deterministic and reproducible instrumentation,
/// which is crucial for debugging and consistent testing environments.
#[derive(Copy, Clone, Debug)]
pub enum Seed {
    /// A randomly generated seed will be used.
    Random,
    /// A user-provided static seed will be used.
    Static(u32),
}
/// A global, mutable static array to hold the coverage map.
///
/// # Safety
///
/// This is a raw pointer to a mutable static memory region, which is inherently `unsafe`.
/// It is used as a shared memory region between the fuzzer and the instrumented canister.
/// The `libafl` framework is designed to work with such a mechanism, which is a highly
/// optimized approach for coverage-guided fuzzing, inspired by AFL.
pub static mut COVERAGE_MAP: &mut [u8] = &mut [0; AFL_COVERAGE_MAP_SIZE as usize];

/// Instruments the given Wasm bytes for fuzzing.
///
/// This function takes a raw Wasm module, applies AFL-style instrumentation for
/// coverage tracking, and returns the instrumented Wasm module as a vector of bytes.
/// The resulting Wasm is validated before being returned.
///
/// # Arguments
///
/// * `instrumentation_args` - A struct containing the Wasm bytes, history size, and instrumentation seed.
pub fn instrument_wasm_for_fuzzing(instrumentation_args: InstrumentationArgs) -> Vec<u8> {
    assert!(
        matches!(instrumentation_args.history_size, 1 | 2 | 4 | 8),
        "History size must be 1, 2, 4, or 8"
    );
    let mut module = Module::parse(&instrumentation_args.wasm_bytes, false, false)
        .expect("Failed to parse module with wirm");

    instrument_for_afl(&mut module, &instrumentation_args)
        .expect("Unable to instrument wasm module for AFL");

    // Sorry it has to be this way :(
    let buf = vec![0u8; AFL_COVERAGE_MAP_SIZE as usize * instrumentation_args.history_size]
        .into_boxed_slice();
    let buf: &'static mut [u8] = Box::leak(buf);
    unsafe {
        COVERAGE_MAP = buf;
    }

    let instrumented_wasm = module.encode();

    validate_wasm(&instrumented_wasm).expect("Wasm is not valid");

    instrumented_wasm
}

/// The main orchestration function for applying AFL instrumentation.
///
/// It performs the following steps:
/// 1. Injects global variables required for tracking coverage.
/// 2. Injects the `[COVERAGE_FN_EXPORT_NAME]` update function to expose the coverage map.
/// 3. Instruments all functions by inserting calls to a helper function at the
///    start of each function and before each branch instruction.
fn instrument_for_afl(
    module: &mut Module<'_>,
    instrumentation_args: &InstrumentationArgs,
) -> Result<()> {
    let is_memory64 = is_memory64(module);
    let (afl_prev_loc_indices, afl_mem_ptr_idx) =
        inject_globals(module, instrumentation_args.history_size, is_memory64);
    println!(
        "  -> Injected globals: prev_locs @ indices {afl_prev_loc_indices:?}, mem_ptr @ index {afl_mem_ptr_idx:?}"
    );

    inject_afl_coverage_export(
        module,
        instrumentation_args.history_size,
        afl_mem_ptr_idx,
        is_memory64,
    )?;
    println!("  -> Injected `canister_update __export_coverage_for_afl` function.");

    instrument_branches(
        module,
        &afl_prev_loc_indices,
        afl_mem_ptr_idx,
        instrumentation_args.seed,
        is_memory64,
    );
    println!("  -> Instrumented branch instructions in all functions.");

    Ok(())
}

/// Injects the necessary global variables for AFL instrumentation.
///
/// - `__afl_prev_loc_N`: A set of `history_size` mutable i32 (or i64 for wasm64) globals to store the IDs
///   of the previously executed basic blocks. This is used to track execution history
///   in the control flow graph.
/// - `__afl_mem_ptr`: An immutable i32 (or i64 for wasm64) global that holds the base address (0) of the coverage map.
fn inject_globals(
    module: &mut Module<'_>,
    history_size: usize,
    is_memory64: bool,
) -> (Vec<GlobalID>, GlobalID) {
    let mut afl_prev_loc_indices = Vec::with_capacity(history_size);

    let (ptr_type, init_val) = if is_memory64 {
        (DataType::I64, Value::I64(0))
    } else {
        (DataType::I32, Value::I32(0))
    };

    for _ in 0..history_size {
        let global_id = module.add_global(
            InitExpr::new(vec![InitInstr::Value(init_val)]),
            ptr_type,
            true,
            false,
        );
        afl_prev_loc_indices.push(global_id);
    }
    let afl_mem_ptr_idx = module.add_global(
        InitExpr::new(vec![InitInstr::Value(init_val)]),
        ptr_type,
        false,
        false,
    );
    (afl_prev_loc_indices, afl_mem_ptr_idx)
}

/// Injects the `canister_update `[COVERAGE_FN_EXPORT_NAME]` function.
///
/// This exported function allows the fuzzer orchestrator to read the canister,
/// retrieve the coverage map and reset it. It uses the `ic0.msg_reply_data_append` and
/// `ic0.msg_reply` System API calls to send the contents of the coverage map
/// back to the caller.
fn inject_afl_coverage_export<'a>(
    module: &mut Module<'a>,
    history_size: usize,
    afl_mem_ptr_idx: GlobalID,
    is_memory64: bool,
) -> Result<()> {
    let (msg_reply_data_append_idx, msg_reply_idx) = ensure_ic0_imports(module, is_memory64)?;

    let mut func_builder = FunctionBuilder::new(&[], &[]);

    if is_memory64 {
        func_builder
            .global_get(afl_mem_ptr_idx)
            .i64_const(AFL_COVERAGE_MAP_SIZE as i64 * history_size as i64)
            .call(msg_reply_data_append_idx)
            .call(msg_reply_idx)
            .global_get(afl_mem_ptr_idx)
            .i32_const(0)
            .i64_const(AFL_COVERAGE_MAP_SIZE as i64 * history_size as i64)
            .memory_fill(0);
    } else {
        func_builder
            .global_get(afl_mem_ptr_idx)
            .i32_const(AFL_COVERAGE_MAP_SIZE * history_size as i32)
            .call(msg_reply_data_append_idx)
            .call(msg_reply_idx)
            .global_get(afl_mem_ptr_idx)
            .i32_const(0)
            .i32_const(AFL_COVERAGE_MAP_SIZE * history_size as i32)
            .memory_fill(0);
    }

    let coverage_function_id = func_builder.finish_module(module);
    let export_name = format!("canister_update {COVERAGE_FN_EXPORT_NAME}");
    module
        .exports
        .add_export_func(export_name, coverage_function_id.0);

    Ok(())
}

/// Instruments all local functions in the module to track code coverage.
///
/// This function iterates through every instruction in every function body.
/// It inserts a call to a helper instrumentation function at the beginning of the function
/// and before each branch-like instruction (`If`, `Else`, `Block`, `Loop`, `Br`, `BrIf`, `BrTable`).
/// This ensures that every basic block is instrumented.
fn instrument_branches(
    module: &mut Module<'_>,
    afl_prev_loc_indices: &[GlobalID],
    afl_mem_ptr_idx: GlobalID,
    seed: Seed,
    is_memory64: bool,
) {
    let instrumentation_function =
        afl_instrumentation_slice(module, afl_prev_loc_indices, afl_mem_ptr_idx, is_memory64);

    let seed = match seed {
        Seed::Random => rand::rng().next_u32(),
        Seed::Static(s) => s,
    };
    println!("The seed used for instrumentation is {seed}");
    let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);

    let mut create_instrumentation_ops = |ops: &mut Vec<Operator>| {
        let curr_location =
            rng.random_range(0..AFL_COVERAGE_MAP_SIZE * afl_prev_loc_indices.len() as i32);

        if is_memory64 {
            ops.push(Operator::I64Const {
                value: curr_location as i64,
            });
        } else {
            ops.push(Operator::I32Const {
                value: curr_location as i32,
            });
        }
        ops.push(Operator::Call {
            function_index: instrumentation_function.0,
        });
    };

    for (function_index, function) in module.functions.iter_mut().enumerate() {
        if matches!(function.kind(), FuncKind::Local(_))
            && FunctionID(function_index as u32) != instrumentation_function
        {
            let local_function = function.unwrap_local_mut();
            let mut new_instructions = Vec::with_capacity(local_function.body.num_instructions * 2);

            create_instrumentation_ops(&mut new_instructions);

            for instruction in local_function.body.instructions.get_ops() {
                match instruction {
                    Operator::Block { .. }
                    | Operator::Loop { .. }
                    | Operator::If { .. }
                    | Operator::Else => {
                        new_instructions.push(instruction.clone());
                        create_instrumentation_ops(&mut new_instructions);
                    }
                    Operator::Br { .. }
                    | Operator::BrIf { .. }
                    | Operator::BrTable { .. }
                    | Operator::Return => {
                        create_instrumentation_ops(&mut new_instructions);
                        new_instructions.push(instruction.clone());
                    }
                    _ => new_instructions.push(instruction.clone()),
                }
            }
            // offsets are set to zero, as we are not interested in preserving them.
            local_function.body.instructions = Instructions::new(
                new_instructions.iter().map(|i| (i.clone(), 0)).collect(),
                0,
                false,
            );
        }
    }
}

/// Creates and injects a helper function that contains the core AFL instrumentation logic.
///
/// This function will be called from instrumented locations (start of functions, before branches).
/// It implements the standard AFL coverage tracking mechanism:
/// ```text
///   curr_location = <COMPILE_TIME_RANDOM>;
///   key = curr_location ^ prev_loc[0] ^ ... ^ prev_loc[history_size-1];
///   shared_mem[key]++;
///   prev_loc[history_size-1] = prev_loc[history_size-2] >> 1;
///   ...
///   prev_loc[0] = curr_location >> 1;
/// ```
/// The generated function takes the current location (`curr_location`) as an i32 (or i64 for wasm64)
/// parameter and is added to the module.
///
/// # Returns
///
/// The `FunctionID` of the newly created helper function.
fn afl_instrumentation_slice(
    module: &mut Module<'_>,
    afl_prev_loc_indices: &[GlobalID],
    afl_mem_ptr_idx: GlobalID,
    is_memory64: bool,
) -> FunctionID {
    if is_memory64 {
        let mut func_builder = FunctionBuilder::new(&[DataType::I64], &[]);
        let curr_location = LocalID(0);
        let afl_local_idx = func_builder.add_local(DataType::I64);

        func_builder.local_get(curr_location);
        for &prev_loc_idx in afl_prev_loc_indices {
            func_builder.global_get(prev_loc_idx).i64_xor();
        }

        func_builder
            .global_get(afl_mem_ptr_idx)
            .i64_add()
            .local_tee(afl_local_idx)
            .local_get(afl_local_idx)
            .i64_load8_u(MemArg {
                offset: 0,
                align: 0,
                memory: 0,
                max_align: 0,
            })
            .i64_const(1)
            .i64_add();

        // i64_store8 opcode trait doesn't exist
        func_builder.inject(Operator::I64Store8 {
            memarg: MemArg {
                offset: 0,
                align: 0,
                memory: 0,
                max_align: 0,
            },
        });

        // Shift the history
        for i in (1..afl_prev_loc_indices.len()).rev() {
            func_builder
                .global_get(afl_prev_loc_indices[i - 1])
                .i64_const(1)
                .i64_shr_unsigned()
                .global_set(afl_prev_loc_indices[i]);
        }

        func_builder
            .local_get(curr_location)
            .i64_const(1)
            .i64_shr_unsigned()
            .global_set(afl_prev_loc_indices[0]);

        func_builder.finish_module(module)
    } else {
        let mut func_builder = FunctionBuilder::new(&[DataType::I32], &[]);
        let curr_location = LocalID(0);
        let afl_local_idx = func_builder.add_local(DataType::I32);

        func_builder.local_get(curr_location);
        for &prev_loc_idx in afl_prev_loc_indices {
            func_builder.global_get(prev_loc_idx).i32_xor();
        }

        func_builder
            .global_get(afl_mem_ptr_idx)
            .i32_add()
            .local_tee(afl_local_idx)
            .local_get(afl_local_idx)
            .i32_load8_u(MemArg {
                offset: 0,
                align: 0,
                memory: 0,
                max_align: 0,
            })
            .i32_const(1)
            .i32_add()
            .i32_store8(MemArg {
                offset: 0,
                align: 0,
                memory: 0,
                max_align: 0,
            });

        // Shift the history
        for i in (1..afl_prev_loc_indices.len()).rev() {
            func_builder
                .global_get(afl_prev_loc_indices[i - 1])
                .i32_const(1)
                .i32_shr_unsigned()
                .global_set(afl_prev_loc_indices[i]);
        }

        func_builder
            .local_get(curr_location)
            .i32_const(1)
            .i32_shr_unsigned()
            .global_set(afl_prev_loc_indices[0]);

        func_builder.finish_module(module)
    }
}

/// Ensures that the necessary `ic0` System API functions are imported.
///
/// The instrumentation requires `ic0.msg_reply_data_append` and `ic0.msg_reply`
/// for the `export_coverage` function. This function checks if they are already
/// imported. If not, it adds them to the module's import section.
/// It returns the function indices for both imports.
fn ensure_ic0_imports(
    module: &mut Module<'_>,
    is_memory64: bool,
) -> Result<(FunctionID, FunctionID)> {
    let mut data_append_idx = module.imports.get_func(
        API_VERSION_IC0.to_string(),
        "msg_reply_data_append".to_string(),
    );
    let mut reply_idx = module
        .imports
        .get_func(API_VERSION_IC0.to_string(), "msg_reply".to_string());

    if data_append_idx.is_none() {
        let ptr_type = if is_memory64 {
            DataType::I64
        } else {
            DataType::I32
        };
        let type_id = module.types.add_func_type(&[ptr_type, ptr_type], &[]);
        let (func_index, _) = module.add_import_func(
            API_VERSION_IC0.to_string(),
            "msg_reply_data_append".to_string(),
            type_id,
        );
        data_append_idx = Some(func_index);
    }

    if reply_idx.is_none() {
        let type_id = module.types.add_func_type(&[], &[]);
        let (func_index, _) = module.add_import_func(
            API_VERSION_IC0.to_string(),
            "msg_reply".to_string(),
            type_id,
        );
        reply_idx = Some(func_index);
    }

    Ok((data_append_idx.unwrap(), reply_idx.unwrap()))
}

/// Checks if the module is using 64-bit memory addressing for the purpose of instrumentation.
///
/// This function determines whether to use 64-bit or 32-bit instructions for memory operations
/// and global variables injected during instrumentation.
///
/// The logic is as follows:
/// 1. If the module's memory (index 0) is 32-bit, it returns `false`.
/// 2. If the memory is 64-bit:
///    - If `ic0.msg_reply_data_append` is NOT imported, it assumes 64-bit usage and returns `true`.
///    - If `ic0.msg_reply_data_append` IS imported, it checks the function signature.
///      - If the parameters are `i64`, it returns `true`.
///      - Otherwise (e.g., `i32`), it returns `false`.
fn is_memory64(module: &Module<'_>) -> bool {
    let memory_64 = module
        .memories
        .get_mem_by_id(MemoryID(0))
        .map(|m| m.ty.memory64)
        .unwrap_or(false);

    // The module is wasm32, no further checks needed
    if !memory_64 {
        return false;
    }

    // The module is guaranteed to be wasm64
    let data_append_idx = module.imports.get_func(
        API_VERSION_IC0.to_string(),
        "msg_reply_data_append".to_string(),
    );

    // If the systemAPI is not imported, we can safely choose i64 for wasm64
    if data_append_idx.is_none() {
        return true;
    }

    // If the systemAPI is imported, we follow the imported DataType for compatability
    // See: https://legacy.internetcomputer.org/docs/references/ic-interface-spec#responding
    let type_id = module
        .functions
        .get_fn_by_id(data_append_idx.unwrap())
        .unwrap()
        .get_type_id();
    let ty = module.types.get(type_id).unwrap();
    ty.params().iter().all(|v| matches!(v, DataType::I64))
}

/// Validates the instrumented Wasm module.
///
/// Uses `wasmparser::Validator` to ensure that the transformations have resulted in a valid Wasm module.
fn validate_wasm(wasm_bytes: &[u8]) -> Result<()> {
    let mut validator = Validator::new();
    validator.validate_all(wasm_bytes)?;
    println!("Validation of instrumented Wasm successful.");
    Ok(())
}

#[cfg(test)]
mod tests {
    use wirm::{ir::module::module_globals::GlobalKind, wasmparser::ValType};

    use super::*;
    #[test]
    fn inject_globals_empty_module() {
        let wat = wat::parse_str(
            r#"
                (module)
            "#,
        )
        .unwrap();

        let history_range: [usize; 4] = [1, 2, 4, 8];
        for history_size in history_range {
            let mut module = Module::parse(&wat, false, false).unwrap();
            let (afl_prev_loc_indices, afl_mem_ptr_idx) =
                inject_globals(&mut module, history_size, false);

            assert_eq!(afl_prev_loc_indices.len(), history_size);
            (0..history_size)
                .for_each(|index| assert_eq!(afl_prev_loc_indices[index], GlobalID(index as u32)));
            assert_eq!(afl_mem_ptr_idx, GlobalID(history_size as u32));
        }
    }

    #[test]
    fn inject_globals_two_globals() {
        let wat = wat::parse_str(
            r#"
                (module
                    (global (;0;) (mut i32) i32.const 0)
                    (global (;1;) (mut i32) i32.const 0)
                )
            "#,
        )
        .unwrap();

        let offset: u32 = 2;

        let history_range: [usize; 4] = [1, 2, 4, 8];
        for history_size in history_range {
            let mut module = Module::parse(&wat, false, false).unwrap();
            let (afl_prev_loc_indices, afl_mem_ptr_idx) =
                inject_globals(&mut module, history_size, false);

            assert_eq!(afl_prev_loc_indices.len(), history_size);
            (0..history_size).for_each(|index| {
                assert_eq!(afl_prev_loc_indices[index], GlobalID(index as u32 + offset))
            });
            assert_eq!(afl_mem_ptr_idx, GlobalID(history_size as u32 + offset));
        }
    }

    #[test]
    fn inject_globals_check_global_values() {
        let wat = wat::parse_str(
            r#"
                (module
                    (global (;0;) (mut i32) i32.const 0)
                    (global (;1;) (mut i32) i32.const 0)
                )
            "#,
        )
        .unwrap();

        let validate_global = |global: GlobalKind, mutable: bool| {
            assert_matches::assert_matches!(global, GlobalKind::Local(_));
            if let GlobalKind::Local(local) = global {
                assert_eq!(local.ty.content_type, ValType::I32);
                assert_eq!(local.ty.mutable, mutable);
                assert!(!local.ty.shared);
                assert_eq!(local.init_expr.instructions().len(), 1);
                assert_matches::assert_matches!(
                    local.init_expr.instructions()[0],
                    InitInstr::Value(Value::I32(0))
                );
            }
        };

        let history_range: [usize; 4] = [1, 2, 4, 8];
        for history_size in history_range {
            let mut module = Module::parse(&wat, false, false).unwrap();
            let (afl_prev_loc_indices, afl_mem_ptr_idx) =
                inject_globals(&mut module, history_size, false);

            for g in afl_prev_loc_indices.iter() {
                let global = module.globals.get_kind(*g);
                validate_global(global.clone(), true);
            }
            let global = module.globals.get_kind(afl_mem_ptr_idx);
            validate_global(global.clone(), false);
        }
    }

    #[test]
    fn inject_ic0_imports_empty_module() {
        let wat = wat::parse_str(
            r#"
                (module)
            "#,
        )
        .unwrap();

        let mut module = Module::parse(&wat, false, false).unwrap();
        let (data_append_idx, reply_idx) = ensure_ic0_imports(&mut module, false).unwrap();

        assert_eq!(data_append_idx, FunctionID(0));
        assert_eq!(reply_idx, FunctionID(1));
    }

    #[test]
    fn inject_ic0_imports_one_import() {
        let wat = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i32)))
                    (import "ic0" "dummy" (func (;0;) (type 0)))
                )
            "#,
        )
        .unwrap();

        let mut module = Module::parse(&wat, false, false).unwrap();
        let (data_append_idx, reply_idx) = ensure_ic0_imports(&mut module, false).unwrap();

        assert_eq!(data_append_idx, FunctionID(1));
        assert_eq!(reply_idx, FunctionID(2));
    }

    #[test]
    fn inject_ic0_imports_data_append_exists() {
        let wat = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i32 i32)))
                    (import "ic0" "msg_reply_data_append" (func (;0;) (type 0)))
                )
            "#,
        )
        .unwrap();

        let mut module = Module::parse(&wat, false, false).unwrap();
        let (data_append_idx, reply_idx) = ensure_ic0_imports(&mut module, false).unwrap();

        assert_eq!(data_append_idx, FunctionID(0));
        assert_eq!(reply_idx, FunctionID(1));
    }

    #[test]
    fn inject_ic0_imports_reply_exists() {
        let wat = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func))
                    (import "ic0" "msg_reply" (func (;0;) (type 0)))
                )
            "#,
        )
        .unwrap();

        let mut module = Module::parse(&wat, false, false).unwrap();
        let (data_append_idx, reply_idx) = ensure_ic0_imports(&mut module, false).unwrap();

        assert_eq!(data_append_idx, FunctionID(1));
        assert_eq!(reply_idx, FunctionID(0));
    }

    #[test]
    fn inject_ic0_imports_both_exists() {
        let wat = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i32 i32)))
                    (type (;1;) (func))
                    (import "ic0" "msg_reply_data_append" (func (;0;) (type 0)))
                    (import "ic0" "msg_reply" (func (;1;) (type 1)))
                )
            "#,
        )
        .unwrap();

        let mut module = Module::parse(&wat, false, false).unwrap();
        let (data_append_idx, reply_idx) = ensure_ic0_imports(&mut module, false).unwrap();

        assert_eq!(data_append_idx, FunctionID(0));
        assert_eq!(reply_idx, FunctionID(1));
    }

    /// Helper function to test equality between two generated Wasm modules
    /// If they are not equal, it displays the textual difference of the WAT.
    fn wasm_equality(generated: Vec<u8>, expected: Vec<u8>) {
        // both are encoded slices
        if generated != expected {
            let generated_text = wasmprinter::print_bytes(&generated).unwrap();
            let expected_text = wasmprinter::print_bytes(&expected).unwrap();
            // It's nice to show textual diffs
            difference::assert_diff!(generated_text.as_str(), expected_text.as_str(), "\n", 0)
        }
    }

    #[test]
    fn inject_instrumentation_function_history_1() {
        let wat = wat::parse_str(
            r#"
                (module
                    (memory (;0;) 1)
                )
            "#,
        )
        .unwrap();

        let history_size = 1;
        let mut module = Module::parse(&wat, false, false).unwrap();
        let (afl_prev_loc_indices, afl_mem_ptr_idx) =
            inject_globals(&mut module, history_size, false);
        let instrumentation_function =
            afl_instrumentation_slice(&mut module, &afl_prev_loc_indices, afl_mem_ptr_idx, false);
        assert_eq!(instrumentation_function, FunctionID(0));
        let expected_wasm = wat::parse_str(
            r#"(module
                            (type (;0;) (func (param i32)))
                            (memory (;0;) 1)
                            (global (;0;) (mut i32) i32.const 0)
                            (global (;1;) i32 i32.const 0)
                            (func (;0;) (type 0) (param i32)
                                (local i32)
                                local.get 0
                                global.get 0
                                i32.xor
                                global.get 1
                                i32.add
                                local.tee 1
                                local.get 1
                                i32.load8_u
                                i32.const 1
                                i32.add
                                i32.store8
                                local.get 0
                                i32.const 1
                                i32.shr_u
                                global.set 0
                            )
                        )"#,
        )
        .unwrap();
        let mut expected_module = Module::parse(&expected_wasm, false, false).unwrap();
        wasm_equality(module.encode(), expected_module.encode());
    }

    #[test]
    fn inject_instrumentation_function_history_2() {
        let wat = wat::parse_str(
            r#"
                (module
                    (memory (;0;) 1)
                )
            "#,
        )
        .unwrap();

        let history_size = 2;
        let mut module = Module::parse(&wat, false, false).unwrap();
        let (afl_prev_loc_indices, afl_mem_ptr_idx) =
            inject_globals(&mut module, history_size, false);
        let instrumentation_function =
            afl_instrumentation_slice(&mut module, &afl_prev_loc_indices, afl_mem_ptr_idx, false);
        assert_eq!(instrumentation_function, FunctionID(0));
        let expected_wasm = wat::parse_str(
            r#"(module
                            (type (;0;) (func (param i32)))
                            (memory (;0;) 1)
                            (global (;0;) (mut i32) i32.const 0)
                            (global (;1;) (mut i32) i32.const 0)
                            (global (;2;) i32 i32.const 0)
                            (func (;0;) (type 0) (param i32)
                                (local i32)
                                local.get 0
                                global.get 0
                                i32.xor
                                global.get 1
                                i32.xor
                                global.get 2
                                i32.add
                                local.tee 1
                                local.get 1
                                i32.load8_u
                                i32.const 1
                                i32.add
                                i32.store8
                                global.get 0
                                i32.const 1
                                i32.shr_u
                                global.set 1
                                local.get 0
                                i32.const 1
                                i32.shr_u
                                global.set 0
                            )
                        )"#,
        )
        .unwrap();
        let mut expected_module = Module::parse(&expected_wasm, false, false).unwrap();
        wasm_equality(module.encode(), expected_module.encode());
    }

    #[test]
    fn inject_afl_coverage_export_history_1() {
        let wat = wat::parse_str(
            r#"
                (module
                    (memory (;0;) 1)
                )
            "#,
        )
        .unwrap();

        let history_size = 1;
        let mut module = Module::parse(&wat, false, false).unwrap();
        let (_, afl_mem_ptr_idx) = inject_globals(&mut module, history_size, false);
        let coverage_function =
            inject_afl_coverage_export(&mut module, history_size, afl_mem_ptr_idx, false);
        assert!(coverage_function.is_ok());
        let expected_wasm = wat::parse_str(
            r#"(module
                    (type (;0;) (func (param i32 i32)))
                    (type (;1;) (func))
                    (import "ic0" "msg_reply_data_append" (func (;0;) (type 0)))
                    (import "ic0" "msg_reply" (func (;1;) (type 1)))
                    (memory (;0;) 1)
                    (global (;0;) (mut i32) i32.const 0)
                    (global (;1;) i32 i32.const 0)
                    (export "canister_update __export_coverage_for_afl" (func 2))
                    (func (;2;) (type 1)
                        global.get 1
                        i32.const 65536
                        call 0
                        call 1
                        global.get 1
                        i32.const 0
                        i32.const 65536
                        memory.fill
                    )
                )"#,
        )
        .unwrap();
        let mut expected_module = Module::parse(&expected_wasm, false, false).unwrap();
        wasm_equality(module.encode(), expected_module.encode());
    }

    #[test]
    fn inject_afl_coverage_export_history_2() {
        let wat = wat::parse_str(
            r#"
                (module
                    (memory (;0;) 1)
                )
            "#,
        )
        .unwrap();

        let history_size = 2;
        let mut module = Module::parse(&wat, false, false).unwrap();
        let (_, afl_mem_ptr_idx) = inject_globals(&mut module, history_size, false);
        let coverage_function =
            inject_afl_coverage_export(&mut module, history_size, afl_mem_ptr_idx, false);
        assert!(coverage_function.is_ok());
        let expected_wasm = wat::parse_str(
            r#"(module
                    (type (;0;) (func (param i32 i32)))
                    (type (;1;) (func))
                    (import "ic0" "msg_reply_data_append" (func (;0;) (type 0)))
                    (import "ic0" "msg_reply" (func (;1;) (type 1)))
                    (memory (;0;) 1)
                    (global (;0;) (mut i32) i32.const 0)
                    (global (;1;) (mut i32) i32.const 0)
                    (global (;2;) i32 i32.const 0)
                    (export "canister_update __export_coverage_for_afl" (func 2))
                    (func (;2;) (type 1)
                        global.get 2
                        i32.const 131072
                        call 0
                        call 1
                        global.get 2
                        i32.const 0
                        i32.const 131072
                        memory.fill
                    )
                )"#,
        )
        .unwrap();
        let mut expected_module = Module::parse(&expected_wasm, false, false).unwrap();
        wasm_equality(module.encode(), expected_module.encode());
    }

    /// Helper function to test branching instrumentation.
    fn instrument_branches_helper(module: &str, expected: &[Operator]) {
        let wat = wat::parse_str(module).unwrap();

        let history_size = 2;
        let mut module = Module::parse(&wat, false, false).unwrap();
        let (afl_prev_loc_indices, afl_mem_ptr_idx) =
            inject_globals(&mut module, history_size, false);
        instrument_branches(
            &mut module,
            &afl_prev_loc_indices,
            afl_mem_ptr_idx,
            Seed::Static(42),
            false,
        );

        let instructions = module
            .functions
            .get_fn_by_id(FunctionID(0))
            .unwrap()
            .unwrap_local()
            .body
            .instructions
            .get_ops();

        assert_eq!(instructions, expected);
    }

    #[test]
    fn inject_branch_instrumentation_func() {
        instrument_branches_helper(
            r#"
                (module
                    (type (;0;) (func))
                    (memory (;0;) 1)
                    (func (;0;) (type 0))
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_block() {
        instrument_branches_helper(
            r#"
                (module
                    (memory (;0;) 1)
                    (func
                        block
                        nop
                        end
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::Block {
                    blockty: wirm::wasmparser::BlockType::Empty,
                },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::Nop,
                Operator::End,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_loop() {
        instrument_branches_helper(
            r#"
                (module
                    (memory (;0;) 1)
                    (func
                        loop
                        nop
                        end
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::Loop {
                    blockty: wirm::wasmparser::BlockType::Empty,
                },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::Nop,
                Operator::End,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_if() {
        instrument_branches_helper(
            r#"
               (module
                    (memory (;0;) 1)
                    (func
                        i32.const 0  ;; Condition
                        if
                        nop
                        end
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::I32Const { value: 0 },
                Operator::If {
                    blockty: wirm::wasmparser::BlockType::Empty,
                },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::Nop,
                Operator::End,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_if_else() {
        instrument_branches_helper(
            r#"
               (module
                    (memory (;0;) 1)
                    (func
                        i32.const 0
                        if
                        nop
                        else
                        nop
                        end
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::I32Const { value: 0 },
                Operator::If {
                    blockty: wirm::wasmparser::BlockType::Empty,
                },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::Nop,
                Operator::Else,
                Operator::I32Const { value: 32602 },
                Operator::Call { function_index: 1 },
                Operator::Nop,
                Operator::End,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_br() {
        instrument_branches_helper(
            r#"
               (module
                    (memory (;0;) 1)
                    (func
                        block
                        br 0
                        end
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::Block {
                    blockty: wirm::wasmparser::BlockType::Empty,
                },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::I32Const { value: 32602 },
                Operator::Call { function_index: 1 },
                Operator::Br { relative_depth: 0 },
                Operator::End,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_brif() {
        instrument_branches_helper(
            r#"
               (module
                    (memory (;0;) 1)
                    (func
                        block
                        i32.const 0
                        br_if 0
                        end
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::Block {
                    blockty: wirm::wasmparser::BlockType::Empty,
                },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::I32Const { value: 0 },
                Operator::I32Const { value: 32602 },
                Operator::Call { function_index: 1 },
                Operator::BrIf { relative_depth: 0 },
                Operator::End,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_return() {
        instrument_branches_helper(
            r#"
               (module
                    (memory (;0;) 1)
                    (func
                        return
                    )
                )
            "#,
            &[
                Operator::I32Const { value: 17486 },
                Operator::Call { function_index: 1 },
                Operator::I32Const { value: 69016 },
                Operator::Call { function_index: 1 },
                Operator::Return,
                Operator::End,
            ],
        );
    }

    #[test]
    fn inject_branch_instrumentation_brtable() {
        let wat = wat::parse_str(
            r#"
               (module
                    (memory (;0;) 1)
                    (func
                        block
                        i32.const 0
                        br_table 0 0
                        end
                    )
                )
            "#,
        )
        .unwrap();

        let history_size = 2;
        let mut module = Module::parse(&wat, false, false).unwrap();
        let (afl_prev_loc_indices, afl_mem_ptr_idx) =
            inject_globals(&mut module, history_size, false);
        instrument_branches(
            &mut module,
            &afl_prev_loc_indices,
            afl_mem_ptr_idx,
            Seed::Static(42),
            false,
        );

        let instructions = module
            .functions
            .get_fn_by_id(FunctionID(0))
            .unwrap()
            .unwrap_local()
            .body
            .instructions
            .get_ops();

        let exptected = vec![
            Operator::I32Const { value: 17486 },
            Operator::Call { function_index: 1 },
            Operator::Block {
                blockty: wirm::wasmparser::BlockType::Empty,
            },
            Operator::I32Const { value: 69016 },
            Operator::Call { function_index: 1 },
            Operator::I32Const { value: 0 },
            Operator::I32Const { value: 32602 },
            Operator::Call { function_index: 1 },
            // BrTable fields are private, so it can't be hardcoded.
            Operator::End,
            Operator::End,
        ];

        assert_eq!(
            instructions
                .iter()
                .filter(|o| !matches!(o, Operator::BrTable { targets: _ }))
                .cloned()
                .collect::<Vec<_>>(),
            exptected
        );
    }

    #[should_panic]
    #[test]
    fn instrumentation_panic_history_size_3() {
        let wat = wat::parse_str(
            r#"
                (module)
            "#,
        )
        .unwrap();

        let history_size: usize = 3;

        let _ = instrument_wasm_for_fuzzing(InstrumentationArgs {
            wasm_bytes: wat,
            history_size,
            seed: Seed::Random,
        });
    }

    #[test]
    fn instrumentation_round_trip() {
        let wat = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i32)))
                    (memory (;0;) 1)
                    (export "memory" (memory 0))
                    (export "check_even" (func 0))
                    (func (;0;) (type 0) (param $num i32)
                        local.get $num
                        i32.const 2
                        i32.rem_u
                        i32.eqz
                        if ;; label = @1
                        i32.const 0
                        i32.const 1
                        i32.store
                        else
                        i32.const 0
                        i32.const 0
                        i32.store
                        end
                    )
                )
            "#,
        )
        .unwrap();

        let history_size: usize = 2;

        let expected = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i32)))
                    (type (;1;) (func (param i32 i32)))
                    (type (;2;) (func))
                    (import "ic0" "msg_reply_data_append" (func (;0;) (type 1)))
                    (import "ic0" "msg_reply" (func (;1;) (type 2)))
                    (memory (;0;) 1)
                    (global (;0;) (mut i32) i32.const 0)
                    (global (;1;) (mut i32) i32.const 0)
                    (global (;2;) i32 i32.const 0)
                    (export "memory" (memory 0))
                    (export "check_even" (func 2))
                    (export "canister_update __export_coverage_for_afl" (func 3))
                    (func (;2;) (type 0) (param i32)
                        i32.const 17486
                        call 4
                        local.get 0
                        i32.const 2
                        i32.rem_u
                        i32.eqz
                        if ;; label = @1
                        i32.const 69016
                        call 4
                        i32.const 0
                        i32.const 1
                        i32.store
                        else
                        i32.const 32602
                        call 4
                        i32.const 0
                        i32.const 0
                        i32.store
                        end
                    )
                    (func (;3;) (type 2)
                        i32.const 71136
                        call 4
                        global.get 2
                        i32.const 131072
                        call 0
                        call 1
                        global.get 2
                        i32.const 0
                        i32.const 131072
                        memory.fill
                    )
                    (func (;4;) (type 0) (param i32)
                        (local i32)
                        local.get 0
                        global.get 0
                        i32.xor
                        global.get 1
                        i32.xor
                        global.get 2
                        i32.add
                        local.tee 1
                        local.get 1
                        i32.load8_u
                        i32.const 1
                        i32.add
                        i32.store8
                        global.get 0
                        i32.const 1
                        i32.shr_u
                        global.set 1
                        local.get 0
                        i32.const 1
                        i32.shr_u
                        global.set 0
                    )
                    )
            "#,
        )
        .unwrap();

        let generated = instrument_wasm_for_fuzzing(InstrumentationArgs {
            wasm_bytes: wat,
            history_size,
            seed: Seed::Static(42),
        });

        wasm_equality(generated, expected);
    }

    #[test]
    fn instrumentation_round_trip_wasm64() {
        let wat = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i64)))
                    (memory (;0;) i64 1)
                    (export "memory" (memory 0))
                    (export "check_even" (func 0))
                    (func (;0;) (type 0) (param $num i64)
                        local.get $num
                        i64.const 2
                        i64.rem_u
                        i64.eqz
                        if ;; label = @1
                        i64.const 0
                        i64.const 1
                        i64.store
                        else
                        i64.const 0
                        i64.const 0
                        i64.store
                        end
                    )
                )
            "#,
        )
        .unwrap();

        let history_size: usize = 2;

        let expected = wat::parse_str(
            r#"
                (module
                    (type (;0;) (func (param i64)))
                    (type (;1;) (func (param i64 i64)))
                    (type (;2;) (func))
                    (import "ic0" "msg_reply_data_append" (func (;0;) (type 1)))
                    (import "ic0" "msg_reply" (func (;1;) (type 2)))
                    (memory (;0;) i64 1)
                    (global (;0;) (mut i64) i64.const 0)
                    (global (;1;) (mut i64) i64.const 0)
                    (global (;2;) i64 i64.const 0)
                    (export "memory" (memory 0))
                    (export "check_even" (func 2))
                    (export "canister_update __export_coverage_for_afl" (func 3))
                    (func (;2;) (type 0) (param i64)
                        i64.const 17486
                        call 4
                        local.get 0
                        i64.const 2
                        i64.rem_u
                        i64.eqz
                        if ;; label = @1
                        i64.const 69016
                        call 4
                        i64.const 0
                        i64.const 1
                        i64.store
                        else
                        i64.const 32602
                        call 4
                        i64.const 0
                        i64.const 0
                        i64.store
                        end
                    )
                    (func (;3;) (type 2)
                        i64.const 71136
                        call 4
                        global.get 2
                        i64.const 131072
                        call 0
                        call 1
                        global.get 2
                        i32.const 0
                        i64.const 131072
                        memory.fill
                    )
                    (func (;4;) (type 0) (param i64)
                        (local i64)
                        local.get 0
                        global.get 0
                        i64.xor
                        global.get 1
                        i64.xor
                        global.get 2
                        i64.add
                        local.tee 1
                        local.get 1
                        i64.load8_u
                        i64.const 1
                        i64.add
                        i64.store8
                        global.get 0
                        i64.const 1
                        i64.shr_u
                        global.set 1
                        local.get 0
                        i64.const 1
                        i64.shr_u
                        global.set 0
                    )
                    )
            "#,
        )
        .unwrap();

        let generated = instrument_wasm_for_fuzzing(InstrumentationArgs {
            wasm_bytes: wat,
            history_size,
            seed: Seed::Static(42),
        });

        wasm_equality(generated, expected);
    }

    #[test]
    fn test_is_memory64_wasm32() {
        let wat = wat::parse_str(r#"(module (memory 1))"#).unwrap();
        let module = Module::parse(&wat, false, false).unwrap();
        assert!(!is_memory64(&module));
    }

    #[test]
    fn test_is_memory64_wasm64_no_import() {
        let wat = wat::parse_str(r#"(module (memory i64 1))"#).unwrap();
        let module = Module::parse(&wat, false, false).unwrap();
        assert!(is_memory64(&module));
    }

    #[test]
    fn test_is_memory64_wasm64_import_i64() {
        let wat = wat::parse_str(
            r#"
            (module
                (import "ic0" "msg_reply_data_append" (func (param i64 i64)))
                (memory i64 1)
            )
            "#,
        )
        .unwrap();
        let module = Module::parse(&wat, false, false).unwrap();
        assert!(is_memory64(&module));
    }

    #[test]
    fn test_is_memory64_wasm64_import_i32() {
        let wat = wat::parse_str(
            r#"
            (module
                (import "ic0" "msg_reply_data_append" (func (param i32 i32)))
                (memory i64 1)
            )
            "#,
        )
        .unwrap();
        let module = Module::parse(&wat, false, false).unwrap();
        assert!(!is_memory64(&module));
    }
}