阿里云开发者社区,千万开发者的选择
阿里云开发者社区,百万精品技术内容、千节免费系统课程、丰富的体验场景、活跃的社群活动、行业专家分享交流,欢迎点击【阅读原文】加入我们。
阿里妹导读
本文是一篇WebAssembly的入门文章,从理论介绍到实战方面有全面的讲述。
历史进程
WebAssembly 是什么
工具链
LLVM
实战
安装 LLVM
brew install llvmbrew link --force llvmllc --version# 确保 wasm32 在 targets 中
编译 C
int add(int a, int b) {return a * a + b;}
第一步:我们先采用 clang 将 C 文件编译到 LLVM IR
clang \--target=wasm32 \-emit-llvm-c \-S \add.c
我们会得到一个 add.ll 文件,这就是 LLVM IR,大概长下面这个样子
; ModuleID = 'add.c'source_filename = "add.c"target datalayout = "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20"target triple = "wasm32"; Function Attrs: noinline nounwind optnonedefine hidden i32 @add(i32 noundef %0, i32 noundef %1) #0 {%3 = alloca i32, align 4%4 = alloca i32, align 4store i32 %0, ptr %3, align 4store i32 %1, ptr %4, align 4%5 = load i32, ptr %3, align 4%6 = load i32, ptr %3, align 4%7 = mul nsw i32 %5, %6%8 = load i32, ptr %4, align 4%9 = add nsw i32 %7, %8ret i32 %9}attributes #0 = { noinline nounwind optnone "frame-pointer"="none" "min-legal-vector-width"="0" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="generic" }!llvm.module.flags = !{!0}!llvm.ident = !{!1}!0 = !{i32 1, !"wchar_size", i32 4}!1 = !{!"Homebrew clang version 15.0.7"}
llc -march=wasm32 -filetype=obj add.ll
我们会得到一个 add.o,它是一个含有这个 C 文件所有编译代码的 wasm 模块,不过现在还不能够运行它。这个模块中其实是一个可以被阅读的格式,我们可以用一些工具来解析它,比如 WebAssembly Binary Toolkit(wabt)
brew install wabtwasm-objdump -x add.o
大概长这样
add.o: file format wasm 0x1Section Details:Type[1]:- type[0] (i32, i32) -> i32Import[2]:- memory[0] pages: initial=0 <- env.__linear_memory- global[0] i32 mutable=1 <- env.__stack_pointerFunction[1]:- func[0] sig=0 <add>Code[1]:- func[0] size=44 <add>Custom:- name: "linking"- symbol table [count=2]- 0: F <add> func=0 [ binding=global vis=hidden ]- 1: G <env.__stack_pointer> global=0 [ undefined binding=global vis=default ]Custom:- name: "reloc.CODE"- relocations for section: 3 (Code) [1]- R_WASM_GLOBAL_INDEX_LEB offset=0x000006(file=0x00005e) symbol=1 <env.__stack_pointer>Custom:- name: "producers"
这里定义了 add 方法,不过除此以外还包含了很多其他信息,比如 imports,这其实是要被下一个环节(linking)所消费的
wasm-ld \--no-entry \--export-all \-o add.wasm \add.o
这里我们会得到最终的 wasm 产物,add.wasm
<script type="module">async function init() {const { instance } = await WebAssembly.instantiateStreaming(fetch ("./add.wasm"))console.log(instance.exports.add(4, 1));};init(); // ouput 17(4 * 4 + 1)</script>
上面的过程略显复杂,这是为了让我们更好的理解这其中发生了什么。其实我们可以一步完成这些动作
clang \-target=wasm32 \-notstdlib \ # 不要连接 C 标准库\ # Wl(Wasm linker), 这表示将 --no-entry 作为参数传给 Wasm linker\-o add.wasm \add.c
我们可以通过 wasm2wat(上面提到的 wabt 中已经包含了) 工具来看下 wasm 的 S expression 格式长什么样
(module(type (;0;) (func))(type (;1;) (func (param i32 i32) (result i32)))(func $__wasm_call_ctors (type 0))(func $add (type 1) (param i32 i32) (result i32)(local i32)global.get $__stack_pointeri32.const 16i32.sublocal.tee 2local.get 0i32.store offset=12local.get 2local.get 1i32.store offset=8local.get 2i32.load offset=12local.get 2i32.load offset=12i32.mullocal.get 2i32.load offset=8i32.add)(memory (;0;) 2)(global $__stack_pointer (mut i32) (i32.const 66560))(global (;1;) i32 (i32.const 1024))(global (;2;) i32 (i32.const 1024))(global (;3;) i32 (i32.const 1024))(global (;4;) i32 (i32.const 66560))(global (;5;) i32 (i32.const 131072))(global (;6;) i32 (i32.const 0))(global (;7;) i32 (i32.const 1))(export "memory" (memory 0))(export "__wasm_call_ctors" (func $__wasm_call_ctors))(export "add" (func $add))(export "__dso_handle" (global 1))(export "__data_end" (global 2))(export "__global_base" (global 3))(export "__heap_base" (global 4))(export "__heap_end" (global 5))(export "__memory_base" (global 6))(export "__table_base" (global 7)))
S expression 看起来舒服多了,我们可以看到一些信息,有方法定义,有本地变量,有导出语句。不过你可能会发现就一个非常简单的 add 方法,居然需要这么多行指令,这是因为我们还没有开启优化。
大小优化
clang \--target=wasm32 \-O3 \-flto \ # 连接优化\-Wl,--no-entry \-Wl,--export-all \-Wl,--lto-O3 \ # 连接器连接优化add.wasm \add.c
在这里其实 link-time optimization(连接优化)并没有起到作用,因为我们这里只有一个文件,在文件多的时候,这会起到很好的优化效果。
(module(type (;0;) (func))(type (;1;) (func (param i32 i32) (result i32)))(func (;0;) (type 0)nop)(func (;1;) (type 1) (param i32 i32) (result i32)local.get 0local.get 0i32.mullocal.get 1i32.add)(memory (;0;) 2)(global (;0;) i32 (i32.const 1024))(global (;1;) i32 (i32.const 1024))(global (;2;) i32 (i32.const 1024))(global (;3;) i32 (i32.const 66560))(global (;4;) i32 (i32.const 131072))(global (;5;) i32 (i32.const 0))(global (;6;) i32 (i32.const 1))(export "memory" (memory 0))(export "__wasm_call_ctors" (func 0))(export "add" (func 1))(export "__dso_handle" (global 0))(export "__data_end" (global 1))(export "__global_base" (global 2))(export "__heap_base" (global 3))(export "__heap_end" (global 4))(export "__memory_base" (global 5))(export "__table_base" (global 6)))
POSIX syscall
内存模型
我们可以看到,先是栈,后面是堆,并且栈从高位往低位生长,堆从低位往高位生长。之所以这样设计是因为 wasm 的内存是可以在运行时动态增长的。
内存分配器
值传递
// js sideconst uints = [1, 2, 3, 4];// 在 wasm heap 中分配 bytes 长度的内存, 返回一个指针const ptr = this.module._malloc(uints.length)// 从 wasm heap 中截取这段堆内存const heapBytes = new Uint8Array(this.module.HEAPU8.buffer, ptr, uints.length)// 在这段堆内存上填充这段 8-bit 无符号整数heapBytes.set(uints)// emscripten 中的内部方法ccall(ptr, heapBytes.length);// c sidevoid c_fn(uint8_t *buf, size_t buf_len) {}
我们可以看到 js 的值在传入 wasm 的时候,先需要在共享内存中申请一块内存,然后将 js 的值序列化成 TypedArray 写入这块内存,wasm 中根据指针取到这块内存之后,再反序列化成自己想要的数据结构。
总结
阿里云开发者社区,千万开发者的选择
阿里云开发者社区,百万精品技术内容、千节免费系统课程、丰富的体验场景、活跃的社群活动、行业专家分享交流,欢迎点击【阅读原文】加入我们。
文章引用微信公众号"阿里开发者",如有侵权,请联系管理员删除!