wasmer 3.0.0-alpha

High-performance WebAssembly runtime
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
#[cfg(feature = "sys")]
mod sys {
    use anyhow::Result;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use wasmer::FunctionEnv;
    use wasmer::*;

    #[test]
    fn func_ref_passed_and_returned() -> Result<()> {
        let mut store = Store::default();
        let wat = r#"(module
    (import "env" "func_ref_identity" (func (param funcref) (result funcref)))
    (type $ret_i32_ty (func (result i32)))
    (table $table (export "table") 2 2 funcref)

    (func (export "run") (param) (result funcref)
          (call 0 (ref.null func)))
    (func (export "call_set_value") (param $fr funcref) (result i32)
          (table.set $table (i32.const 0) (local.get $fr))
          (call_indirect $table (type $ret_i32_ty) (i32.const 0)))
)"#;
        let module = Module::new(&store, wat)?;
        #[derive(Clone, Debug)]
        pub struct Env(Arc<AtomicBool>);
        let env = Env(Arc::new(AtomicBool::new(false)));
        let env = FunctionEnv::new(&mut store, env);
        let imports = imports! {
            "env" => {
                "func_ref_identity" => Function::new(&mut store, &env, FunctionType::new([Type::FuncRef], [Type::FuncRef]), |_env: FunctionEnvMut<Env>, values: &[Value]| -> Result<Vec<_>, _> {
                    Ok(vec![values[0].clone()])
                })
            },
        };

        let instance = Instance::new(&mut store, &module, &imports)?;

        let f: &Function = instance.exports.get_function("run")?;
        let results = f.call(&mut store, &[]).unwrap();
        if let Value::FuncRef(fr) = &results[0] {
            assert!(fr.is_none());
        } else {
            panic!("funcref not found!");
        }

        let func_to_call =
            Function::new_native(&mut store, &env, |mut env: FunctionEnvMut<Env>| -> i32 {
                env.data_mut().0.store(true, Ordering::SeqCst);
                343
            });
        let call_set_value: &Function = instance.exports.get_function("call_set_value")?;
        let results: Box<[Value]> =
            call_set_value.call(&mut store, &[Value::FuncRef(Some(func_to_call))])?;
        assert!(env
            .as_mut(&mut store.as_store_mut())
            .0
            .load(Ordering::SeqCst));
        assert_eq!(&*results, &[Value::I32(343)]);

