-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
typed.rs
2398 lines (2212 loc) · 87.9 KB
/
typed.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::component::func::{Func, LiftContext, LowerContext, Options};
use crate::component::matching::InstanceType;
use crate::component::storage::{storage_as_slice, storage_as_slice_mut};
use crate::{AsContextMut, StoreContext, StoreContextMut, ValRaw};
use anyhow::{anyhow, bail, Context, Result};
use std::borrow::Cow;
use std::fmt;
use std::marker;
use std::mem::{self, MaybeUninit};
use std::ptr::NonNull;
use std::str;
use std::sync::Arc;
use wasmtime_environ::component::{
CanonicalAbiInfo, ComponentTypes, InterfaceType, StringEncoding, VariantInfo, MAX_FLAT_PARAMS,
MAX_FLAT_RESULTS,
};
use wasmtime_runtime::component::ComponentInstance;
use wasmtime_runtime::SendSyncPtr;
/// A statically-typed version of [`Func`] which takes `Params` as input and
/// returns `Return`.
///
/// This is an efficient way to invoke a WebAssembly component where if the
/// inputs and output are statically known this can eschew the vast majority of
/// machinery and checks when calling WebAssembly. This is the most optimized
/// way to call a WebAssembly component.
///
/// Note that like [`Func`] this is a pointer within a [`Store`](crate::Store)
/// and usage will panic if used with the wrong store.
///
/// This type is primarily created with the [`Func::typed`] API.
pub struct TypedFunc<Params, Return> {
func: Func,
// The definition of this field is somewhat subtle and may be surprising.
// Naively one might expect something like
//
// _marker: marker::PhantomData<fn(Params) -> Return>,
//
// Since this is a function pointer after all. The problem with this
// definition though is that it imposes the wrong variance on `Params` from
// what we want. Abstractly a `fn(Params)` is able to store `Params` within
// it meaning you can only give it `Params` that live longer than the
// function pointer.
//
// With a component model function, however, we're always copying data from
// the host into the guest, so we are never storing pointers to `Params`
// into the guest outside the duration of a `call`, meaning we can actually
// accept values in `TypedFunc::call` which live for a shorter duration
// than the `Params` argument on the struct.
//
// This all means that we don't use a phantom function pointer, but instead
// feign phantom storage here to get the variance desired.
_marker: marker::PhantomData<(Params, Return)>,
}
impl<Params, Return> Copy for TypedFunc<Params, Return> {}
impl<Params, Return> Clone for TypedFunc<Params, Return> {
fn clone(&self) -> TypedFunc<Params, Return> {
*self
}
}
impl<Params, Return> TypedFunc<Params, Return>
where
Params: ComponentNamedList + Lower,
Return: ComponentNamedList + Lift,
{
/// Creates a new [`TypedFunc`] from the provided component [`Func`],
/// unsafely asserting that the underlying function takes `Params` as
/// input and returns `Return`.
///
/// # Unsafety
///
/// This is an unsafe function because it does not verify that the [`Func`]
/// provided actually implements this signature. It's up to the caller to
/// have performed some other sort of check to ensure that the signature is
/// correct.
pub unsafe fn new_unchecked(func: Func) -> TypedFunc<Params, Return> {
TypedFunc {
_marker: marker::PhantomData,
func,
}
}
/// Returns the underlying un-typed [`Func`] that this [`TypedFunc`]
/// references.
pub fn func(&self) -> &Func {
&self.func
}
/// Calls the underlying WebAssembly component function using the provided
/// `params` as input.
///
/// This method is used to enter into a component. Execution happens within
/// the `store` provided. The `params` are copied into WebAssembly memory
/// as appropriate and a core wasm function is invoked.
///
/// # Post-return
///
/// In the component model each function can have a "post return" specified
/// which allows cleaning up the arguments returned to the host. For example
/// if WebAssembly returns a string to the host then it might be a uniquely
/// allocated string which, after the host finishes processing it, needs to
/// be deallocated in the wasm instance's own linear memory to prevent
/// memory leaks in wasm itself. The `post-return` canonical abi option is
/// used to configured this.
///
/// To accommodate this feature of the component model after invoking a
/// function via [`TypedFunc::call`] you must next invoke
/// [`TypedFunc::post_return`]. Note that the return value of the function
/// should be processed between these two function calls. The return value
/// continues to be usable from an embedder's perspective after
/// `post_return` is called, but after `post_return` is invoked it may no
/// longer retain the same value that the wasm module originally returned.
///
/// Also note that [`TypedFunc::post_return`] must be invoked irrespective
/// of whether the canonical ABI option `post-return` was configured or not.
/// This means that embedders must unconditionally call
/// [`TypedFunc::post_return`] when a function returns. If this function
/// call returns an error, however, then [`TypedFunc::post_return`] is not
/// required.
///
/// # Errors
///
/// This function can return an error for a number of reasons:
///
/// * If the wasm itself traps during execution.
/// * If the wasm traps while copying arguments into memory.
/// * If the wasm provides bad allocation pointers when copying arguments
/// into memory.
/// * If the wasm returns a value which violates the canonical ABI.
/// * If this function's instances cannot be entered, for example if the
/// instance is currently calling a host function.
/// * If a previous function call occurred and the corresponding
/// `post_return` hasn't been invoked yet.
///
/// In general there are many ways that things could go wrong when copying
/// types in and out of a wasm module with the canonical ABI, and certain
/// error conditions are specific to certain types. For example a
/// WebAssembly module can't return an invalid `char`. When allocating space
/// for this host to copy a string into the returned pointer must be
/// in-bounds in memory.
///
/// If an error happens then the error should contain detailed enough
/// information to understand which part of the canonical ABI went wrong
/// and what to inspect.
///
/// # Panics
///
/// Panics if this is called on a function in an asynchronous store. This
/// only works with functions defined within a synchonous store. Also
/// panics if `store` does not own this function.
pub fn call(&self, store: impl AsContextMut, params: Params) -> Result<Return> {
assert!(
!store.as_context().async_support(),
"must use `call_async` when async support is enabled on the config"
);
self.call_impl(store, params)
}
/// Exactly like [`Self::call`], except for use on asynchronous stores.
///
/// # Panics
///
/// Panics if this is called on a function in a synchronous store. This
/// only works with functions defined within an asynchronous store. Also
/// panics if `store` does not own this function.
#[cfg(feature = "async")]
#[cfg_attr(nightlydoc, doc(cfg(feature = "async")))]
pub async fn call_async<T>(
&self,
mut store: impl AsContextMut<Data = T>,
params: Params,
) -> Result<Return>
where
T: Send,
Params: Send + Sync,
Return: Send + Sync,
{
let mut store = store.as_context_mut();
assert!(
store.0.async_support(),
"cannot use `call_async` when async support is not enabled on the config"
);
store
.on_fiber(|store| self.call_impl(store, params))
.await?
}
fn call_impl(&self, mut store: impl AsContextMut, params: Params) -> Result<Return> {
let store = &mut store.as_context_mut();
// Note that this is in theory simpler than it might read at this time.
// Here we're doing a runtime dispatch on the `flatten_count` for the
// params/results to see whether they're inbounds. This creates 4 cases
// to handle. In reality this is a highly optimizable branch where LLVM
// will easily figure out that only one branch here is taken.
//
// Otherwise this current construction is done to ensure that the stack
// space reserved for the params/results is always of the appropriate
// size (as the params/results needed differ depending on the "flatten"
// count)
if Params::flatten_count() <= MAX_FLAT_PARAMS {
if Return::flatten_count() <= MAX_FLAT_RESULTS {
self.func.call_raw(
store,
¶ms,
Self::lower_stack_args,
Self::lift_stack_result,
)
} else {
self.func.call_raw(
store,
¶ms,
Self::lower_stack_args,
Self::lift_heap_result,
)
}
} else {
if Return::flatten_count() <= MAX_FLAT_RESULTS {
self.func.call_raw(
store,
¶ms,
Self::lower_heap_args,
Self::lift_stack_result,
)
} else {
self.func.call_raw(
store,
¶ms,
Self::lower_heap_args,
Self::lift_heap_result,
)
}
}
}
/// Lower parameters directly onto the stack specified by the `dst`
/// location.
///
/// This is only valid to call when the "flatten count" is small enough, or
/// when the canonical ABI says arguments go through the stack rather than
/// the heap.
fn lower_stack_args<T>(
cx: &mut LowerContext<'_, T>,
params: &Params,
ty: InterfaceType,
dst: &mut MaybeUninit<Params::Lower>,
) -> Result<()> {
assert!(Params::flatten_count() <= MAX_FLAT_PARAMS);
params.lower(cx, ty, dst)?;
Ok(())
}
/// Lower parameters onto a heap-allocated location.
///
/// This is used when the stack space to be used for the arguments is above
/// the `MAX_FLAT_PARAMS` threshold. Here the wasm's `realloc` function is
/// invoked to allocate space and then parameters are stored at that heap
/// pointer location.
fn lower_heap_args<T>(
cx: &mut LowerContext<'_, T>,
params: &Params,
ty: InterfaceType,
dst: &mut MaybeUninit<ValRaw>,
) -> Result<()> {
assert!(Params::flatten_count() > MAX_FLAT_PARAMS);
// Memory must exist via validation if the arguments are stored on the
// heap, so we can create a `MemoryMut` at this point. Afterwards
// `realloc` is used to allocate space for all the arguments and then
// they're all stored in linear memory.
//
// Note that `realloc` will bake in a check that the returned pointer is
// in-bounds.
let ptr = cx.realloc(0, 0, Params::ALIGN32, Params::SIZE32)?;
params.store(cx, ty, ptr)?;
// Note that the pointer here is stored as a 64-bit integer. This allows
// this to work with either 32 or 64-bit memories. For a 32-bit memory
// it'll just ignore the upper 32 zero bits, and for 64-bit memories
// this'll have the full 64-bits. Note that for 32-bit memories the call
// to `realloc` above guarantees that the `ptr` is in-bounds meaning
// that we will know that the zero-extended upper bits of `ptr` are
// guaranteed to be zero.
//
// This comment about 64-bit integers is also referred to below with
// "WRITEPTR64".
dst.write(ValRaw::i64(ptr as i64));
Ok(())
}
/// Lift the result of a function directly from the stack result.
///
/// This is only used when the result fits in the maximum number of stack
/// slots.
fn lift_stack_result(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
dst: &Return::Lower,
) -> Result<Return> {
assert!(Return::flatten_count() <= MAX_FLAT_RESULTS);
Return::lift(cx, ty, dst)
}
/// Lift the result of a function where the result is stored indirectly on
/// the heap.
fn lift_heap_result(
cx: &mut LiftContext<'_>,
ty: InterfaceType,
dst: &ValRaw,
) -> Result<Return> {
assert!(Return::flatten_count() > MAX_FLAT_RESULTS);
// FIXME: needs to read an i64 for memory64
let ptr = usize::try_from(dst.get_u32())?;
if ptr % usize::try_from(Return::ALIGN32)? != 0 {
bail!("return pointer not aligned");
}
let bytes = cx
.memory()
.get(ptr..)
.and_then(|b| b.get(..Return::SIZE32))
.ok_or_else(|| anyhow::anyhow!("pointer out of bounds of memory"))?;
Return::load(cx, ty, bytes)
}
/// See [`Func::post_return`]
pub fn post_return(&self, store: impl AsContextMut) -> Result<()> {
self.func.post_return(store)
}
/// See [`Func::post_return_async`]
#[cfg(feature = "async")]
#[cfg_attr(nightlydoc, doc(cfg(feature = "async")))]
pub async fn post_return_async<T: Send>(
&self,
store: impl AsContextMut<Data = T>,
) -> Result<()> {
self.func.post_return_async(store).await
}
}
/// A trait representing a static list of named types that can be passed to or
/// returned from a [`TypedFunc`].
///
/// This trait is implemented for a number of tuple types and is not expected
/// to be implemented externally. The contents of this trait are hidden as it's
/// intended to be an implementation detail of Wasmtime. The contents of this
/// trait are not covered by Wasmtime's stability guarantees.
///
/// For more information about this trait see [`Func::typed`] and
/// [`TypedFunc`].
//
// Note that this is an `unsafe` trait, and the unsafety means that
// implementations of this trait must be correct or otherwise [`TypedFunc`]
// would not be memory safe. The main reason this is `unsafe` is the
// `typecheck` function which must operate correctly relative to the `AsTuple`
// interpretation of the implementor.
pub unsafe trait ComponentNamedList: ComponentType {}
/// A trait representing types which can be passed to and read from components
/// with the canonical ABI.
///
/// This trait is implemented for Rust types which can be communicated to
/// components. This is implemented for Rust types which correspond to
/// interface types in the component model of WebAssembly. The [`Func::typed`]
/// and [`TypedFunc`] Rust items are the main consumers of this trait.
///
/// For more information on this trait see the examples in [`Func::typed`].
///
/// The contents of this trait are hidden as it's intended to be an
/// implementation detail of Wasmtime. The contents of this trait are not
/// covered by Wasmtime's stability guarantees.
//
// Note that this is an `unsafe` trait as `TypedFunc`'s safety heavily relies on
// the correctness of the implementations of this trait. Some ways in which this
// trait must be correct to be safe are:
//
// * The `Lower` associated type must be a `ValRaw` sequence. It doesn't have to
// literally be `[ValRaw; N]` but when laid out in memory it must be adjacent
// `ValRaw` values and have a multiple of the size of `ValRaw` and the same
// alignment.
//
// * The `lower` function must initialize the bits within `Lower` that are going
// to be read by the trampoline that's used to enter core wasm. A trampoline
// is passed `*mut Lower` and will read the canonical abi arguments in
// sequence, so all of the bits must be correctly initialized.
//
// * The `size` and `align` functions must be correct for this value stored in
// the canonical ABI. The `Cursor<T>` iteration of these bytes rely on this
// for correctness as they otherwise eschew bounds-checking.
//
// There are likely some other correctness issues which aren't documented as
// well, this isn't intended to be an exhaustive list. It suffices to say,
// though, that correctness bugs in this trait implementation are highly likely
// to lead to security bugs, which again leads to the `unsafe` in the trait.
//
// Also note that this trait specifically is not sealed because we have a proc
// macro that generates implementations of this trait for external types in a
// `#[derive]`-like fashion.
pub unsafe trait ComponentType {
/// Representation of the "lowered" form of this component value.
///
/// Lowerings lower into core wasm values which are represented by `ValRaw`.
/// This `Lower` type must be a list of `ValRaw` as either a literal array
/// or a struct where every field is a `ValRaw`. This must be `Copy` (as
/// `ValRaw` is `Copy`) and support all byte patterns. This being correct is
/// one reason why the trait is unsafe.
#[doc(hidden)]
type Lower: Copy;
/// The information about this type's canonical ABI (size/align/etc).
#[doc(hidden)]
const ABI: CanonicalAbiInfo;
#[doc(hidden)]
const SIZE32: usize = Self::ABI.size32 as usize;
#[doc(hidden)]
const ALIGN32: u32 = Self::ABI.align32;
#[doc(hidden)]
const IS_RUST_UNIT_TYPE: bool = false;
/// Returns the number of core wasm abi values will be used to represent
/// this type in its lowered form.
///
/// This divides the size of `Self::Lower` by the size of `ValRaw`.
#[doc(hidden)]
fn flatten_count() -> usize {
assert!(mem::size_of::<Self::Lower>() % mem::size_of::<ValRaw>() == 0);
assert!(mem::align_of::<Self::Lower>() == mem::align_of::<ValRaw>());
mem::size_of::<Self::Lower>() / mem::size_of::<ValRaw>()
}
/// Performs a type-check to see whether this component value type matches
/// the interface type `ty` provided.
#[doc(hidden)]
fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()>;
}
#[doc(hidden)]
pub unsafe trait ComponentVariant: ComponentType {
const CASES: &'static [Option<CanonicalAbiInfo>];
const INFO: VariantInfo = VariantInfo::new_static(Self::CASES);
const PAYLOAD_OFFSET32: usize = Self::INFO.payload_offset32 as usize;
}
/// Host types which can be passed to WebAssembly components.
///
/// This trait is implemented for all types that can be passed to components
/// either as parameters of component exports or returns of component imports.
/// This trait represents the ability to convert from the native host
/// representation to the canonical ABI.
//
// TODO: #[derive(Lower)]
// TODO: more docs here
pub unsafe trait Lower: ComponentType {
/// Performs the "lower" function in the canonical ABI.
///
/// This method will lower the current value into a component. The `lower`
/// function performs a "flat" lowering into the `dst` specified which is
/// allowed to be uninitialized entering this method but is guaranteed to be
/// fully initialized if the method returns `Ok(())`.
///
/// The `cx` context provided is the context within which this lowering is
/// happening. This contains information such as canonical options specified
/// (e.g. string encodings, memories, etc), the store itself, along with
/// type information.
///
/// The `ty` parameter is the destination type that is being lowered into.
/// For example this is the component's "view" of the type that is being
/// lowered. This is guaranteed to have passed a `typecheck` earlier.
///
/// This will only be called if `typecheck` passes for `Op::Lower`.
#[doc(hidden)]
fn lower<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()>;
/// Performs the "store" operation in the canonical ABI.
///
/// This function will store `self` into the linear memory described by
/// `cx` at the `offset` provided.
///
/// It is expected that `offset` is a valid offset in memory for
/// `Self::SIZE32` bytes. At this time that's not an unsafe contract as it's
/// always re-checked on all stores, but this is something that will need to
/// be improved in the future to remove extra bounds checks. For now this
/// function will panic if there's a bug and `offset` isn't valid within
/// memory.
///
/// The `ty` type information passed here is the same as the type
/// information passed to `lower` above, and is the component's own view of
/// what the resulting type should be.
///
/// This will only be called if `typecheck` passes for `Op::Lower`.
#[doc(hidden)]
fn store<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
) -> Result<()>;
/// Provided method to lower a list of `Self` into memory.
///
/// Requires that `offset` has already been checked for alignment and
/// validity in terms of being in-bounds, otherwise this may panic.
///
/// This is primarily here to get overridden for implementations of integers
/// which can avoid some extra fluff and use a pattern that's more easily
/// optimizable by LLVM.
#[doc(hidden)]
fn store_list<T>(
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
mut offset: usize,
items: &[Self],
) -> Result<()>
where
Self: Sized,
{
for item in items {
item.store(cx, ty, offset)?;
offset += Self::SIZE32;
}
Ok(())
}
}
/// Host types which can be created from the canonical ABI.
//
// TODO: #[derive(Lower)]
// TODO: more docs here
pub unsafe trait Lift: Sized + ComponentType {
/// Performs the "lift" operation in the canonical ABI.
///
/// This function performs a "flat" lift operation from the `src` specified
/// which is a sequence of core wasm values. The lifting operation will
/// validate core wasm values and produce a `Self` on success.
///
/// The `cx` provided contains contextual information such as the store
/// that's being loaded from, canonical options, and type information.
///
/// The `ty` parameter is the origin component's specification for what the
/// type that is being lifted is. For example this is the record type or the
/// resource type that is being lifted.
///
/// Note that this has a default implementation but if `typecheck` passes
/// for `Op::Lift` this needs to be overridden.
#[doc(hidden)]
fn lift(cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self>;
/// Performs the "load" operation in the canonical ABI.
///
/// This will read the `bytes` provided, which are a sub-slice into the
/// linear memory described by `cx`. The `bytes` array provided is
/// guaranteed to be `Self::SIZE32` bytes large. All of memory is then also
/// available through `cx` for bounds-checks and such as necessary for
/// strings/lists.
///
/// The `ty` argument is the type that's being loaded, as described by the
/// original component.
///
/// Note that this has a default implementation but if `typecheck` passes
/// for `Op::Lift` this needs to be overridden.
#[doc(hidden)]
fn load(cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self>;
/// Converts `list` into a `Vec<T>`, used in `Lift for Vec<T>`.
///
/// This is primarily here to get overridden for implementations of integers
/// which can avoid some extra fluff and use a pattern that's more easily
/// optimizable by LLVM.
#[doc(hidden)]
fn load_list(cx: &mut LiftContext<'_>, list: &WasmList<Self>) -> Result<Vec<Self>>
where
Self: Sized,
{
(0..list.len)
.map(|index| list.get_from_store(cx, index).unwrap())
.collect()
}
}
// Macro to help generate "forwarding implementations" of `ComponentType` to
// another type, used for wrappers in Rust like `&T`, `Box<T>`, etc. Note that
// these wrappers only implement lowering because lifting native Rust types
// cannot be done.
macro_rules! forward_type_impls {
($(($($generics:tt)*) $a:ty => $b:ty,)*) => ($(
unsafe impl <$($generics)*> ComponentType for $a {
type Lower = <$b as ComponentType>::Lower;
const ABI: CanonicalAbiInfo = <$b as ComponentType>::ABI;
#[inline]
fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {
<$b as ComponentType>::typecheck(ty, types)
}
}
)*)
}
forward_type_impls! {
(T: ComponentType + ?Sized) &'_ T => T,
(T: ComponentType + ?Sized) Box<T> => T,
(T: ComponentType + ?Sized) std::rc::Rc<T> => T,
(T: ComponentType + ?Sized) std::sync::Arc<T> => T,
() String => str,
(T: ComponentType) Vec<T> => [T],
}
macro_rules! forward_lowers {
($(($($generics:tt)*) $a:ty => $b:ty,)*) => ($(
unsafe impl <$($generics)*> Lower for $a {
fn lower<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
<$b as Lower>::lower(self, cx, ty, dst)
}
fn store<U>(
&self,
cx: &mut LowerContext<'_, U>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
<$b as Lower>::store(self, cx, ty, offset)
}
}
)*)
}
forward_lowers! {
(T: Lower + ?Sized) &'_ T => T,
(T: Lower + ?Sized) Box<T> => T,
(T: Lower + ?Sized) std::rc::Rc<T> => T,
(T: Lower + ?Sized) std::sync::Arc<T> => T,
() String => str,
(T: Lower) Vec<T> => [T],
}
macro_rules! forward_string_lifts {
($($a:ty,)*) => ($(
unsafe impl Lift for $a {
#[inline]
fn lift(cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
Ok(<WasmStr as Lift>::lift(cx, ty, src)?.to_str_from_memory(cx.memory())?.into())
}
#[inline]
fn load(cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
Ok(<WasmStr as Lift>::load(cx, ty, bytes)?.to_str_from_memory(cx.memory())?.into())
}
}
)*)
}
forward_string_lifts! {
Box<str>,
std::rc::Rc<str>,
std::sync::Arc<str>,
String,
}
macro_rules! forward_list_lifts {
($($a:ty,)*) => ($(
unsafe impl <T: Lift> Lift for $a {
fn lift(cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
let list = <WasmList::<T> as Lift>::lift(cx, ty, src)?;
Ok(T::load_list(cx, &list)?.into())
}
fn load(cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
let list = <WasmList::<T> as Lift>::load(cx, ty, bytes)?;
Ok(T::load_list(cx, &list)?.into())
}
}
)*)
}
forward_list_lifts! {
Box<[T]>,
std::rc::Rc<[T]>,
std::sync::Arc<[T]>,
Vec<T>,
}
// Macro to help generate `ComponentType` implementations for primitive types
// such as integers, char, bool, etc.
macro_rules! integers {
($($primitive:ident = $ty:ident in $field:ident/$get:ident with abi:$abi:ident,)*) => ($(
unsafe impl ComponentType for $primitive {
type Lower = ValRaw;
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::$abi;
fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::$ty => Ok(()),
other => bail!("expected `{}` found `{}`", desc(&InterfaceType::$ty), desc(other))
}
}
}
unsafe impl Lower for $primitive {
#[inline]
fn lower<T>(
&self,
_cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::$ty));
dst.write(ValRaw::$field(*self as $field));
Ok(())
}
#[inline]
fn store<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::$ty));
debug_assert!(offset % Self::SIZE32 == 0);
*cx.get(offset) = self.to_le_bytes();
Ok(())
}
fn store_list<T>(
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
items: &[Self],
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::$ty));
// Double-check that the CM alignment is at least the host's
// alignment for this type which should be true for all
// platforms.
assert!((Self::ALIGN32 as usize) >= mem::align_of::<Self>());
// Slice `cx`'s memory to the window that we'll be modifying.
// This should all have already been verified in terms of
// alignment and sizing meaning that these assertions here are
// not truly necessary but are instead double-checks.
//
// Note that we're casting a `[u8]` slice to `[Self]` with
// `align_to_mut` which is not safe in general but is safe in
// our specific case as all `u8` patterns are valid `Self`
// patterns since `Self` is an integral type.
let dst = &mut cx.as_slice_mut()[offset..][..items.len() * Self::SIZE32];
let (before, middle, end) = unsafe { dst.align_to_mut::<Self>() };
assert!(before.is_empty() && end.is_empty());
assert_eq!(middle.len(), items.len());
// And with all that out of the way perform the copying loop.
// This is not a `copy_from_slice` because endianness needs to
// be handled here, but LLVM should pretty easily transform this
// into a memcpy on little-endian platforms.
for (dst, src) in middle.iter_mut().zip(items) {
*dst = src.to_le();
}
Ok(())
}
}
unsafe impl Lift for $primitive {
#[inline]
fn lift(_cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::$ty));
Ok(src.$get() as $primitive)
}
#[inline]
fn load(_cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::$ty));
debug_assert!((bytes.as_ptr() as usize) % Self::SIZE32 == 0);
Ok($primitive::from_le_bytes(bytes.try_into().unwrap()))
}
fn load_list(cx: &mut LiftContext<'_>, list: &WasmList<Self>) -> Result<Vec<Self>> {
Ok(
list._as_le_slice(cx.memory())
.iter()
.map(|i| Self::from_le(*i))
.collect(),
)
}
}
)*)
}
integers! {
i8 = S8 in i32/get_i32 with abi:SCALAR1,
u8 = U8 in u32/get_u32 with abi:SCALAR1,
i16 = S16 in i32/get_i32 with abi:SCALAR2,
u16 = U16 in u32/get_u32 with abi:SCALAR2,
i32 = S32 in i32/get_i32 with abi:SCALAR4,
u32 = U32 in u32/get_u32 with abi:SCALAR4,
i64 = S64 in i64/get_i64 with abi:SCALAR8,
u64 = U64 in u64/get_u64 with abi:SCALAR8,
}
macro_rules! floats {
($($float:ident/$get_float:ident = $ty:ident with abi:$abi:ident)*) => ($(const _: () = {
/// All floats in-and-out of the canonical abi always have their nan
/// payloads canonicalized. conveniently the `NAN` constant in rust has
/// the same representation as canonical nan, so we can use that for the
/// nan value.
#[inline]
fn canonicalize(float: $float) -> $float {
if float.is_nan() {
$float::NAN
} else {
float
}
}
unsafe impl ComponentType for $float {
type Lower = ValRaw;
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::$abi;
fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::$ty => Ok(()),
other => bail!("expected `{}` found `{}`", desc(&InterfaceType::$ty), desc(other))
}
}
}
unsafe impl Lower for $float {
#[inline]
fn lower<T>(
&self,
_cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::$ty));
dst.write(ValRaw::$float(canonicalize(*self).to_bits()));
Ok(())
}
#[inline]
fn store<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::$ty));
debug_assert!(offset % Self::SIZE32 == 0);
let ptr = cx.get(offset);
*ptr = canonicalize(*self).to_bits().to_le_bytes();
Ok(())
}
}
unsafe impl Lift for $float {
#[inline]
fn lift(_cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::$ty));
Ok(canonicalize($float::from_bits(src.$get_float())))
}
#[inline]
fn load(_cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::$ty));
debug_assert!((bytes.as_ptr() as usize) % Self::SIZE32 == 0);
Ok(canonicalize($float::from_le_bytes(bytes.try_into().unwrap())))
}
}
};)*)
}
floats! {
f32/get_f32 = Float32 with abi:SCALAR4
f64/get_f64 = Float64 with abi:SCALAR8
}
unsafe impl ComponentType for bool {
type Lower = ValRaw;
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR1;
fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::Bool => Ok(()),
other => bail!("expected `bool` found `{}`", desc(other)),
}
}
}
unsafe impl Lower for bool {
fn lower<T>(
&self,
_cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::Bool));
dst.write(ValRaw::i32(*self as i32));
Ok(())
}
fn store<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::Bool));
debug_assert!(offset % Self::SIZE32 == 0);
cx.get::<1>(offset)[0] = *self as u8;
Ok(())
}
}
unsafe impl Lift for bool {
#[inline]
fn lift(_cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::Bool));
match src.get_i32() {
0 => Ok(false),
_ => Ok(true),
}
}
#[inline]
fn load(_cx: &mut LiftContext<'_>, ty: InterfaceType, bytes: &[u8]) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::Bool));
match bytes[0] {
0 => Ok(false),
_ => Ok(true),
}
}
}
unsafe impl ComponentType for char {
type Lower = ValRaw;
const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;
fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {
match ty {
InterfaceType::Char => Ok(()),
other => bail!("expected `char` found `{}`", desc(other)),
}
}
}
unsafe impl Lower for char {
#[inline]
fn lower<T>(
&self,
_cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
dst: &mut MaybeUninit<Self::Lower>,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::Char));
dst.write(ValRaw::u32(u32::from(*self)));
Ok(())
}
#[inline]
fn store<T>(
&self,
cx: &mut LowerContext<'_, T>,
ty: InterfaceType,
offset: usize,
) -> Result<()> {
debug_assert!(matches!(ty, InterfaceType::Char));
debug_assert!(offset % Self::SIZE32 == 0);
*cx.get::<4>(offset) = u32::from(*self).to_le_bytes();
Ok(())
}
}
unsafe impl Lift for char {
#[inline]
fn lift(_cx: &mut LiftContext<'_>, ty: InterfaceType, src: &Self::Lower) -> Result<Self> {
debug_assert!(matches!(ty, InterfaceType::Char));
Ok(char::try_from(src.get_u32())?)
}
#[inline]