wasmtime-cli 44.0.1

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
#![cfg(not(miri))]

use super::REALLOC_AND_FREE;
use crate::call_hook::{Context, State, sync_call_hook};
use std::future::Future;
use std::pin::Pin;
use std::task::{self, Poll};
use wasmtime::component::*;
use wasmtime::{CallHook, CallHookHandler, Engine, Result, Store, StoreContextMut, bail};

// Crate a synchronous Func, call it directly:
#[test]
fn call_wrapped_func() -> Result<()> {
    let wat = r#"
        (component
            (import "f" (func $f))

            (core func $f_lower
                (canon lower (func $f))
            )
            (core module $m
                (import "" "" (func $f))

                (func $export
                    (call $f)
                )

                (export "export" (func $export))
            )
            (core instance $i (instantiate $m
                (with "" (instance
                    (export "" (func $f_lower))
                ))
            ))
            (func (export "export")
                (canon lift
                    (core func $i "export")
                )
            )
        )
    "#;

    let engine = Engine::default();
    let component = Component::new(&engine, wat)?;

    let mut linker = Linker::<State>::new(&engine);
    linker
        .root()
        .func_wrap("f", |_, _: ()| -> Result<()> { Ok(()) })?;

    let mut store = Store::new(&engine, State::default());
    store.call_hook(sync_call_hook);
    let inst = linker
        .instantiate(&mut store, &component)
        .expect("instantiate");

    let export = inst
        .get_typed_func::<(), ()>(&mut store, "export")
        .expect("looking up `export`");

    export.call(&mut store, ())?;

    let s = store.into_data();
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    Ok(())
}

// Call a func that turns a `list<u8>` into a `string`, to ensure that `realloc` calls are counted.
#[test]
fn call_func_with_realloc() -> Result<()> {
    let wat = format!(
        r#"(component
            (core module $m
                (memory (export "memory") 1)
                (func (export "roundtrip") (param i32 i32) (result i32)
                    (local $base i32)
                    (local.set $base
                        (call $realloc
                            (i32.const 0)
                            (i32.const 0)
                            (i32.const 4)
                            (i32.const 8)))
                    (i32.store offset=0
                        (local.get $base)
                        (local.get 0))
                    (i32.store offset=4
                        (local.get $base)
                        (local.get 1))
                    (local.get $base)
                )

                {REALLOC_AND_FREE}
            )
            (core instance $i (instantiate $m))

            (func (export "list8-to-str") (param "a" (list u8)) (result string)
                (canon lift
                    (core func $i "roundtrip")
                    (memory $i "memory")
                    (realloc (func $i "realloc"))
                )
            )
        )"#
    );

    let engine = Engine::default();
    let component = Component::new(&engine, wat)?;
    let linker = Linker::<State>::new(&engine);
    let mut store = Store::new(&engine, State::default());
    store.call_hook(sync_call_hook);
    let inst = linker
        .instantiate(&mut store, &component)
        .expect("instantiate");

    let export = inst
        .get_typed_func::<(&[u8],), (WasmStr,)>(&mut store, "list8-to-str")
        .expect("looking up `list8-to-str`");

    let message = String::from("hello, world!");
    let res = export.call(&mut store, (message.as_bytes(),))?.0;
    let result = res.to_str(&store)?;
    assert_eq!(&message, &result);

    // There are two wasm calls for the `list8-to-str` call and the guest realloc call for the list
    // argument.
    let s = store.into_data();
    assert_eq!(s.calls_into_host, 0);
    assert_eq!(s.returns_from_host, 0);
    assert_eq!(s.calls_into_wasm, 2);
    assert_eq!(s.returns_from_wasm, 2);

    Ok(())
}

