Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Last active February 5, 2023 14:07
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jedisct1/8ce91d746e09c913ee0d0f33b0ba7981 to your computer and use it in GitHub Desktop.
Save jedisct1/8ce91d746e09c913ee0d0f33b0ba7981 to your computer and use it in GitHub Desktop.
Run WebAssembly files like standard executable files on Linux, using Lucet

The following instructions require Lucet, although they can be easily adapted to other WebAssembly runtimes.

Save the following script as /opt/lucet/bin/lucet-ondemand:

#! /bin/sh

wasm_file="$1"
if [ -n "$wasm_file" ]; then
  if od -x "$wasm_file" | head -n1 | grep -Fq '0000000 6100 6d73 0001'; then
    so_file="$(mktemp).so"
    trap "rm -f $so_file" EXIT
    "/opt/lucet/bin/lucetc-wasi" -o "$so_file" "$wasm_file" && \
      exec "/opt/lucet/bin/lucet-wasi" "$so_file"
  else
    echo "${wasm_file} is not a webassembly file" >&2
  fi
else
  echo "Usage: $0 <wasm file>" >&2
fi

Make it executable:

chmod +x /opt/lucet/bin/lucet-ondemand

Register WebAssembly files to be handled by that script:

sudo bash -c 'echo ":wasm:M::\x00\x61\x73\x6d\x01\x00::/opt/lucet/bin/lucet-ondemand:" > /proc/sys/fs/binfmt_misc/register'

Now, WebAssembly files can be executed directly (make sure that they have the executable bit set, though):

/tmp/example_hello.wasm

Hello world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment