Skip to content

Commit

Permalink
Export Emscripten runtime for the Web (#509)
Browse files Browse the repository at this point in the history
Some runtime environments look like Node.js, but are not Node.js which
confuses Emscripten loader code. I'm talking about JavaScript bundlers
that are used for Web and Electron apps. These things make the code
believe that it can use "require()" for importing and "module.exports"
for exporting things, and expect this be the case.

However, Emscripten believes that it is smarter, detects that it's not
running in Node.js environment, and just uses "Module" for exports.
This breaks bundler's expectation and various Emscripten runtime
functions (like "allocate()") end up not being exported, resulting in
weird TypeErrors when WasmThemis code tries calling them.

This can be avoided by exporting whatever Emscripten wants to export
in Node.js style via "module.exports". We can insert this code into
generated file by using "--pre-js" flag of emcc.

Since now we have more than one file for Emscripten compilation,
move them all into a subdirectory to keep the root directory tidy.
  • Loading branch information
ilammy committed Jul 25, 2019
1 parent 44041ea commit 0b388f7
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/wrappers/themis/wasm/emscripten/pre.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Manually export Emscripten runtime functions for weird environments that
// look like Node.js, but aren't Node.js (e.g., Electron apps or output of
// web bundlers like webpack or Browserify)
module.exports = Module;
9 changes: 6 additions & 3 deletions src/wrappers/themis/wasm/wasmthemis.mk
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@ WASM_PATH = src/wrappers/themis/wasm
WASM_SRC += $(WASM_PATH)/package.json
WASM_SRC += $(wildcard $(WASM_PATH)/src/*.js)

WASM_RUNTIME = $(abspath $(WASM_PATH)/runtime_exports.json)
WASM_RUNTIME = $(abspath $(WASM_PATH)/emscripten/runtime_exports.json)
WASM_PRE_JS = $(abspath $(WASM_PATH)/emscripten/pre.js)

$(BIN_PATH)/libthemis.js: LDFLAGS += -s EXTRA_EXPORTED_RUNTIME_METHODS=@$(WASM_RUNTIME) -s RESERVED_FUNCTION_POINTERS=1
$(BIN_PATH)/libthemis.js: LDFLAGS += -s EXTRA_EXPORTED_RUNTIME_METHODS=@$(WASM_RUNTIME)
$(BIN_PATH)/libthemis.js: LDFLAGS += -s RESERVED_FUNCTION_POINTERS=1
$(BIN_PATH)/libthemis.js: LDFLAGS += --pre-js $(WASM_PRE_JS)

$(BIN_PATH)/libthemis.js: CMD = $(CC) -o $@ $(filter %.o %a, $^) $(LDFLAGS)

$(BIN_PATH)/libthemis.js: $(THEMIS_STATIC) $(WASM_RUNTIME)
$(BIN_PATH)/libthemis.js: $(THEMIS_STATIC) $(WASM_RUNTIME) $(WASM_PRE_JS)
@mkdir -p $(@D)
@echo -n "link "
@$(BUILD_CMD)
Expand Down

0 comments on commit 0b388f7

Please sign in to comment.