wasmtime-cli 48.0.0

Command-line interface for Wasmtime
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
use wasmtime::*;

mod test_utils {
    use std::any::*;
    use std::panic::AssertUnwindSafe;
    use wasmtime::{bail, *};

    pub struct Runner {
        pub engine: Engine,
        pub store: Store<()>,
    }

    impl Runner {
        pub fn new() -> Runner {
            let mut config = Config::default();
            config.wasm_function_references(true);
            config.wasm_exceptions(true);
            config.wasm_stack_switching(true);
            // Required in order to use recursive types.
            config.wasm_gc(true);

            let engine = Engine::new(&config).unwrap();

            let store = Store::<()>::new(&engine, ());

            Runner { engine, store }
        }

        /// Uses this `Runner` to run the module defined in `wat`, satisfying
        /// its imports using `imports`. The module must export a function
        /// `entry`, taking no parameters and returning `Results`.
        pub fn run_test<Results: WasmResults>(
            mut self,
            wat: &str,
            imports: &[Extern],
        ) -> Result<Results> {
            let module = Module::new(&self.engine, wat)?;

            let instance = Instance::new(&mut self.store, &module, imports)?;
            let entry = instance.get_typed_func::<(), Results>(&mut self.store, "entry")?;

            entry.call(&mut self.store, ())
        }

        /// Uses this `Runner` to run the module defined in `wat`, satisfying
        /// its imports using `imports`. The module must export a function
        /// `entry`, taking no parameters and without return values. Execution
        /// of `entry` is expected to cause a panic (and that this is panic is
        /// not handled by wasmtime previously).
        /// Returns the `Error` payload.
        pub fn run_test_expect_panic(
            mut self,
            wat: &str,
            imports: &[Extern],
        ) -> Box<dyn Any + Send + 'static> {
            let module = Module::new(&self.engine, wat).unwrap();

            let instance = Instance::new(&mut self.store, &module, imports).unwrap();
            let entry = instance.get_func(&mut self.store, "entry").unwrap();

            std::panic::catch_unwind(AssertUnwindSafe(|| {
                drop(entry.call(&mut self.store, &[], &mut []))
            }))
            .unwrap_err()
        }
    }

    /// Creates a simple Host function that increments an i32
    pub fn make_i32_inc_host_func(runner: &mut Runner) -> Func {
        Func::new(
            &mut runner.store,
            FuncType::new(&runner.engine, vec![ValType::I32], vec![ValType::I32]),
            |mut _caller, args: &[Val], results: &mut [Val]| {
                let res = match args {
                    [Val::I32(i)] => i + 1,
                    _ => bail!("Error: Received illegal argument (should be single i32)"),
                };
                results[0] = Val::I32(res);
                Ok(())
            },
        )
    }

    /// Creates a host function of type i32 -> i32. `export_func` must denote an
    /// exported function of type i32 -> i32. The created host function
    /// increments its argument by 1, passes it to the exported function, and in
    /// turn increments the result before returning it as the overall result.
    pub fn make_i32_inc_via_export_host_func(
        runner: &mut Runner,
        export_func: &'static str,
    ) -> Func {
        Func::new(
            &mut runner.store,
            FuncType::new(&runner.engine, vec![ValType::I32], vec![ValType::I32]),
            |mut caller, args: &[Val], results: &mut [Val]| {
                let export = caller
                    .get_export(export_func)
                    .ok_or_else(|| wasmtime::format_err!("could not get export"))?;
                let func = export
                    .into_func()
                    .ok_or_else(|| wasmtime::format_err!("export is not a Func"))?;
                let func_typed = func.typed::<i32, i32>(caller.as_context())?;
                let arg = args[0].unwrap_i32();
                let res = func_typed.call(caller.as_context_mut(), arg + 1)?;
                results[0] = Val::I32(res + 1);
                Ok(())
            },
        )
    }

    pub fn make_panicking_host_func(store: &mut Store<()>, msg: &'static str) -> Func {
        Func::wrap(store, move || -> () { std::panic::panic_any(msg) })
    }
}

mod wasi {
    use wasmtime::{Config, Engine, Linker, Module, Result, Store};
    use wasmtime_wasi::WasiCtxBuilder;
    use wasmtime_wasi::p1::{self, WasiP1Ctx};

