Wednesday, July 20, 2016

WebAssembly Hello World!

Photo by isipeoria (license)
Having done so much browser development in the past I have been watching WebAssembly closely. This past weekend I finally got some time to read through the current documents and mess around with various projects including WAVM. In the process after discovering no one seems to have bothered to create a Hello World! program, so I did.

WebAssembly currently has two formats, a binary format and an editable AST form.  (They are not final and there is even talk of going with something other than the AST form for the official text mode.)  Given that wasm AST is readable one thing I have watched for has been someone posting a Hello World! program as that provides a rich entry point as it doesn't require that you figure out how to compile any C code into wasm to see what it would look like. (I have seen examples that show off adding two numbers, but Hello World being such a classic I figured someone would eventually make it.)  Given the intertwined history of Emscripten with WebAssembly it wasn't a surprise when reading through the WAVM source I discovered that it had exposed Emscripten intrinsics so programs compiled using Emscripten could be run on WAVM.

A short while after finding the Emscripten intrinsics I had a working WebAssembly Hello World! program. The wasm ATS isn't exactly made for programming (typically you will compile to it) and no doubt this example will be improved upon and might even break as WebAssembly improves and changes the spec, but it brings the barrier for playing with WebAssembly down a little bit.  Enjoy!

To run the program using WAVM save it locally to a file called helloworld.wast and execute it with the following command:
$ ./bin/wavm helloworld.wast

And for the inevitable comment that points out how much smaller it could be, here it is without comments, spaces, a local variable, return value and all of the other bits that make the program more useful as example code, but is "so much better" at only 6 lines.

And while you can't run this hello world on it, if you are just looking to explore what can be coded in wast you can play around with WebAssembly on the WebAssembly playground which was recently created by Jan Wolski. If you want to try going from a c source file all the way to the browser check this WebAssembly end to end how to document.

Popular Posts