Skip to content

dmarcos/wasm-minimal-libc

Repository files navigation

Minimal C++ and libC to WebAssembly (or WASM) template

  • No build system. Just a bash script.
  • No Emscripten.
  • Stripped down to the bare minimum. Every line of code has a purpose.

This repo is Mac only for now. Downloaded libraries, compiler and linker are Mac binaries. This repo could be adapted easily to Windows or Linux. I just don't have the bandwidth at the moment or one of those machines available.

This builds on a self-contained minimal WASM template that I recommend to look at if you want to learn how the bare WASM stack works without the additional standard / system library complexity. To use libC from WASM we need to know:

  • WebAssembly is designed to be cross-platform so there's no platform API to open a file, access the network stack, write on the standard output, environment variables...
  • WASI is an effort to create a standard system API for WASM that is platform agnostic. The official wasi-sdk includes headers and libraries to compile and link your code against.
  • In order to run WASM + WASI code we also need a platform specific implementation of the WASI API. Remember that WebAssembly and WASI are platform agnostic and the code totally portable. For the code to ultimately run on a specific platform we need to translate the WASI calls into the target platform equivalents. Here we focus on the Web as the target platform and we're using the WASI JS implementation for the browser that ships with runno.

Setup

The command below downloads a wasi-sdk release bundle that contains the WASI headers, libraries, compiler (clang) and linker (wasm-ld)

./setup.sh

Usage

Compiles and links C++ code to WASM

./build.sh

Starts a local Web server so you can run the code. Open in your browser http://localhost:8080

./run.sh

Prior work

https://github.com/michaelfranzl/clang-wasm-browser-starterpack/tree/dev/examples/11

https://medium.com/@michaelyuan_88928/running-llama2-c-in-wasmedge-15291795c470

https://stackoverflow.com/a/29694977/717508

https://github.com/taybenlor/runno

Notes

/vendor/wasi.js is built from the runno wasi js runtime by running mpm run build. There are two small modifications on 9b9dc1f3142c that I might submit upstream:

  1. The ability to pass a WebAssembly.Memory object to the runtime.
  2. The ability to pass an object with JS-defined functions that can be invoked from native code.

I included a wasi.js.original file as a references for the differences (git diff wasi.js wasi.js.original)

About

Minimal example of C++ code using libc that compiles to WASM

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

 

Packages

No packages published