    fn run_wasi_test(wat: &'static str) -> Result<i32> {
        // Construct the wasm engine with async support disabled.
        let mut config = Config::new();
        config
            .wasm_exceptions(true)
            .wasm_function_references(true)
            .wasm_stack_switching(true);
        let engine = Engine::new(&config)?;

        // Add the WASI preview1 API to the linker (will be implemented in terms of
        // the preview2 API)
        let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
        p1::add_to_linker_sync(&mut linker, |t| t)?;

        // Add capabilities (e.g. filesystem access) to the WASI preview2 context here.
        let wasi_ctx = WasiCtxBuilder::new().inherit_stdio().build_p1();

        let mut store: Store<WasiP1Ctx> = Store::new(&engine, wasi_ctx);

        // Instantiate our wasm module.
        let module = Module::new(&engine, wat)?;
        let func = linker
            .module(&mut store, "", &module)?
            .get_default(&mut store, "")?
            .typed::<(), i32>(&store)?;

        // Invoke the WASI program default function.
        func.call(&mut store, ())
    }

    async fn run_wasi_test_async(wat: &'static str) -> Result<i32> {
        // Construct the wasm engine with async support enabled.
        let mut config = Config::new();
        config
            .wasm_exceptions(true)
            .wasm_function_references(true)
            .wasm_stack_switching(true);
        let engine = Engine::new(&config)?;

        // Add the WASI preview1 API to the linker (will be implemented in terms of
        // the preview2 API)
        let mut linker: Linker<WasiP1Ctx> = Linker::new(&engine);
        p1::add_to_linker_async(&mut linker, |t| t)?;

        // Add capabilities (e.g. filesystem access) to the WASI preview2 context here.
        let wasi_ctx = WasiCtxBuilder::new().inherit_stdio().build_p1();

        let mut store: Store<WasiP1Ctx> = Store::new(&engine, wasi_ctx);

        // Instantiate our wasm module.
        let module = Module::new(&engine, wat)?;
        let func = linker
            .module_async(&mut store, "", &module)
            .await?
            .get_default(&mut store, "")?
            .typed::<(), i32>(&store)?;

        // Invoke the WASI program default function.
        func.call_async(&mut store, ()).await
    }