// Call a guest function that also defines a post-return.
#[test]
fn call_func_with_post_return() -> Result<()> {
    let wat = r#"
        (component
            (core module $m
                (func (export "roundtrip"))
                (func (export "post-return"))
            )
            (core instance $i (instantiate $m))

            (func (export "export")
                (canon lift
                    (core func $i "roundtrip")
                    (post-return (func $i "post-return"))
                )
            )
        )"#;

    let engine = Engine::default();
    let component = Component::new(&engine, wat)?;
    let linker = Linker::<State>::new(&engine);
    let mut store = Store::new(&engine, State::default());
    store.call_hook(sync_call_hook);
    let inst = linker
        .instantiate(&mut store, &component)
        .expect("instantiate");

    let export = inst
        .get_typed_func::<(), ()>(&mut store, "export")
        .expect("looking up `export`");

    export.call(&mut store, ())?;

    // There are no host calls in this example, but the post-return does increment the count of
    // wasm calls by 1, putting the total number of wasm calls at 2.
    let s = store.into_data();
    assert_eq!(s.calls_into_host, 0);
    assert_eq!(s.returns_from_host, 0);
    assert_eq!(s.calls_into_wasm, 2);
    assert_eq!(s.returns_from_wasm, 2);

    Ok(())
}

// Create an async Func, call it directly:
#[tokio::test]
async fn call_wrapped_async_func() -> Result<()> {
    let wat = r#"
        (component
            (import "f" (func $f))

            (core func $f_lower
                (canon lower (func $f))
            )
            (core module $m
                (import "" "" (func $f))

                (func $export
                    (call $f)
                )

                (export "export" (func $export))
            )
            (core instance $i (instantiate $m
                (with "" (instance
                    (export "" (func $f_lower))
                ))
            ))
            (func (export "export")
                (canon lift
                    (core func $i "export")
                )
            )
        )
    "#;

    let engine = Engine::default();

    let component = Component::new(&engine, wat)?;

    let mut linker = Linker::<State>::new(&engine);
    linker
        .root()
        .func_wrap_async("f", |_, _: ()| Box::new(async { Ok(()) }))?;

    let mut store = Store::new(&engine, State::default());
    store.call_hook(sync_call_hook);

    let inst = linker
        .instantiate_async(&mut store, &component)
        .await
        .expect("instantiate");

    let export = inst
        .get_typed_func::<(), ()>(&mut store, "export")
        .expect("looking up `export`");

    export.call_async(&mut store, ()).await?;

    let s = store.into_data();
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    Ok(())
}

