Example of limiting a WebAssembly function's runtime using "fuel consumption".
()
| 15 | |
| 16 | // Example of limiting a WebAssembly function's runtime using "fuel consumption". |
| 17 | func ExampleConfig_fuel() { |
| 18 | config := wasmtime.NewConfig() |
| 19 | config.SetConsumeFuel(true) |
| 20 | engine := wasmtime.NewEngineWithConfig(config) |
| 21 | store := wasmtime.NewStore(engine) |
| 22 | err := store.SetFuel(10000) |
| 23 | if err != nil { |
| 24 | log.Fatal(err) |
| 25 | } |
| 26 | |
| 27 | // Compile and instantiate a small example with an infinite loop. |
| 28 | wasm, err := wasmtime.Wat2Wasm(` |
| 29 | (module |
| 30 | (func $fibonacci (param $n i32) (result i32) |
| 31 | (if |
| 32 | (i32.lt_s (local.get $n) (i32.const 2)) |
| 33 | (then (return (local.get $n))) |
| 34 | ) |
| 35 | (i32.add |
| 36 | (call $fibonacci (i32.sub (local.get $n) (i32.const 1))) |
| 37 | (call $fibonacci (i32.sub (local.get $n) (i32.const 2))) |
| 38 | ) |
| 39 | ) |
| 40 | (export "fibonacci" (func $fibonacci)) |
| 41 | ) |
| 42 | `) |
| 43 | if err != nil { |
| 44 | log.Fatal(err) |
| 45 | } |
| 46 | module, err := wasmtime.NewModule(store.Engine, wasm) |
| 47 | if err != nil { |
| 48 | log.Fatal(err) |
| 49 | } |
| 50 | instance, err := wasmtime.NewInstance(store, module, []wasmtime.AsExtern{}) |
| 51 | if err != nil { |
| 52 | log.Fatal(err) |
| 53 | } |
| 54 | |
| 55 | // Invoke `fibonacci` export with higher and higher numbers until we exhaust our fuel. |
| 56 | fibonacci := instance.GetFunc(store, "fibonacci") |
| 57 | if fibonacci == nil { |
| 58 | log.Fatal("Failed to find function export `fibonacci`") |
| 59 | } |
| 60 | fuel := uint64(10000) |
| 61 | for n := 0; ; n++ { |
| 62 | err := store.SetFuel(fuel) |
| 63 | if err != nil { |
| 64 | log.Fatal(err) |
| 65 | } |
| 66 | output, err := fibonacci.Call(store, n) |
| 67 | if err != nil { |
| 68 | break |
| 69 | } |
| 70 | fuelAfter, err := store.GetFuel() |
| 71 | if err != nil { |
| 72 | log.Fatal(err) |
| 73 | } |
| 74 | fmt.Printf("fib(%d) = %d [consumed %d fuel]\n", n, output, fuel-fuelAfter) |
nothing calls this directly
no test coverage detected
searching dependent graphs…