assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Stale Memory Reads

Open martindevans opened this issue 5 months ago • 14 comments

Question

I'm encountering an issue which might be a bug in assembly script. However I haven't managed to narrow it down to a simple reproduction program yet so I'm really just wanting to check that I'm not doing something obviously incorrect, or missing some critical thing.

The setup is a C# program which runs WASM modules written in AssemblyScript. The code is compiled with AS and then run through Binaryen to "asyncify" it. The wasm module can call "sched_yield" to trigger an async unwind and then the WASM program will be resumed one frame later. From the point of view of the running code it's one single long-lived program with time passing.

At the very start of the program it allocates a buffer like this:

let _data = heap.alloc(DATA_SIZE);
sharedmemory_set_readaddress(_data, DATA_SIZE);

On the host side this pointer is saved, and it will be written to every frame just before execution is resumed (that's how data is sent in to the WASM module). AssemblyScript code reads the values like this:

return load<i32>(_data, 52, 1); // various hardcoded offsets to certain values in the buffer

However, I'm having issues with what seems to be stale or otherwise invalid reads from that buffer in AssemblyScript. Seemingly unrelated changes to the program will cause incorrect values to be read (usually zero, when it should be something else).

Is there something fundamentally wrong with my approach here?

Other Things I've Tried

  • StaticBuffer instead of heap.alloc
  • Memory.data() instead of heap.alloc
  • Calling sharedmemory_set_readaddress every frame, just before and just after yielding (the idea was so the compiler is "aware" that the pointer might be written to at this point)

Other Possible Ideas

  • Volatile reads (doesn't seem to be a thing in AS?)
  • Maybe I need some kind of memory barrier (atomic.barrier did nothing, doesn't really seem applicable anyway)
  • Binaryen optimisations (maybe it's a binaryen issue, not an AS issue)
  • A Wasmtime bug (maybe it's a wasmtime issue, not an AS issue)

martindevans avatar Jan 18 '24 19:01 martindevans