How to create a minimal wasm file with Rust?

I can create a fairly minimal (203 bytes) wasm file from the following C code by running emcc -O3 -s WASM=1 -s SIDE_MODULE=1 -o sum.wasm sum.c

 #include <emscripten/emscripten.h> int EMSCRIPTEN_KEEPALIVE sum(int a, int b) { return a + b; } 

Disassembled output:

 (module (type $0 (func (param i32 i32) (result i32))) ... trim 9 lines ... (export "_sum" (func $0)) (func $0 (type $0) (param $var$0 i32) (param $var$1 i32) (result i32) (i32.add (get_local $var$1) (get_local $var$0) ) ) ... trim 17 lines ... ) 

But given the following rust code

 pub fn main() {} #[no_mangle] pub extern fn sum(a: i32, b: i32) -> i32 { a + b } 

I don't seem to be doing anything like that.

rustc -O --target=wasm32-unknown-emscripten sum.rs works, but it gives me an 85 kg wasm file and a 128k js file.

I tried exporting EMMAKEN_CFLAGS='-s WASM=1 -s SIDE_MODULE=1' , but this gives me some warnings like

The input file "/tmp/.../rust.metadata.bin" exists, but is not an LLVM bitcode file suitable for Emscripten. Perhaps accidentally mix your own embedded object files with Emscripten?

and then failed to bind.

My version is Rust 1.22.0-nightly (c6884b12d 2017-09-30) and my version is emcc 1.37.21 .

What am I doing wrong?

+5
source share
1 answer

For the purpose of wasm32-unknown-emscripten you use the Emscripten-based compiler toolchain. Emscripten adds quite a lot of additional runtime code to the wasm module, as well as additional JavaScript code to integrate with this at runtime. As you also noticed, Emscripten can compile with the SIDE_MODULE option, which removes the vast majority of this runtime code. This reduces the size of the binary, but means you have to handle things like complex type bindings.

More recently (November 2017), a new wasm32-unknown-unknown target was added to Rust that uses the LLVM backend (rather than Emscripten and its fastcomp fork), which leads to a minimal result.

This target can be used as described in the configuration guide :

 rustup update rustup target add wasm32-unknown-unknown --toolchain nightly rustc +nightly --target wasm32-unknown-unknown -O hello.rs 
+3
source

Source: https://habr.com/ru/post/1272478/


All Articles