Webassembly still fragile

As I am preparing the website for my upcoming book on equity derivatives models, I played around with webassembly to run some C++ code from your web browser…

December 5, 2017

As I am preparing the website for my upcoming book on equity derivatives models, I played around with webassembly to run some C++ code from your web browser. In order to do that, I rely on emscripten, which seems to be the most advanced toolkit to generate webassembly code.

I did not expect the webassembly toolchain to be so fragile. At first I had trouble using some specific C code (not so complicated) from javascript through emscripten: there are multiple ways to do it. Many approaches failed and I did not manage to go very far to find out the root cause for the failure. One approach worked, the one described in the Google tutorial for Webassembly.

I still have some strange issues I could not fully resolve: if I compile with the flag -O3 then the generated wasm and javascript do not work, and without the flag, I have no issues. Here is the kind of error stack I get from the browser with -O3 (or -O2):

RuntimeError: integer result unrepresentable
    at wasm-function[42]:46
    at wasm-function[43]:251
    at wasm-function[44]:215
    at wasm-function[45]:38
    at wasm-function[138]:23
    at dynCall_iiiiiddd_1 (eval at makeDynCaller (http://localhost:9000/fractal.js:1:42548),
And looking at the line 42548 of the generated javascript file is not very helpful. It is actually quite amazing that emscripten generates so many lines of javascript (this is partly because I rely on the C++ standard library I suppose). I managed to find a workaround thanks to a google search. I have to add the option -s “BINARYEN_TRAP_MODE=‘clamp’" to em++. I wonder what the root cause exactly is, maybe the faddeeva library tries to convert infinity or NaN to an int? I could not find it.

In any case, when it works, it works well and it is definitely possible to call some C++ libraries from javascript, which is still something quite amazing.