banner
raye~

Raye's Journey

且趁闲身未老,尽放我、些子疏狂。
medium
tg_channel
twitter
github
email
nintendo switch
playstation
steam_profiles

Research on wasm memory access

wasm Memory Out-of-Bounds Read/Write Test#

Manually write a wasm module, the wat code is as follows:

  • Declare the need for a segment of memory space
  • Expose two functions, write memory and read memory, which are then called in the js code
(module
  ;; Declare the need to provide memory
  (import "env" "memory" (memory 1 2)) ;; Initial 1 page, maximum 2 pages

  ;; Write i32 to memory[offset]
  (func (export "writeToMemory") (param i32) (param i32)
    (i32.store
      (local.get 0)
      (local.get 1)
    )
  )

  ;; Read i32 from memory[offset]
  (func (export "readFromMemory") (param i32) (result i32)
    (i32.load
      (local.get 0)
    )
  )
)

Then compile it into a wasm module

wat2wasm memory_test.wat -o memory_test.wasm 

Write js code

const fs = require('fs');

(async () => {
  const memory = new WebAssembly.Memory({ initial: 1, maximum: 2 });

  const importObject = {
    env: {
      memory: memory
    }
  };
  // Read wasm, allocate memory
  const wasmBuffer = fs.readFileSync('./memory_test.wasm');
  const wasmModule = await WebAssembly.instantiate(wasmBuffer, importObject);

  const { writeToMemory, readFromMemory} = wasmModule.instance.exports;

  const inBoundsOffset = 65532; // Normal offset
  const outOfBoundsOffset = 70000; // Out-of-bounds offset

  // Test normal write and read
  writeToMemory(inBoundsOffset, 123456);
  console.log("Read data:", readFromMemory(inBoundsOffset));

  try {
    // 👇 Attempt to write out of bounds
    console.log("Attempting to write out of bounds");
    writeToMemory(outOfBoundsOffset, 999);
  } catch (err) {
    console.error("Out of bounds write error:", err.message);
    console.log(err);
  }

  try {
    // 👇 Attempt to read out of bounds
    console.log("Attempting to read out of bounds");
    console.log(readFromMemory(outOfBoundsOffset));
  } catch (err) {
    console.error("Out of bounds read error:", err.message);
    console.log(err);
  }
})();

The result shows that an error occurs at this time

 node main.js
Read data: 123456
Attempting to write out of bounds
Out of bounds write error: memory access out of bounds
RuntimeError: memory access out of bounds
    at wasm://wasm/488cc87e:wasm-function[0]:0x59
    at /Users/rayepeng/Documents/code/wasm-memory-test/main.js:26:5
Attempting to read out of bounds
Out of bounds read error: memory access out of bounds
RuntimeError: memory access out of bounds
    at wasm://wasm/488cc87e:wasm-function[1]:0x61
    at /Users/rayepeng/Documents/code/wasm-memory-test/main.js:35:17
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.