#[test]
fn trapping() -> Result<()> {
    const TRAP_IN_F: i32 = 0;
    const TRAP_NEXT_CALL_HOST: i32 = 1;
    const TRAP_NEXT_RETURN_HOST: i32 = 2;
    const TRAP_NEXT_CALL_WASM: i32 = 3;
    const TRAP_NEXT_RETURN_WASM: i32 = 4;
    const DO_NOTHING: i32 = 5;

    let engine = Engine::default();

    let mut linker = Linker::<State>::new(&engine);

    linker
        .root()
        .func_wrap("f", |mut store: _, (action,): (i32,)| -> Result<()> {
            assert_eq!(store.data().context.last(), Some(&Context::Host));
            assert_eq!(store.data().calls_into_host, store.data().calls_into_wasm);

            match action {
                TRAP_IN_F => bail!("trapping in f"),
                TRAP_NEXT_CALL_HOST => store.data_mut().trap_next_call_host = true,
                TRAP_NEXT_RETURN_HOST => store.data_mut().trap_next_return_host = true,
                TRAP_NEXT_CALL_WASM => store.data_mut().trap_next_call_wasm = true,
                TRAP_NEXT_RETURN_WASM => store.data_mut().trap_next_return_wasm = true,
                _ => {} // Do nothing
            }

            Ok(())
        })?;

    let wat = r#"
        (component
            (import "f" (func $f (param "action" s32)))

            (core func $f_lower
                (canon lower (func $f))
            )
            (core module $m
                (import "" "" (func $f (param i32)))

                (func $export (param i32)
                    (call $f (local.get 0))
                )

                (export "export" (func $export))
            )
            (core instance $i (instantiate $m
                (with "" (instance
                    (export "" (func $f_lower))
                ))
            ))
            (func (export "export") (param "action" s32)
                (canon lift
                    (core func $i "export")
                )
            )
        )
    "#;

    let component = Component::new(&engine, wat)?;

    let run = |action: i32, again: bool| -> (State, Option<wasmtime::Error>) {
        let mut store = Store::new(&engine, State::default());
        store.call_hook(sync_call_hook);
        let inst = linker
            .instantiate(&mut store, &component)
            .expect("instantiate");

        let export = inst
            .get_typed_func::<(i32,), ()>(&mut store, "export")
            .expect("looking up `export`");

        let mut r = export.call(&mut store, (action,));
        if r.is_ok() && again {
            r = export.call(&mut store, (action,));
        }
        (store.into_data(), r.err())
    };

    let (s, e) = run(DO_NOTHING, false);
    assert!(e.is_none());
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    let (s, e) = run(DO_NOTHING, true);
    assert!(e.is_none());
    assert_eq!(s.calls_into_host, 2);
    assert_eq!(s.returns_from_host, 2);
    assert_eq!(s.calls_into_wasm, 2);
    assert_eq!(s.returns_from_wasm, 2);

    let (s, e) = run(TRAP_IN_F, false);
    assert!(format!("{:?}", e.unwrap()).contains("trapping in f"));
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    // // trap in next call to host. No calls after the bit is set, so this trap shouldn't happen
    let (s, e) = run(TRAP_NEXT_CALL_HOST, false);
    assert!(e.is_none());
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    // trap in next call to host. call again, so the second call into host traps:
    let (s, e) = run(TRAP_NEXT_CALL_HOST, true);
    println!("{:?}", e.as_ref().unwrap());
    assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on CallingHost"));
    assert_eq!(s.calls_into_host, 2);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 2);
    assert_eq!(s.returns_from_wasm, 2);

    // trap in the return from host. should trap right away, without a second call
    let (s, e) = run(TRAP_NEXT_RETURN_HOST, false);
    assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on ReturningFromHost"));
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    // trap in next call to wasm. No calls after the bit is set, so this trap shouldn't happen:
    let (s, e) = run(TRAP_NEXT_CALL_WASM, false);
    assert!(e.is_none());
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    // trap in next call to wasm. call again, so the second call into wasm traps:
    let (s, e) = run(TRAP_NEXT_CALL_WASM, true);
    assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on CallingWasm"));
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 2);
    assert_eq!(s.returns_from_wasm, 1);

    // trap in the return from wasm. should trap right away, without a second call
    let (s, e) = run(TRAP_NEXT_RETURN_WASM, false);
    assert!(format!("{:?}", e.unwrap()).contains("call_hook: trapping on ReturningFromWasm"));
    assert_eq!(s.calls_into_host, 1);
    assert_eq!(s.returns_from_host, 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 1);

    Ok(())
}

#[tokio::test]
async fn timeout_async_hook() -> Result<()> {
    struct HandlerR;

    #[async_trait::async_trait]
    impl CallHookHandler<State> for HandlerR {
        async fn handle_call_event(
            &self,
            mut ctx: StoreContextMut<'_, State>,
            ch: CallHook,
        ) -> Result<()> {
            let obj = ctx.data_mut();
            if obj.calls_into_host > 200 {
                bail!("timeout");
            }

            match ch {
                CallHook::CallingHost => obj.calls_into_host += 1,
                CallHook::CallingWasm => obj.calls_into_wasm += 1,
                CallHook::ReturningFromHost => obj.returns_from_host += 1,
                CallHook::ReturningFromWasm => obj.returns_from_wasm += 1,
            }

            Ok(())
        }
    }

    let wat = r#"
        (component
            (import "f" (func $f))

            (core func $f_lower
                (canon lower (func $f))
            )
            (core module $m
                (import "" "" (func $f))

                (func $export
                    (loop $start
                        (call $f)
                        (br $start))
                )

                (export "export" (func $export))
            )
            (core instance $i (instantiate $m
                (with "" (instance
                    (export "" (func $f_lower))
                ))
            ))
            (func (export "export")
                (canon lift
                    (core func $i "export")
                )
            )
        )
    "#;

    let engine = Engine::default();

    let component = Component::new(&engine, wat)?;

    let mut linker = Linker::<State>::new(&engine);
    linker
        .root()
        .func_wrap_async("f", |_, _: ()| Box::new(async { Ok(()) }))?;

    let mut store = Store::new(&engine, State::default());
    store.call_hook_async(HandlerR {});

    let inst = linker
        .instantiate_async(&mut store, &component)
        .await
        .expect("instantiate");

    let export = inst
        .get_typed_func::<(), ()>(&mut store, "export")
        .expect("looking up `export`");

    let r = export.call_async(&mut store, ()).await;
    assert!(format!("{:?}", r.unwrap_err()).contains("timeout"));

    let s = store.into_data();
    assert!(s.calls_into_host > 1);
    assert!(s.returns_from_host > 1);
    assert_eq!(s.calls_into_wasm, 1);
    assert_eq!(s.returns_from_wasm, 0);

    Ok(())
}

