wasm-metering icon indicating copy to clipboard operation
wasm-metering copied to clipboard

Recovering the stack for intra-call persistence

Open void4 opened this issue 7 years ago • 1 comments

(To be able to resume a function where it ran out of gas or create a merkle tree of intermediate execution states, as in truebit)

I've tried to serialize a Wasm instance but then noticed the stack isn't accessible:

const fs = require('fs')
const metering = require('.')
const sha256 = require('simple-sha256')
const wasm = fs.readFileSync('example/main.wasm')

const persist = require('wasm-persist')
meteredWasm = persist.prepare(meteredWasm)

var meteredWasm = metering.meterWASM(wasm, {
  meterType: 'i32'
})
console.log(wasm)
console.log(meteredWasm)
//console.log(meteredWasm.keys())

const mod = WebAssembly.Module(meteredWasm)

let gasUsed = 0
var step = 100000
var limit = 10000000
var total = 0

instance = WebAssembly.Instance(mod, {
	  'metering': {
		'usegas': (gas) => {
		  gasUsed += gas
		  if (total > limit) {
		    throw new Error('out of gas!')
		  } else if (gasUsed>=step) {
		  	state = persist.hibernate(instance)
		  	var hsh = sha256.sync(JSON.stringify({instance,state}))
			console.log("step", hsh)
			total += gasUsed
			gasUsed = 0
		  }
		}
	  }
})
var result = instance.exports.fac(1000)
//console.log(sha256.sync(JSON.stringify(result)))
console.log(`result:${result}, gas used ${total * 1e-9}s`) // result:720, gas used 0.4177

My knowledge of Wasm semantics is limited. Would it be possible to inject the following:

  1. keep a stack depth counter along with the instruction cost
  2. grow the memory by this depth
  3. store the entire stack in memory
  4. call the metering function as usual
  5. within the metering function, serialize the stack and the rest of the module that can already be accessed (code, memory etc.)
  6. recover the stack from memory
  7. continue execution

One problem with this might be that the value type on the stack is not known, I'm not sure if a module that uses two times i32.store instead of one i64.store is still valid.

Also, this doesn't save the call frames either.

Edit: I'm reading through the specs again now, one crucial limitation is:

The fact that the nested instruction sequence instr∗ must have type []→[t?] implies that it cannot access operands that have been pushed on the stack before the block was entered. This may be generalized in future versions of WebAssembly.

This seems to imply that the stack must have been mirrored to memory before any block or function call in order to recover it within it, which will be quite inefficient.

void4 avatar Jul 04 '18 17:07 void4

After starting to modify warpy (an RPython Wasm JIT interpreter), I switched to extending https://github.com/xtuc/webassemblyjs/ instead. Here's a preview:

https://www.youtube.com/watch?v=_5vN9NKeLXE

:)

void4 avatar Aug 09 '18 20:08 void4