WASM(WebAssenbly) 大概指的是一种二进制代码(网页汇编语言)。

WAT(WebAssembly Text Format) 大概指的是一种和WASM很像的,但是对人而言可以是可以读出来的代码。


Part1 WAT 的语法

Understanding WebAssembly text format - WebAssembly | MDN (mozilla.org)

类型

  • i32,i64,f32,f64
  • v128
  • externref 外部引用类型

栈机制

  • 一般操作有一个栈,每次往栈 push 或者 pop 来实现读取。

memory

  • 可以定义一个内存,一个 page 默认 64KB
  • 内存以 byte 为单位来存值,JavaScript 可以根据偏移量和长度来获取值。

tables

  • 类似 map 的一个东西,把 i32 的地址映射到一个东西,这个东西比如可以是一个函数(如果定义了 funcref 的类型)。
  • 大概可以理解成引用数组?
  • 利用 call_indirect ,增加类型检查,调用栈顶元素所对应函数。

  • table和内存是可以公用的,利用这个可以实现两个程序之间的链接。


Instructions — WebAssembly 2.0 (Draft 2022-09-01)

应该看几段代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
(module
(type (;0;) (func (param i32 i32 i32)))
(func (;0;) (type 0) (param i32 i32 i32)
(local i32 i32)
local.get 1
i32.const 0
i32.gt_s
if ;; label = @1
loop ;; label = @2
local.get 0
local.get 3
i32.const 2
i32.shl
i32.add
local.tee 4
local.get 4
i32.load
local.get 2
i32.add
i32.const 26
i32.rem_s
i32.store
local.get 3
i32.const 1
i32.add
local.tee 3
local.get 1
i32.ne
br_if 0 (;@2;)
end
end)
(func (;1;) (type 0) (param i32 i32 i32)
(local i32 i32)
local.get 1
i32.const 0
i32.gt_s
if ;; label = @1
loop ;; label = @2
local.get 0
local.get 3
i32.const 2
i32.shl
i32.add
local.tee 4
local.get 4
i32.load
local.get 2
i32.sub
i32.const 26
i32.rem_s
i32.store
local.get 3
i32.const 1
i32.add
local.tee 3
local.get 1
i32.ne
br_if 0 (;@2;)
end
end)
(memory (;0;) 256 256)
(export "memory" (memory 0))
(export "caesarEncrypt" (func 0))
(export "caesarDecrypt" (func 1))
(data (;0;) (i32.const 1536) "\a0\06P"))

Part2 WASMTIME

Part3 WASI接口