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
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
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
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
result:
error opening input test.txt: Capabilities insufficient
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.
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
To read to content of the somewhere.txt
cat /home/ngp/outreachy/enarx/demo/'c-cpp to wasm outside browser'/somewhere.txt
Result:
hello world
The screenshot is shown below:
The directory now contains all the generated files (.wasm, and .txt files) as shown below
Top comments (0)