-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
func.rs
2634 lines (2452 loc) · 102 KB
/
func.rs
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::runtime::Uninhabited;
use crate::store::{AutoAssertNoGc, StoreData, StoreOpaque, Stored};
use crate::type_registry::RegisteredType;
use crate::{
AsContext, AsContextMut, CallHook, Engine, Extern, FuncType, Instance, Module, Ref,
StoreContext, StoreContextMut, Val, ValRaw, ValType,
};
use anyhow::{bail, Context as _, Error, Result};
use std::ffi::c_void;
use std::future::Future;
use std::mem;
use std::num::NonZeroUsize;
use std::pin::Pin;
use std::ptr::{self, NonNull};
use std::sync::Arc;
use wasmtime_environ::VMSharedTypeIndex;
use wasmtime_runtime::{
ExportFunction, SendSyncPtr, StoreBox, VMArrayCallHostFuncContext, VMContext, VMFuncRef,
VMFunctionImport, VMNativeCallHostFuncContext, VMOpaqueContext,
};
/// A reference to the abstract `nofunc` heap value.
///
/// The are no instances of `(ref nofunc)`: it is an uninhabited type.
///
/// There is precisely one instance of `(ref null nofunc)`, aka `nullfuncref`:
/// the null reference.
///
/// This `NoFunc` Rust type's sole purpose is for use with [`Func::wrap`]- and
/// [`Func::typed`]-style APIs for statically typing a function as taking or
/// returning a `(ref null nofunc)` (aka `Option<NoFunc>`) which is always
/// `None`.
///
/// # Example
///
/// ```
/// # use wasmtime::*;
/// # fn _foo() -> Result<()> {
/// let mut config = Config::new();
/// config.wasm_function_references(true);
/// let engine = Engine::new(&config)?;
///
/// let module = Module::new(
/// &engine,
/// r#"
/// (module
/// (func (export "f") (param (ref null nofunc))
/// ;; If the reference is null, return.
/// local.get 0
/// ref.is_null nofunc
/// br_if 0
///
/// ;; If the reference was not null (which is impossible)
/// ;; then raise a trap.
/// unreachable
/// )
/// )
/// "#,
/// )?;
///
/// let mut store = Store::new(&engine, ());
/// let instance = Instance::new(&mut store, &module, &[])?;
/// let f = instance.get_func(&mut store, "f").unwrap();
///
/// // We can cast a `(ref null nofunc)`-taking function into a typed function that
/// // takes an `Option<NoFunc>` via the `Func::typed` method.
/// let f = f.typed::<Option<NoFunc>, ()>(&store)?;
///
/// // We can call the typed function, passing the null `nofunc` reference.
/// let result = f.call(&mut store, NoFunc::null());
///
/// // The function should not have trapped, because the reference we gave it was
/// // null (as it had to be, since `NoFunc` is uninhabited).
/// assert!(result.is_ok());
/// # Ok(())
/// # }
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct NoFunc {
_inner: Uninhabited,
}
impl NoFunc {
/// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference.
#[inline]
pub fn null() -> Option<NoFunc> {
None
}
/// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a
/// [`Ref`].
pub fn null_ref() -> Ref {
Ref::Func(None)
}
/// Get the null `(ref null nofunc)` (aka `nullfuncref`) reference as a
/// [`Val`].
pub fn null_val() -> Val {
Val::FuncRef(None)
}
}
/// A WebAssembly function which can be called.
///
/// This type typically represents an exported function from a WebAssembly
/// module instance. In this case a [`Func`] belongs to an [`Instance`] and is
/// loaded from there. A [`Func`] may also represent a host function as well in
/// some cases, too.
///
/// Functions can be called in a few different ways, either synchronous or async
/// and either typed or untyped (more on this below). Note that host functions
/// are normally inserted directly into a [`Linker`](crate::Linker) rather than
/// using this directly, but both options are available.
///
/// # `Func` and `async`
///
/// Functions from the perspective of WebAssembly are always synchronous. You
/// might have an `async` function in Rust, however, which you'd like to make
/// available from WebAssembly. Wasmtime supports asynchronously calling
/// WebAssembly through native stack switching. You can get some more
/// information about [asynchronous configs](crate::Config::async_support), but
/// from the perspective of `Func` it's important to know that whether or not
/// your [`Store`](crate::Store) is asynchronous will dictate whether you call
/// functions through [`Func::call`] or [`Func::call_async`] (or the typed
/// wrappers such as [`TypedFunc::call`] vs [`TypedFunc::call_async`]).
///
/// # To `Func::call` or to `Func::typed().call()`
///
/// There's a 2x2 matrix of methods to call [`Func`]. Invocations can either be
/// asynchronous or synchronous. They can also be statically typed or not.
/// Whether or not an invocation is asynchronous is indicated via the method
/// being `async` and [`call_async`](Func::call_async) being the entry point.
/// Otherwise for statically typed or not your options are:
///
/// * Dynamically typed - if you don't statically know the signature of the
/// function that you're calling you'll be using [`Func::call`] or
/// [`Func::call_async`]. These functions take a variable-length slice of
/// "boxed" arguments in their [`Val`] representation. Additionally the
/// results are returned as an owned slice of [`Val`]. These methods are not
/// optimized due to the dynamic type checks that must occur, in addition to
/// some dynamic allocations for where to put all the arguments. While this
/// allows you to call all possible wasm function signatures, if you're
/// looking for a speedier alternative you can also use...
///
/// * Statically typed - if you statically know the type signature of the wasm
/// function you're calling, then you'll want to use the [`Func::typed`]
/// method to acquire an instance of [`TypedFunc`]. This structure is static proof
/// that the underlying wasm function has the ascripted type, and type
/// validation is only done once up-front. The [`TypedFunc::call`] and
/// [`TypedFunc::call_async`] methods are much more efficient than [`Func::call`]
/// and [`Func::call_async`] because the type signature is statically known.
/// This eschews runtime checks as much as possible to get into wasm as fast
/// as possible.
///
/// # Examples
///
/// One way to get a `Func` is from an [`Instance`] after you've instantiated
/// it:
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// let engine = Engine::default();
/// let module = Module::new(&engine, r#"(module (func (export "foo")))"#)?;
/// let mut store = Store::new(&engine, ());
/// let instance = Instance::new(&mut store, &module, &[])?;
/// let foo = instance.get_func(&mut store, "foo").expect("export wasn't a function");
///
/// // Work with `foo` as a `Func` at this point, such as calling it
/// // dynamically...
/// match foo.call(&mut store, &[], &mut []) {
/// Ok(()) => { /* ... */ }
/// Err(trap) => {
/// panic!("execution of `foo` resulted in a wasm trap: {}", trap);
/// }
/// }
/// foo.call(&mut store, &[], &mut [])?;
///
/// // ... or we can make a static assertion about its signature and call it.
/// // Our first call here can fail if the signatures don't match, and then the
/// // second call can fail if the function traps (like the `match` above).
/// let foo = foo.typed::<(), ()>(&store)?;
/// foo.call(&mut store, ())?;
/// # Ok(())
/// # }
/// ```
///
/// You can also use the [`wrap` function](Func::wrap) to create a
/// `Func`
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// let mut store = Store::<()>::default();
///
/// // Create a custom `Func` which can execute arbitrary code inside of the
/// // closure.
/// let add = Func::wrap(&mut store, |a: i32, b: i32| -> i32 { a + b });
///
/// // Next we can hook that up to a wasm module which uses it.
/// let module = Module::new(
/// store.engine(),
/// r#"
/// (module
/// (import "" "" (func $add (param i32 i32) (result i32)))
/// (func (export "call_add_twice") (result i32)
/// i32.const 1
/// i32.const 2
/// call $add
/// i32.const 3
/// i32.const 4
/// call $add
/// i32.add))
/// "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[add.into()])?;
/// let call_add_twice = instance.get_typed_func::<(), i32>(&mut store, "call_add_twice")?;
///
/// assert_eq!(call_add_twice.call(&mut store, ())?, 10);
/// # Ok(())
/// # }
/// ```
///
/// Or you could also create an entirely dynamic `Func`!
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// let mut store = Store::<()>::default();
///
/// // Here we need to define the type signature of our `Double` function and
/// // then wrap it up in a `Func`
/// let double_type = wasmtime::FuncType::new(
/// store.engine(),
/// [wasmtime::ValType::I32].iter().cloned(),
/// [wasmtime::ValType::I32].iter().cloned(),
/// );
/// let double = Func::new(&mut store, double_type, |_, params, results| {
/// let mut value = params[0].unwrap_i32();
/// value *= 2;
/// results[0] = value.into();
/// Ok(())
/// });
///
/// let module = Module::new(
/// store.engine(),
/// r#"
/// (module
/// (import "" "" (func $double (param i32) (result i32)))
/// (func $start
/// i32.const 1
/// call $double
/// drop)
/// (start $start))
/// "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[double.into()])?;
/// // .. work with `instance` if necessary
/// # Ok(())
/// # }
/// ```
#[derive(Copy, Clone, Debug)]
#[repr(transparent)] // here for the C API
pub struct Func(Stored<FuncData>);
pub(crate) struct FuncData {
kind: FuncKind,
// A pointer to the in-store `VMFuncRef` for this function, if
// any.
//
// When a function is passed to Wasm but doesn't have a Wasm-to-native
// trampoline, we have to patch it in. But that requires mutating the
// `VMFuncRef`, and this function could be shared across
// threads. So we instead copy and pin the `VMFuncRef` into
// `StoreOpaque::func_refs`, where we can safely patch the field without
// worrying about synchronization and we hold a pointer to it here so we can
// reuse it rather than re-copy if it is passed to Wasm again.
in_store_func_ref: Option<SendSyncPtr<VMFuncRef>>,
// This is somewhat expensive to load from the `Engine` and in most
// optimized use cases (e.g. `TypedFunc`) it's not actually needed or it's
// only needed rarely. To handle that this is an optionally-contained field
// which is lazily loaded into as part of `Func::call`.
//
// Also note that this is intentionally placed behind a pointer to keep it
// small as `FuncData` instances are often inserted into a `Store`.
ty: Option<Box<FuncType>>,
}
/// The three ways that a function can be created and referenced from within a
/// store.
enum FuncKind {
/// A function already owned by the store via some other means. This is
/// used, for example, when creating a `Func` from an instance's exported
/// function. The instance's `InstanceHandle` is already owned by the store
/// and we just have some pointers into that which represent how to call the
/// function.
StoreOwned { export: ExportFunction },
/// A function is shared across possibly other stores, hence the `Arc`. This
/// variant happens when a `Linker`-defined function is instantiated within
/// a `Store` (e.g. via `Linker::get` or similar APIs). The `Arc` here
/// indicates that there's some number of other stores holding this function
/// too, so dropping this may not deallocate the underlying
/// `InstanceHandle`.
SharedHost(Arc<HostFunc>),
/// A uniquely-owned host function within a `Store`. This comes about with
/// `Func::new` or similar APIs. The `HostFunc` internally owns the
/// `InstanceHandle` and that will get dropped when this `HostFunc` itself
/// is dropped.
///
/// Note that this is intentionally placed behind a `Box` to minimize the
/// size of this enum since the most common variant for high-peformance
/// situations is `SharedHost` and `StoreOwned`, so this ideally isn't
/// larger than those two.
Host(Box<HostFunc>),
/// A reference to a `HostFunc`, but one that's "rooted" in the `Store`
/// itself.
///
/// This variant is created when an `InstancePre<T>` is instantiated in to a
/// `Store<T>`. In that situation the `InstancePre<T>` already has a list of
/// host functions that are packaged up in an `Arc`, so the `Arc<[T]>` is
/// cloned once into the `Store` to avoid each individual function requiring
/// an `Arc::clone`.
///
/// The lifetime management of this type is `unsafe` because
/// `RootedHostFunc` is a small wrapper around `NonNull<HostFunc>`. To be
/// safe this is required that the memory of the host function is pinned
/// elsewhere (e.g. the `Arc` in the `Store`).
RootedHost(RootedHostFunc),
}
macro_rules! for_each_function_signature {
($mac:ident) => {
$mac!(0);
$mac!(1 A1);
$mac!(2 A1 A2);
$mac!(3 A1 A2 A3);
$mac!(4 A1 A2 A3 A4);
$mac!(5 A1 A2 A3 A4 A5);
$mac!(6 A1 A2 A3 A4 A5 A6);
$mac!(7 A1 A2 A3 A4 A5 A6 A7);
$mac!(8 A1 A2 A3 A4 A5 A6 A7 A8);
$mac!(9 A1 A2 A3 A4 A5 A6 A7 A8 A9);
$mac!(10 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10);
$mac!(11 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11);
$mac!(12 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12);
$mac!(13 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13);
$mac!(14 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14);
$mac!(15 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15);
$mac!(16 A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12 A13 A14 A15 A16);
};
}
mod typed;
pub use typed::*;
macro_rules! generate_wrap_async_func {
($num:tt $($args:ident)*) => (paste::paste!{
/// Same as [`Func::wrap`], except the closure asynchronously produces
/// its result. For more information see the [`Func`] documentation.
///
/// # Panics
///
/// This function will panic if called with a non-asynchronous store.
#[allow(non_snake_case)]
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub fn [<wrap $num _async>]<T, $($args,)* R>(
store: impl AsContextMut<Data = T>,
func: impl for<'a> Fn(Caller<'a, T>, $($args),*) -> Box<dyn Future<Output = R> + Send + 'a> + Send + Sync + 'static,
) -> Func
where
$($args: WasmTy,)*
R: WasmRet,
{
assert!(store.as_context().async_support(), concat!("cannot use `wrap", $num, "_async` without enabling async support on the config"));
Func::wrap(store, move |mut caller: Caller<'_, T>, $($args: $args),*| {
let async_cx = caller.store.as_context_mut().0.async_cx().expect("Attempt to start async function on dying fiber");
let mut future = Pin::from(func(caller, $($args),*));
match unsafe { async_cx.block_on(future.as_mut()) } {
Ok(ret) => ret.into_fallible(),
Err(e) => R::fallible_from_error(e),
}
})
}
})
}
impl Func {
/// Creates a new `Func` with the given arguments, typically to create a
/// host-defined function to pass as an import to a module.
///
/// * `store` - the store in which to create this [`Func`], which will own
/// the return value.
///
/// * `ty` - the signature of this function, used to indicate what the
/// inputs and outputs are.
///
/// * `func` - the native code invoked whenever this `Func` will be called.
/// This closure is provided a [`Caller`] as its first argument to learn
/// information about the caller, and then it's passed a list of
/// parameters as a slice along with a mutable slice of where to write
/// results.
///
/// Note that the implementation of `func` must adhere to the `ty` signature
/// given, error or traps may occur if it does not respect the `ty`
/// signature. For example if the function type declares that it returns one
/// i32 but the `func` closures does not write anything into the results
/// slice then a trap may be generated.
///
/// Additionally note that this is quite a dynamic function since signatures
/// are not statically known. For a more performant and ergonomic `Func`
/// it's recommended to use [`Func::wrap`] if you can because with
/// statically known signatures Wasmtime can optimize the implementation
/// much more.
///
/// For more information about `Send + Sync + 'static` requirements on the
/// `func`, see [`Func::wrap`](#why-send--sync--static).
///
/// # Errors
///
/// The host-provided function here returns a
/// [`Result<()>`](anyhow::Result). If the function returns `Ok(())` then
/// that indicates that the host function completed successfully and wrote
/// the result into the `&mut [Val]` argument.
///
/// If the function returns `Err(e)`, however, then this is equivalent to
/// the host function triggering a trap for wasm. WebAssembly execution is
/// immediately halted and the original caller of [`Func::call`], for
/// example, will receive the error returned here (possibly with
/// [`WasmBacktrace`](crate::WasmBacktrace) context information attached).
///
/// For more information about errors in Wasmtime see the [`Trap`]
/// documentation.
///
/// [`Trap`]: crate::Trap
///
/// # Panics
///
/// Panics if the given function type is not associated with this store's
/// engine.
#[cfg(any(feature = "cranelift", feature = "winch"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "cranelift", feature = "winch"))))]
pub fn new<T>(
store: impl AsContextMut<Data = T>,
ty: FuncType,
func: impl Fn(Caller<'_, T>, &[Val], &mut [Val]) -> Result<()> + Send + Sync + 'static,
) -> Self {
assert!(ty.comes_from_same_engine(store.as_context().engine()));
let ty_clone = ty.clone();
unsafe {
Func::new_unchecked(store, ty, move |caller, values| {
Func::invoke_host_func_for_wasm(caller, &ty_clone, values, &func)
})
}
}
/// Creates a new [`Func`] with the given arguments, although has fewer
/// runtime checks than [`Func::new`].
///
/// This function takes a callback of a different signature than
/// [`Func::new`], instead receiving a raw pointer with a list of [`ValRaw`]
/// structures. These values have no type information associated with them
/// so it's up to the caller to provide a function that will correctly
/// interpret the list of values as those coming from the `ty` specified.
///
/// If you're calling this from Rust it's recommended to either instead use
/// [`Func::new`] or [`Func::wrap`]. The [`Func::wrap`] API, in particular,
/// is both safer and faster than this API.
///
/// # Errors
///
/// See [`Func::new`] for the behavior of returning an error from the host
/// function provided here.
///
/// # Unsafety
///
/// This function is not safe because it's not known at compile time that
/// the `func` provided correctly interprets the argument types provided to
/// it, or that the results it produces will be of the correct type.
///
/// # Panics
///
/// Panics if the given function type is not associated with this store's
/// engine.
#[cfg(any(feature = "cranelift", feature = "winch"))]
#[cfg_attr(docsrs, doc(cfg(any(feature = "cranelift", feature = "winch"))))]
pub unsafe fn new_unchecked<T>(
mut store: impl AsContextMut<Data = T>,
ty: FuncType,
func: impl Fn(Caller<'_, T>, &mut [ValRaw]) -> Result<()> + Send + Sync + 'static,
) -> Self {
assert!(ty.comes_from_same_engine(store.as_context().engine()));
let store = store.as_context_mut().0;
let host = HostFunc::new_unchecked(store.engine(), ty, func);
host.into_func(store)
}
/// Creates a new host-defined WebAssembly function which, when called,
/// will run the asynchronous computation defined by `func` to completion
/// and then return the result to WebAssembly.
///
/// This function is the asynchronous analogue of [`Func::new`] and much of
/// that documentation applies to this as well. The key difference is that
/// `func` returns a future instead of simply a `Result`. Note that the
/// returned future can close over any of the arguments, but it cannot close
/// over the state of the closure itself. It's recommended to store any
/// necessary async state in the `T` of the [`Store<T>`](crate::Store) which
/// can be accessed through [`Caller::data`] or [`Caller::data_mut`].
///
/// For more information on `Send + Sync + 'static`, see
/// [`Func::wrap`](#why-send--sync--static).
///
/// # Panics
///
/// This function will panic if `store` is not associated with an [async
/// config](crate::Config::async_support).
///
/// Panics if the given function type is not associated with this store's
/// engine.
///
/// # Errors
///
/// See [`Func::new`] for the behavior of returning an error from the host
/// function provided here.
///
/// # Examples
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// // Simulate some application-specific state as well as asynchronous
/// // functions to query that state.
/// struct MyDatabase {
/// // ...
/// }
///
/// impl MyDatabase {
/// async fn get_row_count(&self) -> u32 {
/// // ...
/// # 100
/// }
/// }
///
/// let my_database = MyDatabase {
/// // ...
/// };
///
/// // Using `new_async` we can hook up into calling our async
/// // `get_row_count` function.
/// let engine = Engine::new(Config::new().async_support(true))?;
/// let mut store = Store::new(&engine, MyDatabase {
/// // ...
/// });
/// let get_row_count_type = wasmtime::FuncType::new(
/// &engine,
/// None,
/// Some(wasmtime::ValType::I32),
/// );
/// let get = Func::new_async(&mut store, get_row_count_type, |caller, _params, results| {
/// Box::new(async move {
/// let count = caller.data().get_row_count().await;
/// results[0] = Val::I32(count as i32);
/// Ok(())
/// })
/// });
/// // ...
/// # Ok(())
/// # }
/// ```
#[cfg(all(feature = "async", feature = "cranelift"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "async", feature = "cranelift"))))]
pub fn new_async<T, F>(store: impl AsContextMut<Data = T>, ty: FuncType, func: F) -> Func
where
F: for<'a> Fn(
Caller<'a, T>,
&'a [Val],
&'a mut [Val],
) -> Box<dyn Future<Output = Result<()>> + Send + 'a>
+ Send
+ Sync
+ 'static,
{
assert!(
store.as_context().async_support(),
"cannot use `new_async` without enabling async support in the config"
);
assert!(ty.comes_from_same_engine(store.as_context().engine()));
Func::new(store, ty, move |mut caller, params, results| {
let async_cx = caller
.store
.as_context_mut()
.0
.async_cx()
.expect("Attempt to spawn new action on dying fiber");
let mut future = Pin::from(func(caller, params, results));
match unsafe { async_cx.block_on(future.as_mut()) } {
Ok(Ok(())) => Ok(()),
Ok(Err(trap)) | Err(trap) => Err(trap),
}
})
}
pub(crate) unsafe fn from_vm_func_ref(
store: &mut StoreOpaque,
raw: *mut VMFuncRef,
) -> Option<Func> {
let func_ref = NonNull::new(raw)?;
debug_assert!(func_ref.as_ref().type_index != VMSharedTypeIndex::default());
let export = ExportFunction { func_ref };
Some(Func::from_wasmtime_function(export, store))
}
/// Creates a new `Func` from the given Rust closure.
///
/// This function will create a new `Func` which, when called, will
/// execute the given Rust closure. Unlike [`Func::new`] the target
/// function being called is known statically so the type signature can
/// be inferred. Rust types will map to WebAssembly types as follows:
///
/// | Rust Argument Type | WebAssembly Type |
/// |-----------------------------------|---------------------------------------|
/// | `i32` | `i32` |
/// | `u32` | `i32` |
/// | `i64` | `i64` |
/// | `u64` | `i64` |
/// | `f32` | `f32` |
/// | `f64` | `f64` |
/// | `V128` on x86-64 and aarch64 only | `v128` |
/// | `Option<Func>` | `funcref` aka `(ref null func)` |
/// | `Func` | `(ref func)` |
/// | `Option<Nofunc>` | `nullfuncref` aka `(ref null nofunc)` |
/// | `NoFunc` | `(ref nofunc)` |
/// | `Option<ExternRef>` | `externref` aka `(ref null extern)` |
/// | `ExternRef` | `(ref extern)` |
/// | `Option<AnyRef>` | `anyref` aka `(ref null any)` |
/// | `AnyRef` | `(ref any)` |
/// | `Option<I31>` | `i31ref` aka `(ref null i31)` |
/// | `I31` | `(ref i31)` |
///
/// Any of the Rust types can be returned from the closure as well, in
/// addition to some extra types
///
/// | Rust Return Type | WebAssembly Return Type | Meaning |
/// |-------------------|-------------------------|-----------------------|
/// | `()` | nothing | no return value |
/// | `T` | `T` | a single return value |
/// | `(T1, T2, ...)` | `T1 T2 ...` | multiple returns |
///
/// Note that all return types can also be wrapped in `Result<_>` to
/// indicate that the host function can generate a trap as well as possibly
/// returning a value.
///
/// Finally you can also optionally take [`Caller`] as the first argument of
/// your closure. If inserted then you're able to inspect the caller's
/// state, for example the [`Memory`](crate::Memory) it has exported so you
/// can read what pointers point to.
///
/// Note that when using this API, the intention is to create as thin of a
/// layer as possible for when WebAssembly calls the function provided. With
/// sufficient inlining and optimization the WebAssembly will call straight
/// into `func` provided, with no extra fluff entailed.
///
/// # Why `Send + Sync + 'static`?
///
/// All host functions defined in a [`Store`](crate::Store) (including
/// those from [`Func::new`] and other constructors) require that the
/// `func` provided is `Send + Sync + 'static`. Additionally host functions
/// always are `Fn` as opposed to `FnMut` or `FnOnce`. This can at-a-glance
/// feel restrictive since the closure cannot close over as many types as
/// before. The reason for this, though, is to ensure that
/// [`Store<T>`](crate::Store) can implement both the `Send` and `Sync`
/// traits.
///
/// Fear not, however, because this isn't as restrictive as it seems! Host
/// functions are provided a [`Caller<'_, T>`](crate::Caller) argument which
/// allows access to the host-defined data within the
/// [`Store`](crate::Store). The `T` type is not required to be any of
/// `Send`, `Sync`, or `'static`! This means that you can store whatever
/// you'd like in `T` and have it accessible by all host functions.
/// Additionally mutable access to `T` is allowed through
/// [`Caller::data_mut`].
///
/// Most host-defined [`Func`] values provide closures that end up not
/// actually closing over any values. These zero-sized types will use the
/// context from [`Caller`] for host-defined information.
///
/// # Errors
///
/// The closure provided here to `wrap` can optionally return a
/// [`Result<T>`](anyhow::Result). Returning `Ok(t)` represents the host
/// function successfully completing with the `t` result. Returning
/// `Err(e)`, however, is equivalent to raising a custom wasm trap.
/// Execution of WebAssembly does not resume and the stack is unwound to the
/// original caller of the function where the error is returned.
///
/// For more information about errors in Wasmtime see the [`Trap`]
/// documentation.
///
/// [`Trap`]: crate::Trap
///
/// # Examples
///
/// First up we can see how simple wasm imports can be implemented, such
/// as a function that adds its two arguments and returns the result.
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::<()>::default();
/// let add = Func::wrap(&mut store, |a: i32, b: i32| a + b);
/// let module = Module::new(
/// store.engine(),
/// r#"
/// (module
/// (import "" "" (func $add (param i32 i32) (result i32)))
/// (func (export "foo") (param i32 i32) (result i32)
/// local.get 0
/// local.get 1
/// call $add))
/// "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[add.into()])?;
/// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?;
/// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
/// # Ok(())
/// # }
/// ```
///
/// We can also do the same thing, but generate a trap if the addition
/// overflows:
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::<()>::default();
/// let add = Func::wrap(&mut store, |a: i32, b: i32| {
/// match a.checked_add(b) {
/// Some(i) => Ok(i),
/// None => anyhow::bail!("overflow"),
/// }
/// });
/// let module = Module::new(
/// store.engine(),
/// r#"
/// (module
/// (import "" "" (func $add (param i32 i32) (result i32)))
/// (func (export "foo") (param i32 i32) (result i32)
/// local.get 0
/// local.get 1
/// call $add))
/// "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[add.into()])?;
/// let foo = instance.get_typed_func::<(i32, i32), i32>(&mut store, "foo")?;
/// assert_eq!(foo.call(&mut store, (1, 2))?, 3);
/// assert!(foo.call(&mut store, (i32::max_value(), 1)).is_err());
/// # Ok(())
/// # }
/// ```
///
/// And don't forget all the wasm types are supported!
///
/// ```
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::<()>::default();
/// let debug = Func::wrap(&mut store, |a: i32, b: u32, c: f32, d: i64, e: u64, f: f64| {
///
/// println!("a={}", a);
/// println!("b={}", b);
/// println!("c={}", c);
/// println!("d={}", d);
/// println!("e={}", e);
/// println!("f={}", f);
/// });
/// let module = Module::new(
/// store.engine(),
/// r#"
/// (module
/// (import "" "" (func $debug (param i32 i32 f32 i64 i64 f64)))
/// (func (export "foo")
/// i32.const -1
/// i32.const 1
/// f32.const 2
/// i64.const -3
/// i64.const 3
/// f64.const 4
/// call $debug))
/// "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[debug.into()])?;
/// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
/// foo.call(&mut store, ())?;
/// # Ok(())
/// # }
/// ```
///
/// Finally if you want to get really fancy you can also implement
/// imports that read/write wasm module's memory
///
/// ```
/// use std::str;
///
/// # use wasmtime::*;
/// # fn main() -> anyhow::Result<()> {
/// # let mut store = Store::default();
/// let log_str = Func::wrap(&mut store, |mut caller: Caller<'_, ()>, ptr: i32, len: i32| {
/// let mem = match caller.get_export("memory") {
/// Some(Extern::Memory(mem)) => mem,
/// _ => anyhow::bail!("failed to find host memory"),
/// };
/// let data = mem.data(&caller)
/// .get(ptr as u32 as usize..)
/// .and_then(|arr| arr.get(..len as u32 as usize));
/// let string = match data {
/// Some(data) => match str::from_utf8(data) {
/// Ok(s) => s,
/// Err(_) => anyhow::bail!("invalid utf-8"),
/// },
/// None => anyhow::bail!("pointer/length out of bounds"),
/// };
/// assert_eq!(string, "Hello, world!");
/// println!("{}", string);
/// Ok(())
/// });
/// let module = Module::new(
/// store.engine(),
/// r#"
/// (module
/// (import "" "" (func $log_str (param i32 i32)))
/// (func (export "foo")
/// i32.const 4 ;; ptr
/// i32.const 13 ;; len
/// call $log_str)
/// (memory (export "memory") 1)
/// (data (i32.const 4) "Hello, world!"))
/// "#,
/// )?;
/// let instance = Instance::new(&mut store, &module, &[log_str.into()])?;
/// let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
/// foo.call(&mut store, ())?;
/// # Ok(())
/// # }
/// ```
pub fn wrap<T, Params, Results>(
mut store: impl AsContextMut<Data = T>,
func: impl IntoFunc<T, Params, Results>,
) -> Func {
let store = store.as_context_mut().0;
// part of this unsafety is about matching the `T` to a `Store<T>`,
// which is done through the `AsContextMut` bound above.
unsafe {
let host = HostFunc::wrap(store.engine(), func);
host.into_func(store)
}
}
for_each_function_signature!(generate_wrap_async_func);
/// Returns the underlying wasm type that this `Func` has.
///
/// # Panics
///
/// Panics if `store` does not own this function.
pub fn ty(&self, store: impl AsContext) -> FuncType {
self.load_ty(&store.as_context().0)
}
/// Forcibly loads the type of this function from the `Engine`.
///
/// Note that this is a somewhat expensive method since it requires taking a
/// lock as well as cloning a type.
pub(crate) fn load_ty(&self, store: &StoreOpaque) -> FuncType {
assert!(self.comes_from_same_store(store));
FuncType::from_shared_type_index(store.engine(), self.type_index(store.store_data()))
}
/// Does this function match the given type?
///
/// That is, is this function's type a subtype of the given type?
pub fn matches_ty(&self, store: impl AsContext, func_ty: &FuncType) -> bool {
self._matches_ty(store.as_context().0, func_ty)
}
pub(crate) fn _matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> bool {
let actual_ty = self.load_ty(store);
actual_ty.matches(func_ty)
}
pub(crate) fn ensure_matches_ty(&self, store: &StoreOpaque, func_ty: &FuncType) -> Result<()> {
if !self.comes_from_same_store(store) {
bail!("function used with wrong store");
}
if self._matches_ty(store, func_ty) {
Ok(())
} else {
let actual_ty = self.load_ty(store);
bail!("type mismatch: expected {func_ty}, found {actual_ty}")
}
}
/// Gets a reference to the `FuncType` for this function.
///
/// Note that this returns both a reference to the type of this function as
/// well as a reference back to the store itself. This enables using the
/// `StoreOpaque` while the `FuncType` is also being used (from the
/// perspective of the borrow-checker) because otherwise the signature would
/// consider `StoreOpaque` borrowed mutable while `FuncType` is in use.
fn ty_ref<'a>(&self, store: &'a mut StoreOpaque) -> (&'a FuncType, &'a StoreOpaque) {
// If we haven't loaded our type into the store yet then do so lazily at
// this time.
if store.store_data()[self.0].ty.is_none() {
let ty = self.load_ty(store);
store.store_data_mut()[self.0].ty = Some(Box::new(ty));
}
(store.store_data()[self.0].ty.as_ref().unwrap(), store)
}
pub(crate) fn type_index(&self, data: &StoreData) -> VMSharedTypeIndex {
data[self.0].sig_index()
}
/// Invokes this function with the `params` given and writes returned values
/// to `results`.
///
/// The `params` here must match the type signature of this `Func`, or an
/// error will occur. Additionally `results` must have the same
/// length as the number of results for this function. Calling this function
/// will synchronously execute the WebAssembly function referenced to get
/// the results.
///
/// This function will return `Ok(())` if execution completed without a trap
/// or error of any kind. In this situation the results will be written to
/// the provided `results` array.
///
/// # Errors
///
/// Any error which occurs throughout the execution of the function will be
/// returned as `Err(e)`. The [`Error`](anyhow::Error) type can be inspected
/// for the precise error cause such as:
///
/// * [`Trap`] - indicates that a wasm trap happened and execution was
/// halted.
/// * [`WasmBacktrace`] - optionally included on errors for backtrace
/// information of the trap/error.
/// * Other string-based errors to indicate issues such as type errors with
/// `params`.
/// * Any host-originating error originally returned from a function defined
/// via [`Func::new`], for example.
///
/// Errors typically indicate that execution of WebAssembly was halted
/// mid-way and did not complete after the error condition happened.
///
/// [`Trap`]: crate::Trap
///
/// # Panics
///
/// This function will panic if called on a function belonging to an async
/// store. Asynchronous stores must always use `call_async`.
/// initiates a panic. Also panics if `store` does not own this function.
///
/// [`WasmBacktrace`]: crate::WasmBacktrace
pub fn call(
&self,
mut store: impl AsContextMut,
params: &[Val],
results: &mut [Val],
) -> Result<()> {
assert!(
!store.as_context().async_support(),
"must use `call_async` when async support is enabled on the config",
);
let mut store = store.as_context_mut();
let need_gc = self.call_impl_check_args(&mut store, params, results)?;
if need_gc {
store.0.gc();
}
unsafe { self.call_impl_do_call(&mut store, params, results) }
}
/// Invokes this function in an "unchecked" fashion, reading parameters and
/// writing results to `params_and_returns`.
///
/// This function is the same as [`Func::call`] except that the arguments
/// and results both use a different representation. If possible it's
/// recommended to use [`Func::call`] if safety isn't necessary or to use
/// [`Func::typed`] in conjunction with [`TypedFunc::call`] since that's
/// both safer and faster than this method of invoking a function.
///
/// Note that if this function takes `externref` arguments then it will
/// **not** automatically GC unlike the [`Func::call`] and
/// [`TypedFunc::call`] functions. This means that if this function is
/// invoked many times with new `ExternRef` values and no other GC happens