forked from bytecodealliance/wasmtime-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc_test.go
367 lines (312 loc) · 9.73 KB
/
doc_test.go
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package wasmtime
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"runtime"
)
// An example of instantiating a small wasm module which imports functionality
// from the host, then calling into wasm which calls back into the host.
func Example() {
// Almost all operations in wasmtime require a contextual `store`
// argument to share, so create that first
store := NewStore(NewEngine())
// Compiling modules requires WebAssembly binary input, but the wasmtime
// package also supports converting the WebAssembly text format to the
// binary format.
wasm, err := Wat2Wasm(`
(module
(import "" "hello" (func $hello))
(func (export "run")
(call $hello))
)
`)
check(err)
// Once we have our binary `wasm` we can compile that into a `*Module`
// which represents compiled JIT code.
module, err := NewModule(store.Engine, wasm)
check(err)
// Our `hello.wat` file imports one item, so we create that function
// here.
item := WrapFunc(store, func() {
fmt.Println("Hello from Go!")
})
// Next up we instantiate a module which is where we link in all our
// imports. We've got one import so we pass that in here.
instance, err := NewInstance(store, module, []AsExtern{item})
check(err)
// After we've instantiated we can lookup our `run` function and call
// it.
run := instance.GetFunc(store, "run")
_, err = run.Call(store)
check(err)
// Output: Hello from Go!
}
const GcdWat = `
(module
(func $gcd (param i32 i32) (result i32)
(local i32)
block ;; label = @1
block ;; label = @2
local.get 0
br_if 0 (;@2;)
local.get 1
local.set 2
br 1 (;@1;)
end
loop ;; label = @2
local.get 1
local.get 0
local.tee 2
i32.rem_u
local.set 0
local.get 2
local.set 1
local.get 0
br_if 0 (;@2;)
end
end
local.get 2
)
(export "gcd" (func $gcd))
)
`
// An example of a wasm module which calculates the GCD of two numbers
func Example_gcd() {
store := NewStore(NewEngine())
wasm, err := Wat2Wasm(GcdWat)
check(err)
module, err := NewModule(store.Engine, wasm)
check(err)
instance, err := NewInstance(store, module, []AsExtern{})
check(err)
run := instance.GetFunc(store, "gcd")
result, err := run.Call(store, 6, 27)
check(err)
fmt.Printf("gcd(6, 27) = %d\n", result.(int32))
// Output: gcd(6, 27) = 3
}
// An example of working with the Memory type to read/write wasm memory.
func Example_memory() {
// Create our `Store` context and then compile a module and create an
// instance from the compiled module all in one go.
store := NewStore(NewEngine())
wasm, err := Wat2Wasm(`
(module
(memory (export "memory") 2 3)
(func (export "size") (result i32) (memory.size))
(func (export "load") (param i32) (result i32)
(i32.load8_s (local.get 0))
)
(func (export "store") (param i32 i32)
(i32.store8 (local.get 0) (local.get 1))
)
(data (i32.const 0x1000) "\01\02\03\04")
)
`)
check(err)
module, err := NewModule(store.Engine, wasm)
check(err)
instance, err := NewInstance(store, module, []AsExtern{})
check(err)
// Load up our exports from the instance
memory := instance.GetExport(store, "memory").Memory()
sizeFn := instance.GetFunc(store, "size")
loadFn := instance.GetFunc(store, "load")
storeFn := instance.GetFunc(store, "store")
// some helper functions we'll use below
call32 := func(f *Func, args ...interface{}) int32 {
ret, err := f.Call(store, args...)
check(err)
return ret.(int32)
}
call := func(f *Func, args ...interface{}) {
_, err := f.Call(store, args...)
check(err)
}
assertTraps := func(f *Func, args ...interface{}) {
_, err := f.Call(store, args...)
_, ok := err.(*Trap)
if !ok {
panic("expected a trap")
}
}
// Check the initial memory sizes/contents
assert(memory.Size(store) == 2)
assert(memory.DataSize(store) == 0x20000)
buf := memory.UnsafeData(store)
assert(buf[0] == 0)
assert(buf[0x1000] == 1)
assert(buf[0x1003] == 4)
assert(call32(sizeFn) == 2)
assert(call32(loadFn, 0) == 0)
assert(call32(loadFn, 0x1000) == 1)
assert(call32(loadFn, 0x1003) == 4)
assert(call32(loadFn, 0x1ffff) == 0)
assertTraps(loadFn, 0x20000)
// We can mutate memory as well
buf[0x1003] = 5
call(storeFn, 0x1002, 6)
assertTraps(storeFn, 0x20000, 0)
assert(buf[0x1002] == 6)
assert(buf[0x1003] == 5)
assert(call32(loadFn, 0x1002) == 6)
assert(call32(loadFn, 0x1003) == 5)
// And like wasm instructions, we can grow memory
_, err = memory.Grow(store, 1)
assert(err == nil)
assert(memory.Size(store) == 3)
assert(memory.DataSize(store) == 0x30000)
assert(call32(loadFn, 0x20000) == 0)
call(storeFn, 0x20000, 0)
assertTraps(loadFn, 0x30000)
assertTraps(storeFn, 0x30000, 0)
// Memory can fail to grow
_, err = memory.Grow(store, 1)
assert(err != nil)
_, err = memory.Grow(store, 0)
assert(err == nil)
// Ensure that `memory` lives long enough to cover all our usages of
// using its internal buffer we read from `UnsafeData()`
runtime.KeepAlive(memory)
// Finally we can also create standalone memories to get imported by
// wasm modules too.
memorytype := NewMemoryType(5, true, 5)
memory2, err := NewMemory(store, memorytype)
assert(err == nil)
assert(memory2.Size(store) == 5)
_, err = memory2.Grow(store, 1)
assert(err != nil)
_, err = memory2.Grow(store, 0)
assert(err == nil)
// Output:
}
// An example of enabling the multi-value feature of WebAssembly and
// interacting with multi-value functions.
func Example_multi() {
// Configure our `Store`, but be sure to use a `Config` that enables the
// wasm multi-value feature since it's not stable yet.
config := NewConfig()
config.SetWasmMultiValue(true)
store := NewStore(NewEngineWithConfig(config))
wasm, err := Wat2Wasm(`
(module
(func $f (import "" "f") (param i32 i64) (result i64 i32))
(func $g (export "g") (param i32 i64) (result i64 i32)
(call $f (local.get 0) (local.get 1))
)
(func $round_trip_many
(export "round_trip_many")
(param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64)
(result i64 i64 i64 i64 i64 i64 i64 i64 i64 i64)
local.get 0
local.get 1
local.get 2
local.get 3
local.get 4
local.get 5
local.get 6
local.get 7
local.get 8
local.get 9)
)
`)
check(err)
module, err := NewModule(store.Engine, wasm)
check(err)
callback := WrapFunc(store, func(a int32, b int64) (int64, int32) {
return b + 1, a + 1
})
instance, err := NewInstance(store, module, []AsExtern{callback})
check(err)
g := instance.GetFunc(store, "g")
results, err := g.Call(store, 1, 3)
check(err)
arr := results.([]Val)
a := arr[0].I64()
b := arr[1].I32()
fmt.Printf("> %d %d\n", a, b)
assert(a == 4)
assert(b == 2)
roundTripMany := instance.GetFunc(store, "round_trip_many")
results, err = roundTripMany.Call(store, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
check(err)
arr = results.([]Val)
for i := 0; i < len(arr); i++ {
fmt.Printf(" %d", arr[i].Get())
assert(arr[i].I64() == int64(i))
}
// Output: > 4 2
// 0 1 2 3 4 5 6 7 8 9
}
const TextWat = `
(module
;; Import the required fd_write WASI function which will write the given io vectors to stdout
;; The function signature for fd_write is:
;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
(import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory 1)
(export "memory" (memory 0))
;; Write 'hello world\n' to memory at an offset of 8 bytes
;; Note the trailing newline which is required for the text to appear
(data (i32.const 8) "hello world\n")
(func $main (export "_start")
;; Creating a new io vector within linear memory
(i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
(i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string
(call $fd_write
(i32.const 1) ;; file_descriptor - 1 for stdout
(i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
(i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
(i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
)
drop ;; Discard the number of bytes written from the top of the stack
)
)
`
// An example of linking WASI to the runtime in order to interact with the system.
// It uses the WAT code from https://github.com/bytecodealliance/wasmtime/blob/main/docs/WASI-tutorial.md#web-assembly-text-example
func Example_wasi() {
dir, err := ioutil.TempDir("", "out")
check(err)
defer os.RemoveAll(dir)
stdoutPath := filepath.Join(dir, "stdout")
engine := NewEngine()
// Create our module
wasm, err := Wat2Wasm(TextWat)
check(err)
module, err := NewModule(engine, wasm)
check(err)
// Create a linker with WASI functions defined within it
linker := NewLinker(engine)
err = linker.DefineWasi()
check(err)
// Configure WASI imports to write stdout into a file, and then create
// a `Store` using this wasi configuration.
wasiConfig := NewWasiConfig()
wasiConfig.SetStdoutFile(stdoutPath)
store := NewStore(engine)
store.SetWasi(wasiConfig)
instance, err := linker.Instantiate(store, module)
check(err)
// Run the function
nom := instance.GetFunc(store, "_start")
_, err = nom.Call(store)
check(err)
// Print WASM stdout
out, err := ioutil.ReadFile(stdoutPath)
check(err)
fmt.Print(string(out))
// Output: hello world
}
func check(e error) {
if e != nil {
panic(e)
}
}
func assert(b bool) {
if !b {
panic("assertion failed")
}
}