wasmtime-cli 24.0.8

Command-line interface for Wasmtime
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
use super::ref_types_module;
use super::skip_pooling_allocator_tests;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
use std::sync::Arc;
use wasmtime::*;

struct SetFlagOnDrop(Arc<AtomicBool>);

impl Drop for SetFlagOnDrop {
    fn drop(&mut self) {
        self.0.store(true, SeqCst);
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn smoke_test_gc_no_epochs() -> Result<()> {
    smoke_test_gc_impl(false)
}

#[test]
#[cfg_attr(miri, ignore)]
fn smoke_test_gc_yes_epochs() -> Result<()> {
    smoke_test_gc_impl(true)
}

fn smoke_test_gc_impl(use_epochs: bool) -> Result<()> {
    let (mut store, module) = ref_types_module(
        use_epochs,
        r#"
            (module
                (import "" "" (func $do_gc))
                (func $recursive (export "func") (param i32 externref) (result externref)
                    local.get 0
                    i32.eqz
                    if (result externref)
                        call $do_gc
                        local.get 1
                    else
                        local.get 0
                        i32.const 1
                        i32.sub
                        local.get 1
                        call $recursive
                    end
                )
            )
        "#,
    )?;

    let do_gc = Func::wrap(&mut store, |mut caller: Caller<'_, _>| {
        // Do a GC with `externref`s on the stack in Wasm frames.
        caller.gc();
    });
    let instance = Instance::new(&mut store, &module, &[do_gc.into()])?;
    let func = instance.get_func(&mut store, "func").unwrap();

    let inner_dropped = Arc::new(AtomicBool::new(false));

    {
        let mut scope = RootScope::new(&mut store);

        let r = ExternRef::new(&mut scope, SetFlagOnDrop(inner_dropped.clone()))?;
        {
            let args = [Val::I32(5), Val::ExternRef(Some(r.clone()))];
            func.call(&mut scope, &args, &mut [Val::I32(0)])?;
        }

        // Doing a GC should see that there aren't any `externref`s on the stack in
        // Wasm frames anymore.
        scope.as_context_mut().gc();

        // But the scope should still be rooting `r`.
        assert!(!inner_dropped.load(SeqCst));
    }

    // Exiting the scope and unrooting `r` should have dropped the inner
    // `SetFlagOnDrop` value.
    assert!(inner_dropped.load(SeqCst));

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn wasm_dropping_refs() -> Result<()> {
    let (mut store, module) = ref_types_module(
        false,
        r#"
            (module
                (func (export "drop_ref") (param externref)
                    nop
                )
            )
        "#,
    )?;

    let instance = Instance::new(&mut store, &module, &[])?;
    let drop_ref = instance.get_func(&mut store, "drop_ref").unwrap();

    let num_refs_dropped = Arc::new(AtomicUsize::new(0));

    // NB: 4096 is greater than the initial `VMExternRefActivationsTable`
    // capacity, so this will trigger at least one GC.
    for _ in 0..4096 {
        let mut scope = RootScope::new(&mut store);
        let r = ExternRef::new(&mut scope, CountDrops(num_refs_dropped.clone()))?;
        let args = [Val::ExternRef(Some(r))];
        drop_ref.call(&mut scope, &args, &mut [])?;
    }

    assert!(num_refs_dropped.load(SeqCst) > 0);

    // And after doing a final GC, all the refs should have been dropped.
    store.gc();
    assert_eq!(num_refs_dropped.load(SeqCst), 4096);

    return Ok(());

    struct CountDrops(Arc<AtomicUsize>);

    impl Drop for CountDrops {
        fn drop(&mut self) {
            self.0.fetch_add(1, SeqCst);
        }
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn many_live_refs() -> Result<()> {
    let mut wat = r#"
        (module
            ;; Make new `externref`s.
            (import "" "make_ref" (func $make_ref (result externref)))

            ;; Observe an `externref` so it is kept live.
            (import "" "observe_ref" (func $observe_ref (param externref)))

            (func (export "many_live_refs")
    "#
    .to_string();

    // This is more than the initial `VMExternRefActivationsTable` capacity, so
    // it will need to allocate additional bump chunks.
    const NUM_LIVE_REFS: usize = 1024;

    // Push `externref`s onto the stack.
    for _ in 0..NUM_LIVE_REFS {
        wat.push_str("(call $make_ref)\n");
    }

    // Pop `externref`s from the stack. Because we pass each of them to a
    // function call here, they are all live references for the duration of
    // their lifetimes.
    for _ in 0..NUM_LIVE_REFS {
        wat.push_str("(call $observe_ref)\n");
    }

    wat.push_str(
        "
            ) ;; func
        ) ;; module
        ",
    );

    let (mut store, module) = ref_types_module(false, &wat)?;

    let live_refs = Arc::new(AtomicUsize::new(0));

    let make_ref = Func::wrap(&mut store, {
        let live_refs = live_refs.clone();
        move |mut caller: Caller<'_, _>| {
            Ok(Some(ExternRef::new(
                &mut caller,
                CountLiveRefs::new(live_refs.clone()),
            )?))
        }
    });

    let observe_ref = Func::wrap(
        &mut store,
        |caller: Caller<'_, _>, r: Option<Rooted<ExternRef>>| {
            let r = r
                .unwrap()
                .data(&caller)
                .unwrap()
                .downcast_ref::<CountLiveRefs>()
                .unwrap();
            assert!(r.live_refs.load(SeqCst) > 0);
        },
    );

    let instance = Instance::new(&mut store, &module, &[make_ref.into(), observe_ref.into()])?;
    let many_live_refs = instance.get_func(&mut store, "many_live_refs").unwrap();

    many_live_refs.call(&mut store, &[], &mut [])?;

    store.as_context_mut().gc();
    assert_eq!(live_refs.load(SeqCst), 0);

    return Ok(());

    struct CountLiveRefs {
        live_refs: Arc<AtomicUsize>,
    }

    impl CountLiveRefs {
        fn new(live_refs: Arc<AtomicUsize>) -> Self {
            live_refs.fetch_add(1, SeqCst);
            Self { live_refs }
        }
    }

    impl Drop for CountLiveRefs {
        fn drop(&mut self) {
            self.live_refs.fetch_sub(1, SeqCst);
        }
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn drop_externref_via_table_set() -> Result<()> {
    let (mut store, module) = ref_types_module(
        false,
        r#"
            (module
                (table $t 1 externref)

                (func (export "table-set") (param externref)
                  (table.set $t (i32.const 0) (local.get 0))
                )
            )
        "#,
    )?;

    let instance = Instance::new(&mut store, &module, &[])?;
    let table_set = instance.get_func(&mut store, "table-set").unwrap();

    let foo_is_dropped = Arc::new(AtomicBool::new(false));
    let bar_is_dropped = Arc::new(AtomicBool::new(false));

    {
        let mut scope = RootScope::new(&mut store);

        let foo = ExternRef::new(&mut scope, SetFlagOnDrop(foo_is_dropped.clone()))?;
        let bar = ExternRef::new(&mut scope, SetFlagOnDrop(bar_is_dropped.clone()))?;

        {
            let args = vec![Val::ExternRef(Some(foo))];
            table_set.call(&mut scope, &args, &mut [])?;
        }

        scope.as_context_mut().gc();
        assert!(!foo_is_dropped.load(SeqCst));
        assert!(!bar_is_dropped.load(SeqCst));

        {
            let args = vec![Val::ExternRef(Some(bar))];
            table_set.call(&mut scope, &args, &mut [])?;
        }
    }

    store.gc();
    assert!(foo_is_dropped.load(SeqCst));
    assert!(!bar_is_dropped.load(SeqCst));

    table_set.call(&mut store, &[Val::ExternRef(None)], &mut [])?;
    assert!(foo_is_dropped.load(SeqCst));
    assert!(bar_is_dropped.load(SeqCst));

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn global_drops_externref() -> Result<()> {
    let _ = env_logger::try_init();
    test_engine(&Engine::default())?;

    if !skip_pooling_allocator_tests() {
        test_engine(&Engine::new(
            Config::new().allocation_strategy(InstanceAllocationStrategy::pooling()),
        )?)?;
    }

    return Ok(());

    fn test_engine(engine: &Engine) -> Result<()> {
        let mut store = Store::new(&engine, ());
        let flag = Arc::new(AtomicBool::new(false));
        let externref = ExternRef::new(&mut store, SetFlagOnDrop(flag.clone()))?;
        Global::new(
            &mut store,
            GlobalType::new(ValType::EXTERNREF, Mutability::Const),
            externref.into(),
        )?;
        drop(store);
        assert!(flag.load(SeqCst));

        let mut store = Store::new(&engine, ());
        let module = Module::new(
            &engine,
            r#"
                (module
                    (global (mut externref) (ref.null extern))

                    (func (export "run") (param externref)
                        local.get 0
                        global.set 0
                    )
                )
            "#,
        )?;
        let instance = Instance::new(&mut store, &module, &[])?;
        let run = instance.get_typed_func::<Option<Rooted<ExternRef>>, ()>(&mut store, "run")?;
        let flag = Arc::new(AtomicBool::new(false));
        let externref = ExternRef::new(&mut store, SetFlagOnDrop(flag.clone()))?;
        run.call(&mut store, Some(externref))?;
        drop(store);
        assert!(flag.load(SeqCst));
        Ok(())
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn table_drops_externref() -> Result<()> {
    let _ = env_logger::try_init();
    test_engine(&Engine::default())?;

    if !skip_pooling_allocator_tests() {
        test_engine(&Engine::new(
            Config::new().allocation_strategy(InstanceAllocationStrategy::pooling()),
        )?)?;
    }

    return Ok(());

    fn test_engine(engine: &Engine) -> Result<()> {
        let mut store = Store::new(&engine, ());
        let flag = Arc::new(AtomicBool::new(false));
        let externref = ExternRef::new(&mut store, SetFlagOnDrop(flag.clone()))?;
        Table::new(
            &mut store,
            TableType::new(RefType::EXTERNREF, 1, None),
            externref.into(),
        )?;
        drop(store);
        assert!(flag.load(SeqCst));

        let mut store = Store::new(&engine, ());
        let module = Module::new(
            &engine,
            r#"
            (module
                (table 1 externref)

                (func (export "run") (param externref)
                    i32.const 0
                    local.get 0
                    table.set 0
                )
            )
        "#,
        )?;
        let instance = Instance::new(&mut store, &module, &[])?;
        let run = instance.get_typed_func::<Option<Rooted<ExternRef>>, ()>(&mut store, "run")?;
        let flag = Arc::new(AtomicBool::new(false));
        let externref = ExternRef::new(&mut store, SetFlagOnDrop(flag.clone()))?;
        run.call(&mut store, Some(externref))?;
        drop(store);
        assert!(flag.load(SeqCst));
        Ok(())
    }
}

#[test]
fn global_init_no_leak() -> Result<()> {
    let (mut store, module) = ref_types_module(
        false,
        r#"
            (module
                (import "" "" (global externref))
                (global externref (global.get 0))
            )
        "#,
    )?;

    let flag = Arc::new(AtomicBool::new(false));
    let externref = ExternRef::new(&mut store, SetFlagOnDrop(flag.clone()))?;
    let global = Global::new(
        &mut store,
        GlobalType::new(ValType::EXTERNREF, Mutability::Const),
        externref.clone().into(),
    )?;
    Instance::new(&mut store, &module, &[global.into()])?;
    drop(store);
    assert!(flag.load(SeqCst));

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn no_gc_middle_of_args() -> Result<()> {
    let (mut store, module) = ref_types_module(
        false,
        r#"
            (module
                (import "" "return_some" (func $return (result externref externref externref)))
                (import "" "take_some" (func $take (param externref externref externref)))
                (func (export "run")
                    (local i32)
                    i32.const 1000
                    local.set 0
                    loop
                        call $return
                        call $take
                        local.get 0
                        i32.const -1
                        i32.add
                        local.tee 0
                        br_if 0
                    end
                )
            )
        "#,
    )?;

    let mut linker = Linker::new(store.engine());
    linker.func_wrap("", "return_some", |mut caller: Caller<'_, _>| {
        let a = Some(ExternRef::new(&mut caller, String::from("a"))?);
        let b = Some(ExternRef::new(&mut caller, String::from("b"))?);
        let c = Some(ExternRef::new(&mut caller, String::from("c"))?);
        Ok((a, b, c))
    })?;
    linker.func_wrap(
        "",
        "take_some",
        |caller: Caller<'_, _>,
         a: Option<Rooted<ExternRef>>,
         b: Option<Rooted<ExternRef>>,
         c: Option<Rooted<ExternRef>>| {
            let a = a.unwrap();
            let b = b.unwrap();
            let c = c.unwrap();
            assert_eq!(
                a.data(&caller)
                    .expect("rooted")
                    .downcast_ref::<String>()
                    .expect("is string"),
                "a"
            );
            assert_eq!(
                b.data(&caller)
                    .expect("rooted")
                    .downcast_ref::<String>()
                    .expect("is string"),
                "b"
            );
            assert_eq!(
                c.data(&caller)
                    .expect("rooted")
                    .downcast_ref::<String>()
                    .expect("is string"),
                "c"
            );
        },
    )?;

    let instance = linker.instantiate(&mut store, &module)?;
    let func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
    func.call(&mut store, ())?;

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn gc_and_tail_calls_and_stack_arguments() -> Result<()> {
    // Test that GC refs in tail-calls' stack arguments get properly accounted
    // for in stack maps.
    //
    // What we do _not_ want to happen is for tail callers to be responsible for
    // including stack arguments in their stack maps (and therefore whether or
    // not they get marked at runtime). If that was the case, then we could have
    // the following scenario:
    //
    // * `f` calls `g` without any stack arguments,
    // * `g` tail calls `h` with GC ref stack arguments,
    // * and then `h` triggers a GC.
    //
    // Because `g`, who is responsible for including the GC refs in its stack
    // map in this hypothetical scenario, is no longer on the stack, we never
    // see its stack map, and therefore never mark the GC refs, and then we
    // collect them too early, and then we can get user-after-free bugs. Not
    // good! Note also that `f`, which is the frame that `h` will return to,
    // _cannot_ be responsible for including these stack arguments in its stack
    // map, because it has no idea what frame will be returning to it, and it
    // could be any number of different functions using that frame for long (and
    // indirect!) tail-call chains.
    //
    // In Cranelift we avoid this scenario because stack arguments are eagerly
    // loaded into virtual registers, and then when we insert a GC safe point,
    // we spill these virtual registers to the callee stack frame, and the stack
    // map includes entries for these stack slots.
    //
    // Nonetheless, this test exercises the above scenario just in case we do
    // something in the future like lazily load stack arguments into virtual
    // registers, to make sure that everything shows up in stack maps like they
    // are supposed to.

    let (mut store, module) = ref_types_module(
        false,
        r#"
            (module
                (import "" "make_some" (func $make (result externref externref externref)))
                (import "" "take_some" (func $take (param externref externref externref)))
                (import "" "gc" (func $gc))

                (func $stack_args (param externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref externref)
                  call $gc
                  ;; Make sure all these GC refs are live, so that they need to
                  ;; be put into the stack map.
                  local.get 0
                  local.get 1
                  local.get 2
                  call $take
                  local.get 3
                  local.get 4
                  local.get 5
                  call $take
                  local.get 6
                  local.get 7
                  local.get 8
                  call $take
                  local.get 9
                  local.get 10
                  local.get 11
                  call $take
                  local.get 12
                  local.get 13
                  local.get 14
                  call $take
                  local.get 15
                  local.get 16
                  local.get 17
                  call $take
                  local.get 18
                  local.get 19
                  local.get 20
                  call $take
                  local.get 21
                  local.get 22
                  local.get 23
                  call $take
                  local.get 24
                  local.get 25
                  local.get 26
                  call $take
                  local.get 27
                  local.get 28
                  local.get 29
                  call $take
                )

                (func $no_stack_args
                  call $make
                  call $make
                  call $make
                  call $make
                  call $make
                  call $make
                  call $make
                  call $make
                  call $make
                  call $make
                  return_call $stack_args
                )

                (func (export "run")
                    (local i32)
                    i32.const 1000
                    local.set 0
                    loop
                        call $no_stack_args
                        local.get 0
                        i32.const -1
                        i32.add
                        local.tee 0
                        br_if 0
                    end
                )
            )
        "#,
    )?;

    let mut linker = Linker::new(store.engine());
    linker.func_wrap("", "make_some", |mut caller: Caller<'_, _>| {
        Ok((
            Some(ExternRef::new(&mut caller, "a".to_string())?),
            Some(ExternRef::new(&mut caller, "b".to_string())?),
            Some(ExternRef::new(&mut caller, "c".to_string())?),
        ))
    })?;
    linker.func_wrap(
        "",
        "take_some",
        |caller: Caller<'_, _>,
         a: Option<Rooted<ExternRef>>,
         b: Option<Rooted<ExternRef>>,
         c: Option<Rooted<ExternRef>>| {
            let a = a.unwrap();
            let b = b.unwrap();
            let c = c.unwrap();
            assert_eq!(
                a.data(&caller).unwrap().downcast_ref::<String>().unwrap(),
                "a"
            );
            assert_eq!(
                b.data(&caller).unwrap().downcast_ref::<String>().unwrap(),
                "b"
            );
            assert_eq!(
                c.data(&caller).unwrap().downcast_ref::<String>().unwrap(),
                "c"
            );
        },
    )?;
    linker.func_wrap("", "gc", |mut caller: Caller<()>| {
        caller.gc();
    })?;

    let instance = linker.instantiate(&mut store, &module)?;
    let func = instance.get_typed_func::<(), ()>(&mut store, "run")?;
    func.call(&mut store, ())?;

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn no_leak_with_global_get_elem_segment() -> anyhow::Result<()> {
    let dropped = Arc::new(AtomicBool::new(false));

    let engine = Engine::default();
    let mut store = Store::new(&engine, ());
    let module = Module::new(
        &engine,
        r#"
            (module
                (import "" "" (global $init externref))
                (start $f)
                (table $t 1 externref)
                (elem $e externref (global.get $init))

                (func $f
                    i32.const 0
                    i32.const 0
                    i32.const 1
                    table.init $t $e

                    i32.const 0
                    i32.const 0
                    i32.const 1
                    table.init $t $e
                )
            )
        "#,
    )?;

    let externref = ExternRef::new(&mut store, SetFlagOnDrop(dropped.clone()))?;
    let global = Global::new(
        &mut store,
        GlobalType::new(ValType::EXTERNREF, Mutability::Const),
        externref.into(),
    )?;

    Instance::new(&mut store, &module, &[global.into()])?;

    drop(store);

    assert!(dropped.load(SeqCst));
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn table_init_with_externref_global_get() -> anyhow::Result<()> {
    let dropped = Arc::new(AtomicBool::new(false));

    let mut config = Config::new();
    config.wasm_function_references(true);
    let engine = Engine::new(&config)?;
    let mut store = Store::new(&engine, ());
    let module = Module::new(
        &engine,
        r#"
            (module
                (import "" "" (global $init externref))
                (table $t 1 externref (global.get $init))
            )
        "#,
    )?;

    let externref = ExternRef::new(&mut store, SetFlagOnDrop(dropped.clone()))?;
    let global = Global::new(
        &mut store,
        GlobalType::new(ValType::EXTERNREF, Mutability::Const),
        externref.into(),
    )?;

    Instance::new(&mut store, &module, &[global.into()])?;

    drop(store);

    assert!(dropped.load(SeqCst));
    Ok(())
}

#[test]
fn rooted_gets_collected_after_scope_exit() -> Result<()> {
    let mut store = Store::<()>::default();
    let flag = Arc::new(AtomicBool::new(false));

    {
        let mut scope = RootScope::new(&mut store);
        let _externref = ExternRef::new(&mut scope, SetFlagOnDrop(flag.clone()))?;

        scope.as_context_mut().gc();
        assert!(!flag.load(SeqCst), "not dropped when still rooted");
    }

    store.as_context_mut().gc();
    assert!(flag.load(SeqCst), "dropped after being unrooted");

    Ok(())
}

#[test]
fn manually_rooted_gets_collected_after_unrooting() -> Result<()> {
    let mut store = Store::<()>::default();
    let flag = Arc::new(AtomicBool::new(false));

    let externref = ExternRef::new_manually_rooted(&mut store, SetFlagOnDrop(flag.clone()))?;

    store.gc();
    assert!(!flag.load(SeqCst), "not dropped when still rooted");

    externref.unroot(&mut store);
    store.gc();
    assert!(flag.load(SeqCst), "dropped after being unrooted");

    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn round_trip_gc_ref_through_typed_wasm_func() -> Result<()> {
    let mut store = Store::<()>::default();
    let module = Module::new(
        store.engine(),
        r#"
            (module
                (import "" "" (func $gc))
                (func (export "f") (param externref) (result externref)
                    call $gc
                    local.get 0
                )
            )
        "#,
    )?;
    let gc = Func::wrap(&mut store, |mut caller: Caller<'_, _>| caller.gc());
    let instance = Instance::new(&mut store, &module, &[gc.into()])?;
    let f = instance
        .get_typed_func::<Option<Rooted<ExternRef>>, Option<Rooted<ExternRef>>>(&mut store, "f")?;
    let x1 = ExternRef::new(&mut store, 1234)?;
    let x2 = f.call(&mut store, Some(x1))?.unwrap();
    assert!(Rooted::ref_eq(&store, &x1, &x2)?);
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn round_trip_gc_ref_through_func_wrap() -> Result<()> {
    let mut store = Store::<()>::default();
    let f = Func::wrap(
        &mut store,
        |mut caller: Caller<'_, _>, x: Rooted<ExternRef>| {
            caller.gc();
            x
        },
    );
    let f = f.typed::<Rooted<ExternRef>, Rooted<ExternRef>>(&store)?;
    let x1 = ExternRef::new(&mut store, 1234)?;
    let x2 = f.call(&mut store, x1)?;
    assert!(Rooted::ref_eq(&store, &x1, &x2)?);
    Ok(())
}

#[test]
fn to_raw_from_raw_doesnt_leak() -> Result<()> {
    let mut store = Store::<()>::default();
    let flag = Arc::new(AtomicBool::new(false));

    {
        let mut scope = RootScope::new(&mut store);
        let x = ExternRef::new(&mut scope, SetFlagOnDrop(flag.clone()))?;
        let raw = unsafe { x.to_raw(&mut scope)? };
        let _x = unsafe { ExternRef::from_raw(&mut scope, raw) };
    }

    store.gc();
    assert!(flag.load(SeqCst));
    Ok(())
}

#[test]
fn table_fill_doesnt_leak() -> Result<()> {
    let _ = env_logger::try_init();

    let mut store = Store::<()>::default();
    let flag = Arc::new(AtomicBool::new(false));

    {
        let mut scope = RootScope::new(&mut store);
        let x = ExternRef::new(&mut scope, SetFlagOnDrop(flag.clone()))?;
        let table = Table::new(
            &mut scope,
            TableType::new(RefType::EXTERNREF, 10, Some(10)),
            x.into(),
        )?;
        table.fill(&mut scope, 0, Ref::Extern(None), 10)?;
    }

    store.gc();
    assert!(flag.load(SeqCst));
    Ok(())
}

#[test]
#[cfg_attr(miri, ignore)]
fn table_copy_doesnt_leak() -> Result<()> {
    let _ = env_logger::try_init();

    let mut store = Store::<()>::default();
    let flag = Arc::new(AtomicBool::new(false));

    {
        let mut scope = RootScope::new(&mut store);
        let table = Table::new(
            &mut scope,
            TableType::new(RefType::EXTERNREF, 10, Some(10)),
            Ref::Extern(None),
        )?;

        let x = ExternRef::new(&mut scope, SetFlagOnDrop(flag.clone()))?;
        table.fill(&mut scope, 2, x.into(), 3)?;

        Table::copy(&mut scope, &table, 0, &table, 5, 5)?;
    }

    store.gc();
    assert!(flag.load(SeqCst));
    Ok(())
}