Wasm Builders

Paul Nwoko
Paul Nwoko

Posted on • Updated on

Compiling C/C++ to WebAssembly and running it outside the Web browser.

In this tutorial I will be compiling C programs to WASI and executing the compiled WebAssembly module using wasmtime runtime outside of the Web browser.

Setting up the environment

Find steps on how to setup your development environment in my previous post here.

Compiling to .WASM

The wasi-sdk provides a clang which is configured to target WASI

WASI stands for WebAssembly System Interface. It's an API designed by the Wasmtime project that provides access to several operating-system-like features, including files and filesystems, Berkeley sockets, clocks, and random numbers.

Use the command to generate a WebAssembly file in pure binary format:

~/wasi-sdk-12.0/bin/clang {path to c source}demo.c --sysroot ~/wasi-sdk-12.0/share/wasi-sysroot/ -o {destination path for .wasm file}demo.wasm
Enter fullscreen mode Exit fullscreen mode

Here specify the directory path to the source and destination file

~/wasi-sdk-12.0/bin/clang /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/demo.c --sysroot ~/wasi-sdk-12.0/share/wasi-sysroot/ -o /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/demo.wasm
Enter fullscreen mode Exit fullscreen mode

After running the above comand a .wasm file was generated in the /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/ directory as show below
image

Executing in wasmtime runtime

the program requires a command line argument so let's parse it as shown below:

create a file test and write hello world to it. the C application will use this file
echo hello world > test.txt

wasmtime demo.wasm test.txt /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/somewhere.txt
Enter fullscreen mode Exit fullscreen mode

result:

error opening input test.txt: Capabilities insufficient
Enter fullscreen mode Exit fullscreen mode

The program is attempting to access a file by the name of test.txt, but was denied access. That is the sandboxing in action.
The outcome is show in the screenshot below.
image

To give access to the file system, specify the directory path to the .wasm file to run, .txt file to read from and the .txt file to create and write to accordingly.

wasmtime --dir=. --dir=/home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/ demo.wasm test.txt /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/somewhere.txt
Enter fullscreen mode Exit fullscreen mode

To read to content of the somewhere.txt

cat /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/somewhere.txt
Enter fullscreen mode Exit fullscreen mode

Result:

hello world
Enter fullscreen mode Exit fullscreen mode

The screenshot is shown below:

image

The directory now contains all the generated files (.wasm, and .txt files) as shown below

image

Further reading:

WASI documentation

Discussion (0)