#[tokio::test]
async fn drop_suspended_async_hook() -> Result<()> {
    struct Handler;

    #[async_trait::async_trait]
    impl CallHookHandler<u32> for Handler {
        async fn handle_call_event(
            &self,
            mut ctx: StoreContextMut<'_, u32>,
            _ch: CallHook,
        ) -> Result<()> {
            let state = ctx.data_mut();
            assert_eq!(*state, 0);
            *state += 1;
            let _dec = Decrement(state);

            // Simulate some sort of event which takes a number of yields
            for _ in 0..500 {
                tokio::task::yield_now().await;
            }
            Ok(())
        }
    }

    let wat = r#"
        (component
            (import "f" (func $f))

            (core func $f_lower
                (canon lower (func $f))
            )
            (core module $m
                (import "" "" (func $f))

                (func $export
                    (call $f)
                )

                (export "export" (func $export))
            )
            (core instance $i (instantiate $m
                (with "" (instance
                    (export "" (func $f_lower))
                ))
            ))
            (func (export "export")
                (canon lift
                    (core func $i "export")
                )
            )
        )
    "#;

    let engine = Engine::default();

    let component = Component::new(&engine, wat)?;

    let mut linker = Linker::<u32>::new(&engine);
    linker.root().func_wrap_async("f", |mut store, _: ()| {
        Box::new(async move {
            let state = store.data_mut();
            assert_eq!(*state, 0);
            *state += 1;
            let _dec = Decrement(state);
            for _ in 0.. {
                tokio::task::yield_now().await;
            }
            Ok(())
        })
    })?;

    let mut store = Store::new(&engine, 0);
    store.call_hook_async(Handler);

    let inst = linker
        .instantiate_async(&mut store, &component)
        .await
        .expect("instantiate");

    let export = inst
        .get_typed_func::<(), ()>(&mut store, "export")
        .expect("looking up `export`");

    // Test that if we drop in the middle of an async hook that everything
    // is alright.
    PollNTimes {
        future: Box::pin(export.call_async(&mut store, ())),
        times: 200,
    }
    .await;
    assert_eq!(*store.data(), 0); // double-check user dtors ran

    return Ok(());

    // A helper struct to poll an inner `future` N `times` and then resolve.
    // This is used above to test that when futures are dropped while they're
    // pending everything works and is cleaned up on the Wasmtime side of
    // things.
    struct PollNTimes<F> {
        future: F,
        times: u32,
    }

    impl<F: Future + Unpin> Future for PollNTimes<F>
    where
        F::Output: std::fmt::Debug,
    {
        type Output = ();
        fn poll(mut self: Pin<&mut Self>, task: &mut task::Context<'_>) -> Poll<()> {
            for i in 0..self.times {
                match Pin::new(&mut self.future).poll(task) {
                    Poll::Ready(v) => panic!("future should not be ready at {i}; result is {v:?}"),
                    Poll::Pending => {}
                }
            }

            Poll::Ready(())
        }
    }

    // helper struct to decrement a counter on drop
    struct Decrement<'a>(&'a mut u32);

    impl Drop for Decrement<'_> {
        fn drop(&mut self) {
            *self.0 -= 1;
        }
    }
}