File: interrupt.rs

package info (click to toggle)
rust-wasmtime 26.0.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 48,504 kB
  • sloc: ansic: 4,003; sh: 561; javascript: 542; cpp: 254; asm: 175; ml: 96; makefile: 55
file content (34 lines) | stat: -rw-r--r-- 1,239 bytes parent folder | download | duplicates (3)
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
//! Small example of how you can interrupt the execution of a wasm module to
//! ensure that it doesn't run for too long.

// You can execute this example with `cargo run --example interrupt`

use wasmtime::*;

fn main() -> Result<()> {
    // Enable epoch interruption code via `Config` which means that code will
    // get interrupted when `Engine::increment_epoch` happens.
    let engine = Engine::new(Config::new().epoch_interruption(true))?;
    let mut store = Store::new(&engine, ());
    store.set_epoch_deadline(1);

    // Compile and instantiate a small example with an infinite loop.
    let module = Module::from_file(&engine, "examples/interrupt.wat")?;
    let instance = Instance::new(&mut store, &module, &[])?;
    let run = instance.get_typed_func::<(), ()>(&mut store, "run")?;

    // Spin up a thread to send us an interrupt in a second
    std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_secs(1));
        println!("Interrupting!");
        engine.increment_epoch();
    });

    println!("Entering infinite loop ...");
    let err = run.call(&mut store, ()).unwrap_err();

    println!("trap received...");
    assert_eq!(err.downcast::<Trap>()?, Trap::Interrupt);

    Ok(())
}