Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of execution limits using fuel consumption #2869

Merged
merged 6 commits into from
May 4, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions examples/fuel.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//! Example of limiting a WebAssembly function's runtime using "fuel consumption".

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

use anyhow::Result;
use wasmtime::*;

fn main() -> Result<()> {
let mut config = Config::new();
config.consume_fuel(true);
let engine = Engine::new(&config)?;
let store = Store::new(&engine);
store.add_fuel(10_000)?;
let module = Module::from_file(store.engine(), "examples/fuel.wat")?;
let instance = Instance::new(&store, &module, &[])?;

// Invoke `fibonacci` export with higher and higher numbers until we exhaust our fuel.
let fibonacci = instance.get_typed_func::<i32, i32>("fibonacci")?;
for n in 1.. {
let fuel_before = store.fuel_consumed().unwrap();
let output = fibonacci.call(n)?;
let fuel_consumed = store.fuel_consumed().unwrap() - fuel_before;

println!("fib({}) = {} [consumed {} fuel]", n, output, fuel_consumed);
store.add_fuel(fuel_consumed)?;
}
Ok(())
}
36 changes: 36 additions & 0 deletions examples/fuel.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
(module
(func $fibonacci (param i32) (result i32)
(local i32)
local.get 0
i32.const 2
i32.ge_s
if (result i32) ;; label = @1
local.get 0
i32.const 1
i32.add
local.set 0
loop ;; label = @2
local.get 0
i32.const -3
i32.add
call 0
local.get 1
i32.add
local.set 1
local.get 0
i32.const -1
i32.add
local.tee 0
i32.const 2
i32.gt_s
br_if 0 (;@2;)
end
i32.const 1
else
local.get 0
end
local.get 1
i32.add
)
(export "fibonacci" (func $fibonacci))
)
alexcrichton marked this conversation as resolved.
Show resolved Hide resolved