    static WRITE_SOMETHING_WAT: &str = r#"
(module
  (type $ft (func (result i32)))
  (type $ct (cont $ft))
  (import "wasi_snapshot_preview1" "fd_write"
     (func $print (param $fd i32)
                  (param $iovec i32)
                  (param $len i32)
                  (param $written i32) (result i32)))
  (memory 1)
  (export "memory" (memory 0))

  ;; 9 is the offset to write to
  (data (i32.const 9) "something\n")

  (func $f (result i32)
    (i32.const 0) ;; offset
    (i32.const 9) ;; value start of the string
    (i32.store)

    (i32.const 4)                ;; offset
    (i32.const 10)               ;; value, the length of the string
    (i32.store offset=0 align=2) ;; size_buf_len

    (i32.const 1)   ;; 1 for stdout
    (i32.const 0)   ;; 0 as we stored the beginning of __wasi_ciovec_t
    (i32.const 1)   ;;
    (i32.const 20)  ;; nwritten
    (call $print)
  )
  (elem declare func $f)

  (func (export "_start") (result i32)
    (ref.func $f)
    (cont.new $ct)
    (resume $ct)
  )
)"#;

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    fn write_something_test() -> Result<()> {
        assert_eq!(run_wasi_test(WRITE_SOMETHING_WAT)?, 0);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[tokio::test]
    async fn write_something_test_async() -> Result<()> {
        assert_eq!(run_wasi_test_async(WRITE_SOMETHING_WAT).await?, 0);
        Ok(())
    }

    static SCHED_YIELD_WAT: &'static str = r#"
(module
  (type $ft (func (result i32)))
  (type $ct (cont $ft))
  (import "wasi_snapshot_preview1" "sched_yield"
     (func $sched_yield (result i32)))
  (memory 1)
  (export "memory" (memory 0))

  (func $g (result i32)
    (call $sched_yield))
  (elem declare func $g)

  (func (export "_start") (result i32)
    (cont.new $ct (ref.func $g))
    (resume $ct)
  )
)"#;

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    fn sched_yield_test() -> Result<()> {
        assert_eq!(run_wasi_test(SCHED_YIELD_WAT)?, 0);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[tokio::test]
    async fn sched_yield_test_async() -> Result<()> {
        assert_eq!(run_wasi_test_async(SCHED_YIELD_WAT).await?, 0);
        Ok(())
    }
}

/// Test that two distinct instantiations of the same module yield
/// different control tag identities.
#[cfg_attr(any(asan, miri), ignore)]
#[test]
fn inter_instance_suspend() -> Result<()> {
    let mut config = Config::default();
    config.wasm_function_references(true);
    config.wasm_exceptions(true);
    config.wasm_stack_switching(true);

    let engine = Engine::new(&config)?;

    let mut store = Store::<()>::new(&engine, ());

    let wat_other = r#"
        (module

          (type $ft (func))
          (type $ct (cont $ft))
          (tag $tag)


          (func $suspend (export "suspend")
            (suspend $tag)
          )

          (func $resume (export "resume") (param $f (ref $ct))
            (block $handler (result (ref $ct))
              (resume $ct (on $tag $handler) (local.get $f))
              (unreachable)
            )
            (drop)
          )
        )
    "#;

    let wat_main = r#"
        (module

          (type $ft (func))
          (type $ct (cont $ft))

          (import "other" "suspend" (func $suspend))
          (import "other" "resume" (func $resume (param (ref $ct))))

          (elem declare func $suspend)


          (func $entry (export "entry")
            (call $resume (cont.new $ct (ref.func $suspend)))
          )
        )
    "#;

    let module_other = Module::new(&engine, wat_other)?;

    let other_inst1 = Instance::new(&mut store, &module_other, &[])?;
    let other_inst2 = Instance::new(&mut store, &module_other, &[])?;

    // Crucially, suspend and resume are from two separate instances
    // of the same module.
    let suspend = other_inst1.get_func(&mut store, "suspend").unwrap();
    let resume = other_inst2.get_func(&mut store, "resume").unwrap();

    let module_main = Module::new(&engine, wat_main)?;
    let main_instance = Instance::new(&mut store, &module_main, &[suspend.into(), resume.into()])?;
    let entry_func = main_instance.get_func(&mut store, "entry").unwrap();

    let result = entry_func.call(&mut store, &[], &mut []);
    assert!(result.is_err());
    Ok(())
}

/// Tests interaction with host functions. Note that the interaction with host
/// functions and traps is covered by the module `traps` further down.
mod host {
    use super::test_utils::*;
    use wasmtime::*;

    const CONTINUATION_TRAP_MODULE: &str = r#"
    (module
        (import "host" "reenter" (func $host-reenter))
        (import "host" "trap" (func $host-trap))

        (type $ft (func))
        (type $ct (cont $ft))

        (global $stacks-left (mut i32) (i32.const 0))
        (global $frames-left (mut i32) (i32.const 0))
        (global $frames-per-stack (mut i32) (i32.const 0))
        (global $trap-in-host (mut i32) (i32.const 0))
        (global $g (export "g") (mut i32) (i32.const 0))

        (func $increment
            (global.set $g
                (i32.add (global.get $g) (i32.const 1))))

        (func $continue (export "continue")
            (if (i32.gt_u (global.get $frames-left) (i32.const 0))
                (then
                    (global.set $frames-left
                        (i32.sub (global.get $frames-left) (i32.const 1)))
                    (call $host-reenter))
                (else
                    (if (i32.gt_u (global.get $stacks-left) (i32.const 0))
                        (then
                            ;; Install a new child stack.
                            (global.set $stacks-left
                                (i32.sub (global.get $stacks-left) (i32.const 1)))
                            (global.set $frames-left (global.get $frames-per-stack))
                            (resume $ct (cont.new $ct (ref.func $continue))))
                        (else
                            ;; Call either the host provided trap, or the native Wasm trapping instruction `unreachable`.
                            (if (global.get $trap-in-host)
                                (then (call $host-trap))
                                (else unreachable))))))

            ;; No frame, on any stack, may resume after the terminal trap.
            (call $increment))

        (func (export "run")
            (param $stacks i32)
            (param $frames-per-stack-arg i32)
            (param $trap-in-host-arg i32)
            (global.set $stacks-left (local.get $stacks))
            (global.set $frames-left (local.get $frames-per-stack-arg))
            (global.set $frames-per-stack (local.get $frames-per-stack-arg))
            (global.set $trap-in-host (local.get $trap-in-host-arg))
            (call $continue))

        (elem declare func $continue)
    )
"#;

    fn increment_global<T>(caller: &mut Caller<'_, T>) -> Result<()> {
        let g = caller.get_export("g").unwrap().into_global().unwrap();
        let value = g.get(&mut *caller).unwrap_i32();
        g.set(caller, Val::I32(value + 1))
    }

    fn assert_expected_trap(error: &Error, trap_in_host: bool, stacks: i32, frames_per_stack: i32) {
        if trap_in_host {
            assert!(
                format!("{error:#}").contains("intentional host trap"),
                "unexpected error for stacks={stacks}, frames_per_stack={frames_per_stack}: {error:#}"
            );
        } else {
            assert_eq!(
                error.downcast_ref::<Trap>(),
                Some(&Trap::UnreachableCodeReached),
                "unexpected error for stacks={stacks}, frames_per_stack={frames_per_stack}: {error:#}"
            );
        }
    }

    fn host_trap() -> Result<()> {
        bail!("intentional host trap")
    }

    // TODO(dhil): Enable ASAN. ASAN produces a false positive here,
    // because ASAN thinks the thread is on the default stack. We need to
    // instrument the stack switching runtime to inform ASAN about the
    // switching of stacks.
    #[test]
    #[cfg_attr(any(asan, miri), ignore)]
    fn traps_cross_continuation_stacks_and_host_frames() -> Result<()> {
        let mut config = Config::new();
        config.wasm_stack_switching(true);
        let engine = Engine::new(&config)?;
        let module = Module::new(&engine, CONTINUATION_TRAP_MODULE)?;

        // Exercise short continuation chains with different numbers of alternating
        // Wasm and host frames on each stack. Test both a Wasm trap and a host trap
        // as the youngest frame.
        for stacks in 0..=10 {
            for frames_per_stack in 0..=10 {
                for trap_in_host in [false, true] {
                    let mut store = Store::new(&engine, ());
                    let reenter =
                        Func::wrap(&mut store, |mut caller: Caller<'_, ()>| -> Result<()> {
                            let continue_ = caller
                                .get_export("continue")
                                .unwrap()
                                .into_func()
                                .unwrap()
                                .typed::<(), ()>(&caller)?;
                            continue_.call(&mut caller, ())?;

                            // This must not execute: the recursive call always traps.
                            increment_global(&mut caller)
                        });
                    let host_trap = Func::wrap(&mut store, host_trap);
                    let instance =
                        Instance::new(&mut store, &module, &[reenter.into(), host_trap.into()])?;

                    let run = instance.get_typed_func::<(i32, i32, i32), ()>(&mut store, "run")?;
                    let error = run
                        .call(
                            &mut store,
                            (stacks, frames_per_stack, i32::from(trap_in_host)),
                        )
                        .unwrap_err();

                    assert_expected_trap(&error, trap_in_host, stacks, frames_per_stack);

                    let g = instance.get_global(&mut store, "g").unwrap();
                    assert_eq!(g.get(&mut store).unwrap_i32(), 0);
                }
            }
        }

        Ok(())
    }

    #[derive(Default)]
    struct CatchState {
        error: Option<Error>,
    }

    // TODO(dhil): Enable ASAN.
    #[test]
    #[cfg_attr(any(asan, miri), ignore)]
    fn parent_frames_resume_after_host_catches_trap() -> Result<()> {
        let mut config = Config::new();
        config.wasm_stack_switching(true);
        let engine = Engine::new(&config)?;
        let module = Module::new(&engine, CONTINUATION_TRAP_MODULE)?;

        for stacks in 0..=10 {
            // At least one host re-entry is needed to catch the terminal trap.
            for frames_per_stack in 1..=10 {
                for trap_in_host in [false, true] {
                    let mut store = Store::new(&engine, CatchState::default());
                    let reenter = Func::wrap(
                        &mut store,
                        |mut caller: Caller<'_, CatchState>| -> Result<()> {
                            let continue_ = caller
                                .get_export("continue")
                                .unwrap()
                                .into_func()
                                .unwrap()
                                .typed::<(), ()>(&caller)?;

                            if let Err(error) = continue_.call(&mut caller, ()) {
                                let previous = caller.data_mut().error.replace(error);
                                assert!(
                                    previous.is_none(),
                                    "more than one host frame caught a trap"
                                );
                            }

                            increment_global(&mut caller)
                        },
                    );
                    let host_trap = Func::wrap(&mut store, host_trap);
                    let instance =
                        Instance::new(&mut store, &module, &[reenter.into(), host_trap.into()])?;

                    let run = instance.get_typed_func::<(i32, i32, i32), ()>(&mut store, "run")?;
                    run.call(
                        &mut store,
                        (stacks, frames_per_stack, i32::from(trap_in_host)),
                    )?;

                    let error = store
                        .data()
                        .error
                        .as_ref()
                        .expect("a host frame should have caught the terminal trap");
                    assert_expected_trap(error, trap_in_host, stacks, frames_per_stack);

                    // `stacks` counts child stacks, so there are `stacks + 1`
                    // stacks in total. Each has `frames_per_stack` host frames and
                    // `frames_per_stack + 1` Wasm frames. All frames except the
                    // terminal trapping Wasm frame return and increment `g`.
                    let expected = (stacks + 1) * (2 * frames_per_stack + 1) - 1;
                    let g = instance.get_global(&mut store, "g").unwrap();
                    assert_eq!(
                        g.get(&mut store).unwrap_i32(),
                        expected,
                        "wrong count for stacks={stacks}, frames_per_stack={frames_per_stack}"
                    );
                }
            }
        }

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests calling a host function from within a wasm function running inside a continuation.
    /// Call chain:
    /// $entry -resume-> a -call-> host_func_a
    fn call_host_from_continuation() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (result i32)))
            (type $ct (cont $ft))

            (import "" "" (func $host_func_a (param i32) (result i32)))

            (func $a (export "a") (result i32)
                (call $host_func_a (i32.const 122))
            )
            (func $entry (export "entry") (result i32)
                (resume $ct (cont.new $ct (ref.func $a)))
            )
        )
    "#;

        let mut runner = Runner::new();

        let host_func_a = make_i32_inc_host_func(&mut runner);

        let result = runner.run_test::<i32>(wat, &[host_func_a.into()]).unwrap();
        assert_eq!(result, 123);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// We re-enter wasm from a host function and execute a continuation.
    /// Call chain:
    /// $entry -call-> $a -call-> $host_func_a -call-> $b -resume-> $c
    fn re_enter_wasm_ok1() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (param i32) (result i32)))
            (type $ct (cont $ft))

            (import "" "" (func $host_func_a (param i32) (result i32)))


            (func $a (export "a") (param $x i32) (result i32)
                (call $host_func_a (local.get $x))
            )

            (func $b (export "b") (param $x i32) (result i32)
                (resume $ct (local.get $x) (cont.new $ct (ref.func $c)))
            )

            (func $c (export "c") (param $x i32) (result i32)
                (return (i32.add (local.get $x) (i32.const 1)))
            )


            (func $entry (export "entry") (result i32)
                (call $a (i32.const 120))
            )
        )
    "#;

        let mut runner = Runner::new();

        let host_func_a = make_i32_inc_via_export_host_func(&mut runner, "b");

        let result = runner.run_test::<i32>(wat, &[host_func_a.into()]).unwrap();
        assert_eq!(result, 123);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Similar to `re_enter_wasm_ok2, but we run a continuation before the host call.
    /// Call chain:
    /// $entry -call-> $a -call-> $host_func_a -call-> $b -resume-> $c
    fn re_enter_wasm_ok2() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (param i32) (result i32)))
            (type $ct (cont $ft))

            (import "" "" (func $host_func_a (param i32) (result i32)))


            (func $a (export "a") (param $x i32) (result i32)
                ;; Running continuation before calling into host is fine
                (resume $ct (local.get $x) (cont.new $ct (ref.func $c)))
                (drop)

                (call $host_func_a (local.get $x))
            )

            (func $b (export "b") (param $x i32) (result i32)
                (resume $ct (local.get $x) (cont.new $ct (ref.func $c)))
            )

            (func $c (export "c") (param $x i32) (result i32)
                (return (i32.add (local.get $x) (i32.const 1)))
            )


            (func $entry (export "entry") (result i32)
                (call $a (i32.const 120))
            )
        )
    "#;

        let mut runner = Runner::new();

        let host_func_a = make_i32_inc_via_export_host_func(&mut runner, "b");

        let result = runner.run_test::<i32>(wat, &[host_func_a.into()]).unwrap();
        assert_eq!(result, 123);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// We re-enter Wasm from a host function while already running on a
    /// continuation stack.
    /// Call chain:
    /// $entry -resume-> $a -call-> $host_func_a -call-> $b
    fn re_enter_wasm_from_continuation() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (param i32) (result i32)))
            (type $ct (cont $ft))

            (import "" "" (func $host_func_a (param i32) (result i32)))


            (func $a (export "a") (param $x i32) (result i32)
                (call $host_func_a (local.get $x))
            )


            (func $b (export "b") (param $x i32) (result i32)
                 (return (i32.add (local.get $x) (i32.const 1)))
            )


            (func $entry (export "entry") (result i32)
                (resume $ct (i32.const 120) (cont.new $ct (ref.func $a)))
            )
        )
    "#;
        let mut runner = Runner::new();

        let host_func_a = make_i32_inc_via_export_host_func(&mut runner, "b");

        let result = runner.run_test::<i32>(&wat, &[host_func_a.into()])?;
        assert_eq!(result, 123);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// After crossing from the host back into wasm, we suspend to a tag that is
    /// handled by the surrounding function (i.e., without needing to cross the
    /// host frame to reach the handler).
    /// Call chain:
    /// $entry -resume-> $a -call-> $host_func_a -call-> $b -resume-> $c
    fn call_host_from_continuation_nested_suspend_ok() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (param i32) (result i32)))
            (type $ct (cont $ft))
            (tag $t (result i32))

            (import "" "" (func $host_func_a (param i32) (result i32)))


            (func $a (export "a") (param $x i32) (result i32)
                (call $host_func_a (local.get $x))
            )


            (func $b (export "b") (param $x i32) (result i32)
                (block $h (result (ref $ct))
                  (resume $ct (on $t $h) (local.get $x) (cont.new $ct (ref.func $c)))
                  (unreachable)
                )
                (drop)
                ;; note that we do not run the continuation to completion
                (i32.add (local.get $x) (i32.const 1))
            )

            (func $c (export "c") (param $x i32) (result i32)
                (suspend $t)
            )


            (func $entry (export "entry") (result i32)
                (resume $ct (i32.const 120) (cont.new $ct (ref.func $a)))
            )
        )
    "#;

        let mut runner = Runner::new();

        let host_func_a = make_i32_inc_via_export_host_func(&mut runner, "b");

        let result = runner.run_test::<i32>(&wat, &[host_func_a.into()])?;
        assert_eq!(result, 123);
        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Similar to `call_host_from_continuation_nested_suspend_ok`. However,
    /// we suspend to a tag that is only handled if we were to cross a host function
    /// boundary.
    /// Host calls act as barriers for suspensions, so the inner `resume`
    /// observes an unhandled tag.
    ///
    /// Call chain:
    /// $entry -resume-> $a -call-> $host_func_a -call-> $b -resume-> $c
    fn call_host_from_continuation_nested_suspend_unhandled() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (param i32) (result i32)))
            (type $ct (cont $ft))
            (tag $t (result i32))

            (import "" "" (func $host_func_a (param i32) (result i32)))


            (func $a (export "a") (param $x i32) (result i32)
                (call $host_func_a (local.get $x))
            )


            (func $b (export "b") (param $x i32) (result i32)
                (resume $ct (local.get $x) (cont.new $ct (ref.func $c)))
            )

            (func $c (export "c") (param $x i32) (result i32)
                (suspend $t)
            )


            (func $entry (export "entry")
                (block $h (result (ref $ct))
                    (return
                        (resume $ct
                            (on $t $h)
                            (i32.const 123)
                            (cont.new $ct (ref.func $a))))
                )
                (drop)
            )
        )
    "#;

        let mut runner = Runner::new();

        let host_func_a = make_i32_inc_via_export_host_func(&mut runner, "b");

        let error = runner
            .run_test::<()>(&wat, &[host_func_a.into()])
            .unwrap_err();
        assert_eq!(
            error.downcast_ref::<Trap>(),
            Some(&Trap::UnhandledTag),
            "unexpected error: {error:#}"
        );
        Ok(())
    }
}

mod traps {
    use super::test_utils::*;
    use wasmtime::*;

    /// Runs the module given as `wat`. We expect execution to cause the
    /// `expected_trap` and a backtrace containing exactly the function names
    /// given by `expected_backtrace`.
    fn run_test_expect_trap_backtrace(wat: &str, expected_trap: Trap, expected_backtrace: &[&str]) {
        let runner = Runner::new();
        let result = runner.run_test::<()>(wat, &[]);

        let err = result.expect_err("Was expecting wasm execution to yield error");

        assert!(err.root_cause().is::<Trap>());
        assert_eq!(*err.downcast_ref::<Trap>().unwrap(), expected_trap);

        let trace = err.downcast_ref::<WasmBacktrace>().unwrap();

        let actual_func_name_it = trace
            .frames()
            .iter()
            .map(|frame| {
                frame
                    .func_name()
                    .expect("Expecting all functions in actual backtrace to have names")
            })
            .rev();

        let expected_func_name_it = expected_backtrace.iter().copied();

        assert!(actual_func_name_it.eq(expected_func_name_it));
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces if we trap deep inside multiple continuations.
    /// Call chain:
    /// $entry -call-> $a -resume-> $b -call-> $c -resume-> $d -call-> $e -resume-> $f
    /// Here, $f traps.
    fn trap_in_continuation_nested() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
            )

            (func $b (export "b")
                (call $c)
            )

            (func $c (export "c")
                (resume $ct (cont.new $ct (ref.func $d)))
            )

            (func $d (export "d")
              (call $e)
            )

            (func $e (export "e")
                (resume $ct (cont.new $ct (ref.func $f)))
            )

            (func $f (export "f")
                (unreachable)
            )
        )
        "#;

        run_test_expect_trap_backtrace(
            wat,
            Trap::UnreachableCodeReached,
            &["entry", "a", "b", "c", "d", "e", "f"],
        );

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces if we trap after returning from one
    /// continuation to its parent.
    fn trap_in_continuation_back_to_parent() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
            )

            (func $b (export "b")
                (call $c)
            )

            (func $c (export "c")
                (resume $ct (cont.new $ct (ref.func $d)))
                (unreachable)
            )

            (func $d (export "d")
                (call $e)
            )

            (func $e (export "e"))

        )
        "#;

        run_test_expect_trap_backtrace(
            wat,
            Trap::UnreachableCodeReached,
            &["entry", "a", "b", "c"],
        );

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces if we trap after returning from
    /// several continuations back to the main stack.
    fn trap_in_continuation_back_to_main() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
                (unreachable)
            )

            (func $b (export "b")
                (call $c)
            )

            (func $c (export "c")
                (resume $ct (cont.new $ct (ref.func $d)))
            )

            (func $d (export "d")
              (call $e)
            )

            (func $e (export "e"))

        )
        "#;

        run_test_expect_trap_backtrace(wat, Trap::UnreachableCodeReached, &["entry", "a"]);

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces after suspending a continuation.
    fn trap_in_continuation_suspend() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))

            (tag $t)

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
                (unreachable)
            )

            (func $b (export "b")
                (call $c)
            )

            (func $c (export "c")
                (block $handler (result  (ref $ct))
                    (resume $ct (on $t $handler) (cont.new $ct (ref.func $d)))
                    (return)
                )
                (unreachable)
            )

            (func $d (export "d")
                (call $e)
            )

            (func $e (export "e")
                (suspend $t)
            )

        )
    "#;

        run_test_expect_trap_backtrace(
            wat,
            Trap::UnreachableCodeReached,
            &["entry", "a", "b", "c"],
        );

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces after suspending a continuation and
    /// then resuming it from a different stack frame.
    fn trap_in_continuation_suspend_resume() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))

            (tag $t)

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
            )

            (func $b (export "b")
                (resume $ct (call $c))
            )

            (func $c (export "c") (result (ref $ct))
                (block $handler (result  (ref $ct))
                    (resume $ct (on $t $handler) (cont.new $ct (ref.func $d)))

                    ;; We never want to get here, but also don't want to use
                    ;; (unreachable), which is the trap we deliberately use in
                    ;; this test. Instead, we call a null function ref here,
                    ;; which is guaranteed to trap.
                    (call_ref $ft (ref.null $ft))

                    (return (cont.new $ct (ref.func $d)))
                )
                ;; implicitly returning the continuation here
            )

            (func $d (export "d")
                (call $e)
                (unreachable)
            )

            (func $e (export "e")
                (suspend $t)
            )

        )
    "#;

        // Note that c does not appear in the stack trace:
        // In $b, we resume the suspended computation, which started in $d,
        // suspended in $e, and traps in $d
        run_test_expect_trap_backtrace(
            wat,
            Trap::UnreachableCodeReached,
            &["entry", "a", "b", "d"],
        );

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces after suspending a continuation
    /// where we need to forward to an outer handler.
    fn trap_in_continuation_forward() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))
            (tag $t)

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (block $handler (result  (ref $ct))
                    (resume $ct (on $t $handler) (cont.new $ct (ref.func $b)))
                    ;; We don't actually want to get here
                    (return)
                )
                (unreachable)
            )

            (func $b (export "b")
                (call $c)
            )

            (func $c (export "c")
                (resume $ct (cont.new $ct (ref.func $d)))
            )

            (func $d (export "d")
                (call $e)
            )

            (func $e (export "e")
                (suspend $t)
            )

        )
    "#;

        // Note that c does not appear in the stack trace:
        // In $b, we resume the suspended computation, which started in $d,
        // suspended in $e, and traps in $d
        run_test_expect_trap_backtrace(wat, Trap::UnreachableCodeReached, &["entry", "a"]);

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces after suspending a continuation
    /// where we need to forward to an outer handler. We then resume the
    /// continuation from within another continuation.
    fn trap_in_continuation_forward_resume() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))
            (tag $t)

            (global $k (mut (ref null $ct)) (ref.null $ct))

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
            )

            (func $b (export "b")
                (block $handler (result  (ref $ct))
                    (resume $ct (on $t $handler) (cont.new $ct (ref.func $c)))
                    ;; We don't actually want to get here
                    (return)
                )
                (global.set $k)
                ;; $f will resume $k
                (resume $ct (cont.new $ct (ref.func $f)))
            )

            (func $c (export "c")
                (resume $ct (cont.new $ct (ref.func $d)))
            )

            (func $d (export "d")
                (call $e)
            )

            (func $e (export "e")
                (suspend $t)
                (unreachable)
            )

           (func $f  (export "f")
               (resume $ct (global.get $k))
           )
        )
       "#;

        run_test_expect_trap_backtrace(
            wat,
            Trap::UnreachableCodeReached,
            &["entry", "a", "b", "f", "c", "d", "e"],
        );

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct backtraces after switch.
    /// We first create the a stack with the following shape:
    /// entry -> a -> b, then switch, leading to
    /// entry -> c -> d, at which point we resume the a -> b continuation:
    /// entry -> c -> d -> a -> b
    /// We trap at that point.
    fn trap_switch_and_resume() -> Result<()> {
        let wat = r#"
        (module
            (rec
                (type $ft0 (func (param (ref null $ct0))))
                (type $ct0 (cont $ft0)))

            (type $ft1 (func))
            (type $ct1 (cont $ft1))

            (tag $t)

            (func $a (type $ft1)
                (cont.new $ct1 (ref.func $b))
                (resume $ct1)
            )
            (elem declare func $a)

            (func $b (type $ft1)
                (cont.new $ct0 (ref.func $c))
                (switch $ct0 $t)

                ;; we want a backtrace here
                (unreachable)
            )
            (elem declare func $b)

            (func $c (type $ft0)
                (local.get 0)
                (cont.new $ct0 (ref.func $d))
                (resume $ct0)
            )
            (elem declare func $c)

            (func $d (type $ft0)
                (block $handler (result (ref $ct1))
                    (ref.null $ct0) ;; passed as payload
                    (local.get 0) ;; resumed
                    (resume $ct0 (on $t $handler))
                    (unreachable) ;; f1 will suspend after the switch
                 )
                (resume $ct1)
            )
            (elem declare func $d)

            (func $entry (export "entry")
                (cont.new $ct1 (ref.func $a))
                (resume $ct1 (on $t switch))
            )
        )
        "#;

        run_test_expect_trap_backtrace(
            wat,
            Trap::UnreachableCodeReached,
            &["entry", "c", "d", "a", "b"],
        );

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    /// Tests that we get correct panic payloads  if we panic deep inside multiple
    /// continuations. Note that wasmtime does not create its own backtraces for panics.
    fn panic_in_continuation() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func))
            (type $ct (cont $ft))

            (import "" "" (func $f))

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                (resume $ct (cont.new $ct (ref.func $b)))
            )

            (func $b (export "b")
                (call $c)
            )

            (func $c (export "c")
                (resume $ct (cont.new $ct (ref.func $d)))
            )

            (func $d (export "d")
                (call $e)
            )

            (func $e (export "e")
                (call $f)
            )

        )
        "#;

        let mut runner = Runner::new();

        let msg = "Host function f panics";

        let f = make_panicking_host_func(&mut runner.store, msg);
        let error = runner.run_test_expect_panic(wat, &[f.into()]);
        assert_eq!(error.downcast_ref::<&'static str>(), Some(&msg));

        Ok(())
    }

    #[cfg_attr(any(asan, miri), ignore)]
    #[test]
    fn stack_overflow_in_continuation() -> Result<()> {
        let wat = r#"
        (module
            (type $ft (func (param i32)))
            (type $ct (cont $ft))

            (func $entry (export "entry")
                (call $a)
            )

            (func $a (export "a")
                ;; We ask for a billion recursive calls
                (i32.const 1_000_000_000)

                (resume $ct (cont.new $ct (ref.func $overflow)))
            )

            (func $overflow (export "overflow") (param $i i32)
                (block $continue
                    (local.get $i)
                    ;; return if $i == 0
                    (br_if $continue)
                    (return)
                )
                (i32.sub (local.get $i) (i32.const 1))
                (call $overflow)
            )

        )
    "#;

        let runner = Runner::new();

        let error = runner
            .run_test::<()>(wat, &[])
            .expect_err("Expecting execution to yield error");

        assert!(error.root_cause().is::<Trap>());
        assert_eq!(*error.downcast_ref::<Trap>().unwrap(), Trap::StackOverflow);

        Ok(())
    }
}