SwadicalRag / wasm2lua

wasm2lua: converting WASM into Lua
MIT License
190 stars 10 forks source link

Zero initialize locals #33

Closed Rerumu closed 2 years ago

Rerumu commented 2 years ago

WebAssembly expects locals (but not parameters) in a function body to be initialized to 0 by default. wasm2lua currently initializes them as nil which causes code that relies on this invariant to break.

This minimal example is valid and should return 0, but returns nil instead.

SwadicalRag commented 2 years ago

Thank you

SwadicalRag commented 2 years ago

Actually, hold on, this should have already worked prior to the fix since wasm2lua checks if variables are accessed before they are initialised and auto-initialises them to 0

SwadicalRag commented 2 years ago

wasm2lua@0.8.8 image

wasm2lua@0.8.9 image

SwadicalRag commented 2 years ago

I'll rollback the code. 0.8.9 will initialise all non-parametric locals to 0, but it does so at the cost of increased code size.

This is what happens when I try and go edit code I haven't touched in years

Rerumu commented 2 years ago

That is interesting; the issue is an uninitialized variable for sure but possibly because of a buggy heuristic instead. The repro I provided is the same one I used when I found the same issue on a similar project, my bad for not testing if that one specifically caused it.

This is the larger repro I have confirmed the bug in. With this initialization code:

local function put_char(_) end

local module = require('translated')

module.imports.env = {put_char = put_char}
module.exports.main(0, 0)
SwadicalRag commented 2 years ago

I'll have a poke around and see what I find