Allocate Dynamic Memory in WebAssembly with Malloc

InstructorGuy Bedford

Share this video with your friends

Send Tweet

We demonstrate how to build a WebAssembly module that depends on malloc, linking in a pre-built malloc implementation at runtime, using a JS binding trick to handle the circular reference between the two WebAssembly modules. We then optimize the load process to ensure we are fetching these modules in parallel.

Malloc implementation: https://github.com/guybedford/wasm-stdlib-hack/blob/master/dist/memory.wasm

WASM Fiddle: https://wasdk.github.io/WasmFiddle/?1feerp

Demo Repo: https://github.com/guybedford/wasm-intro

dustin71728
~ 7 years ago

When I try this example, the browser complains following error:

loader.js:7 Uncaught (in promise) CompileError: WasmCompile: Wasm decoding failed: expected magic word 00 61 73 6d, found 0a 0a 0a 0a @+0
    at fetch.then.then.bytes (http://127.0.0.1:8080/lesson%206/loader.js:7:32)
    at <anonymous>
fetch.then.then.bytes	@	loader.js:7

Browser compiles memory.wasm and fail

loader.js:

function fetchAndInstantiate(url, imports) {
  return fetch(url)
    .then(res => {
      if(res.ok) return res.arrayBuffer()
      throw new Error(`Unable to fetch Web Assembly files url.`)
    })
    .then(bytes => WebAssembly.compile(bytes))
    .then(modules => WebAssembly.instantiate(modules, imports || {}))
    .then(instance => instance.exports)
}

let wasmMalloc, wasmFree
fetchAndInstantiate('./program.wasm', {
  env: {
    malloc: len => wasmMalloc(len),
    free: addr => wasmFree(addr)
  }
})
.then(m => {
  fetchAndInstantiate('./memory.wasm', {
    env: {
      memory: m.memory
    }
  })
})

Browser: chrome, version 59.0.3071.86 OS: Ubuntu 16.04.2 LTS

INFINIDAT LTD
~ 6 years ago

To me it was unclear where the memory.wasm file came from, and there seems to be no source code for it.