        Ok(())
    }

    #[test]
    fn func_ref_passed_and_called() -> Result<()> {
        let mut store = Store::default();
        let wat = r#"(module
    (func $func_ref_call (import "env" "func_ref_call") (param funcref) (result i32))
    (type $ret_i32_ty (func (result i32)))
    (table $table (export "table") 2 2 funcref)

    (func $product (param $x i32) (param $y i32) (result i32)
          (i32.mul (local.get $x) (local.get $y)))
    ;; TODO: figure out exactly why this statement is needed
    (elem declare func $product)
    (func (export "call_set_value") (param $fr funcref) (result i32)
          (table.set $table (i32.const 0) (local.get $fr))
          (call_indirect $table (type $ret_i32_ty) (i32.const 0)))
    (func (export "call_func") (param $fr funcref) (result i32)
          (call $func_ref_call (local.get $fr)))
    (func (export "call_host_func_with_wasm_func") (result i32)
          (call $func_ref_call (ref.func $product)))
)"#;
        let module = Module::new(&store, wat)?;
        let env = FunctionEnv::new(&mut store, ());
        fn func_ref_call(
            mut env: FunctionEnvMut<()>,
            values: &[Value],
        ) -> Result<Vec<Value>, RuntimeError> {
            // TODO: look into `Box<[Value]>` being returned breakage
            let f = values[0].unwrap_funcref().as_ref().unwrap();
            let f: TypedFunction<(i32, i32), i32> = f.native(&mut env)?;
            Ok(vec![Value::I32(f.call(&mut env, 7, 9)?)])
        }

        let imports = imports! {
            "env" => {
                "func_ref_call" => Function::new(
                    &mut store,
                    &env,
                    FunctionType::new([Type::FuncRef], [Type::I32]),
                    func_ref_call
                ),
                // "func_ref_call_native" => Function::new_native(&mut store, &env, |_env: FunctionEnvMut<()>, f: Function| -> Result<i32, RuntimeError> {
                //     let f: TypedFunction::<(i32, i32), i32> = f.native(&mut store)?;
                //     f.call(&mut store, 7, 9)
                // })
            },
        };

        let instance = Instance::new(&mut store, &module, &imports)?;
        {
            fn sum(_env: FunctionEnvMut<()>, a: i32, b: i32) -> i32 {
                a + b
            }
            let sum_func = Function::new_native(&mut store, &env, sum);

            let call_func: &Function = instance.exports.get_function("call_func")?;
            let result = call_func.call(&mut store, &[Value::FuncRef(Some(sum_func))])?;
            assert_eq!(result[0].unwrap_i32(), 16);
        }

        {
            let f: TypedFunction<(), i32> = instance
                .exports
                .get_typed_function(&mut store, "call_host_func_with_wasm_func")?;
            let result = f.call(&mut store)?;
            assert_eq!(result, 63);
        }

        Ok(())
    }

    /*
        #[test]
        fn extern_ref_passed_and_returned() -> Result<()> {
            let mut store = Store::default();
            let env = FunctionEnv::new(&mut store, ());
            let wat = r#"(module
        (func $extern_ref_identity (import "env" "extern_ref_identity") (param externref) (result externref))
        (func $extern_ref_identity_native (import "env" "extern_ref_identity_native") (param externref) (result externref))
        (func $get_new_extern_ref (import "env" "get_new_extern_ref") (result externref))
        (func $get_new_extern_ref_native (import "env" "get_new_extern_ref_native") (result externref))

        (func (export "run") (param) (result externref)
              (call $extern_ref_identity (ref.null extern)))
        (func (export "run_native") (param) (result externref)
              (call $extern_ref_identity_native (ref.null extern)))
        (func (export "get_hashmap") (param) (result externref)
              (call $get_new_extern_ref))
        (func (export "get_hashmap_native") (param) (result externref)
              (call $get_new_extern_ref_native))
    )"#;
            let module = Module::new(&store, wat)?;
            let env = FunctionEnv::new(&mut store, ());
            let imports = imports! {
                "env" => {
                    "extern_ref_identity" => Function::new(&mut store, &env, FunctionType::new([Type::ExternRef], [Type::ExternRef]), |_env, values| -> Result<Vec<_>, _> {
                        Ok(vec![values[0].clone()])
                    }),
                    "extern_ref_identity_native" => Function::new_native(&mut store, &env, |_env: FunctionEnvMut<()>, er: ExternRef| -> ExternRef {
                        er
                    }),
                    "get_new_extern_ref" => Function::new(&mut store, &env, FunctionType::new([], [Type::ExternRef]), |_env, _| -> Result<Vec<_>, _> {
                        let inner =
                            [("hello".to_string(), "world".to_string()),
                             ("color".to_string(), "orange".to_string())]
                            .iter()
                            .cloned()
                            .collect::<HashMap<String, String>>();
                        let new_extern_ref = ExternRef::new(&mut env, inner);
                        Ok(vec![Value::ExternRef(new_extern_ref)])
                    }),
                    "get_new_extern_ref_native" => Function::new_native(&mut store, &env,|_env| -> ExternRef {
                        let inner =
                            [("hello".to_string(), "world".to_string()),
                             ("color".to_string(), "orange".to_string())]
                            .iter()
                            .cloned()
                            .collect::<HashMap<String, String>>();
                        ExternRef::new(inner)
                    })
                },
            };

            let instance = Instance::new(&module, &imports)?;
            for run in &["run", "run_native"] {
                let f: &Function = instance.exports.get_function(run)?;
                let results = f.call(&[]).unwrap();
                if let Value::ExternRef(er) = &results[0] {
                    assert!(er.is_null());
                } else {
                    panic!("result is not an extern ref!");
                }

                let f: TypedFunction<(), ExternRef> = instance.exports.get_typed_function(run)?;
                let result: ExternRef = f.call()?;
                assert!(result.is_null());
            }

            for get_hashmap in &["get_hashmap", "get_hashmap_native"] {
                let f: &Function = instance.exports.get_function(get_hashmap)?;
                let results = f.call(&[]).unwrap();
                if let Value::ExternRef(er) = &results[0] {
                    let inner: &HashMap<String, String> = er.downcast().unwrap();
                    assert_eq!(inner["hello"], "world");
                    assert_eq!(inner["color"], "orange");
                } else {
                    panic!("result is not an extern ref!");
                }

                let f: TypedFunction<(), ExternRef> =
                    instance.exports.get_typed_function(get_hashmap)?;

                let result: ExternRef = f.call()?;
                let inner: &HashMap<String, String> = result.downcast().unwrap();
                assert_eq!(inner["hello"], "world");
                assert_eq!(inner["color"], "orange");
            }

            Ok(())
        }

    #[test]
        // TODO(reftypes): reenable this test
        #[ignore]
        fn extern_ref_ref_counting_basic() -> Result<()> {
            let mut store = Store::default();
            let wat = r#"(module
        (func (export "drop") (param $er externref) (result)
              (drop (local.get $er)))
    )"#;
            let module = Module::new(&store, wat)?;
            let instance = Instance::new(&module, &imports! {})?;
            let f: TypedFunction<ExternRef, ()> = instance.exports.get_typed_function("drop")?;

            let er = ExternRef::new(3u32);
            f.call(er.clone())?;

            assert_eq!(er.downcast::<u32>().unwrap(), &3);
            assert_eq!(er.strong_count(), 1);

            Ok(())
        }

        #[test]
        fn refs_in_globals() -> Result<()> {
            let mut store = Store::default();
            let wat = r#"(module
        (global $er_global (export "er_global") (mut externref) (ref.null extern))
        (global $fr_global (export "fr_global") (mut funcref) (ref.null func))
        (global $fr_immutable_global (export "fr_immutable_global") funcref (ref.func $hello))
        (func $hello (param) (result i32)
              (i32.const 73))
    )"#;
            let module = Module::new(&store, wat)?;
            let instance = Instance::new(&module, &imports! {})?;
            {
                let er_global: &Global = instance.exports.get_global("er_global")?;

                if let Value::ExternRef(er) = er_global.get() {
                    assert!(er.is_null());
                } else {
                    panic!("Did not find extern ref in the global");
                }

                er_global.set(Value::ExternRef(ExternRef::new(3u32)))?;

                if let Value::ExternRef(er) = er_global.get() {
                    assert_eq!(er.downcast::<u32>().unwrap(), &3);
                    assert_eq!(er.strong_count(), 1);
                } else {
                    panic!("Did not find extern ref in the global");
                }
            }

            {
                let fr_global: &Global = instance.exports.get_global("fr_immutable_global")?;

                if let Value::FuncRef(Some(f)) = fr_global.get() {
                    let native_func: TypedFunction<(), u32> = f.native()?;
                    assert_eq!(native_func.call()?, 73);
                } else {
                    panic!("Did not find non-null func ref in the global");
                }
            }

            {
                let fr_global: &Global = instance.exports.get_global("fr_global")?;

                if let Value::FuncRef(None) = fr_global.get() {
                } else {
                    panic!("Did not find a null func ref in the global");
                }

                let f = Function::new_native(&store, |arg1: i32, arg2: i32| -> i32 { arg1 + arg2 });

                fr_global.set(Value::FuncRef(Some(f)))?;

                if let Value::FuncRef(Some(f)) = fr_global.get() {
                    let native: TypedFunction<(i32, i32), i32> = f.native()?;
                    assert_eq!(native.call(5, 7)?, 12);
                } else {
                    panic!("Did not find extern ref in the global");
                }
            }

            Ok(())
        }

        #[test]
        fn extern_ref_ref_counting_table_basic() -> Result<()> {
            let mut store = Store::default();
            let wat = r#"(module
        (global $global (export "global") (mut externref) (ref.null extern))
        (table $table (export "table") 4 4 externref)
        (func $insert (param $er externref) (param $idx i32)
               (table.set $table (local.get $idx) (local.get $er)))
        (func $intermediate (param $er externref) (param $idx i32)
              (call $insert (local.get $er) (local.get $idx)))
        (func $insert_into_table (export "insert_into_table") (param $er externref) (param $idx i32) (result externref)
              (call $intermediate (local.get $er) (local.get $idx))
              (local.get $er))
    )"#;
            let module = Module::new(&store, wat)?;
            let instance = Instance::new(&module, &imports! {})?;

            let f: TypedFunction<(ExternRef, i32), ExternRef> =
                instance.exports.get_typed_function("insert_into_table")?;

            let er = ExternRef::new(3usize);

            let er = f.call(er, 1)?;
            assert_eq!(er.strong_count(), 2);

            let table: &Table = instance.exports.get_table("table")?;

            {
                let er2 = table.get(1).unwrap().externref().unwrap();
                assert_eq!(er2.strong_count(), 3);
            }

            assert_eq!(er.strong_count(), 2);
            table.set(1, Value::ExternRef(ExternRef::null()))?;

            assert_eq!(er.strong_count(), 1);

            Ok(())
        }

        #[test]
        // TODO(reftypes): reenable this test
        #[ignore]
        fn extern_ref_ref_counting_global_basic() -> Result<()> {
            let mut store = Store::default();
            let wat = r#"(module
        (global $global (export "global") (mut externref) (ref.null extern))
        (func $get_from_global (export "get_from_global") (result externref)
              (drop (global.get $global))
              (global.get $global))
    )"#;
            let module = Module::new(&store, wat)?;
            let instance = Instance::new(&module, &imports! {})?;

            let global: &Global = instance.exports.get_global("global")?;
            {
                let er = ExternRef::new(3usize);
                global.set(Value::ExternRef(er.clone()))?;
                assert_eq!(er.strong_count(), 2);
            }
            let get_from_global: TypedFunction<(), ExternRef> =
                instance.exports.get_typed_function("get_from_global")?;

            let er = get_from_global.call()?;
            assert_eq!(er.strong_count(), 2);
            global.set(Value::ExternRef(ExternRef::null()))?;
            assert_eq!(er.strong_count(), 1);

            Ok(())
        }

        #[test]
        // TODO(reftypes): reenable this test
        #[ignore]
        fn extern_ref_ref_counting_traps() -> Result<()> {
            let mut store = Store::default();
            let wat = r#"(module
        (func $pass_er (export "pass_extern_ref") (param externref)
              (local.get 0)
              (unreachable))
    )"#;
            let module = Module::new(&store, wat)?;
            let instance = Instance::new(&module, &imports! {})?;

            let pass_extern_ref: TypedFunction<ExternRef, ()> =
                instance.exports.get_typed_function("pass_extern_ref")?;

            let er = ExternRef::new(3usize);
            assert_eq!(er.strong_count(), 1);

            let result = pass_extern_ref.call(er.clone());
            assert!(result.is_err());
            assert_eq!(er.strong_count(), 1);

            Ok(())
        }

        #[test]
        fn extern_ref_ref_counting_table_instructions() -> Result<()> {
            let mut store = Store::default();
            let wat = r#"(module
        (table $table1 (export "table1") 2 12 externref)
        (table $table2 (export "table2") 6 12 externref)
        (func $grow_table_with_ref (export "grow_table_with_ref") (param $er externref) (param $size i32) (result i32)
              (table.grow $table1 (local.get $er) (local.get $size)))
        (func $fill_table_with_ref (export "fill_table_with_ref") (param $er externref) (param $start i32) (param $end i32)
              (table.fill $table1 (local.get $start) (local.get $er) (local.get $end)))
        (func $copy_into_table2 (export "copy_into_table2")
              (table.copy $table2 $table1 (i32.const 0) (i32.const 0) (i32.const 4)))
    )"#;
            let module = Module::new(&store, wat)?;
            let instance = Instance::new(&module, &imports! {})?;

            let grow_table_with_ref: TypedFunction<(ExternRef, i32), i32> =
                instance.exports.get_typed_function("grow_table_with_ref")?;
            let fill_table_with_ref: TypedFunction<(ExternRef, i32, i32), ()> =
                instance.exports.get_typed_function("fill_table_with_ref")?;
            let copy_into_table2: TypedFunction<(), ()> =
                instance.exports.get_typed_function("copy_into_table2")?;
            let table1: &Table = instance.exports.get_table("table1")?;
            let table2: &Table = instance.exports.get_table("table2")?;

            let er1 = ExternRef::new(3usize);
            let er2 = ExternRef::new(5usize);
            let er3 = ExternRef::new(7usize);
            {
                let result = grow_table_with_ref.call(er1.clone(), 0)?;
                assert_eq!(result, 2);
                assert_eq!(er1.strong_count(), 1);

                let result = grow_table_with_ref.call(er1.clone(), 10_000)?;
                assert_eq!(result, -1);
                assert_eq!(er1.strong_count(), 1);

                let result = grow_table_with_ref.call(er1.clone(), 8)?;
                assert_eq!(result, 2);
                assert_eq!(er1.strong_count(), 9);

                for i in 2..10 {
                    let e = table1.get(i).unwrap().unwrap_externref();
                    assert_eq!(*e.downcast::<usize>().unwrap(), 3);
                    assert_eq!(&e, &er1);
                }
                assert_eq!(er1.strong_count(), 9);
            }

            {
                fill_table_with_ref.call(er2.clone(), 0, 2)?;
                assert_eq!(er2.strong_count(), 3);
            }

            {
                table2.set(0, Value::ExternRef(er3.clone()))?;
                table2.set(1, Value::ExternRef(er3.clone()))?;
                table2.set(2, Value::ExternRef(er3.clone()))?;
                table2.set(3, Value::ExternRef(er3.clone()))?;
                table2.set(4, Value::ExternRef(er3.clone()))?;
                assert_eq!(er3.strong_count(), 6);
            }

            {
                copy_into_table2.call()?;
                assert_eq!(er3.strong_count(), 2);
                assert_eq!(er2.strong_count(), 5);
                assert_eq!(er1.strong_count(), 11);
                for i in 1..5 {
                    let e = table2.get(i).unwrap().unwrap_externref();
                    let value = e.downcast::<usize>().unwrap();
                    match i {
                        0 | 1 => assert_eq!(*value, 5),
                        4 => assert_eq!(*value, 7),
                        _ => assert_eq!(*value, 3),
                    }
                }
            }

            {
                for i in 0..table1.size() {
                    table1.set(i, Value::ExternRef(ExternRef::null()))?;
                }
                for i in 0..table2.size() {
                    table2.set(i, Value::ExternRef(ExternRef::null()))?;
                }
            }

            assert_eq!(er1.strong_count(), 1);
            assert_eq!(er2.strong_count(), 1);
            assert_eq!(er3.strong_count(), 1);

            Ok(())
        }
        */
}