-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
lib.rs
1785 lines (1597 loc) · 49.3 KB
/
lib.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
//! This file defines the extern "C" API, which is compatible with the
//! [Wasm C API](https://github.com/WebAssembly/wasm-c-api).
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
// TODO complete the C API
use std::cell::RefCell;
use std::panic::{self, AssertUnwindSafe};
use std::rc::Rc;
use std::{mem, ptr, slice};
use wasmtime::{
AnyRef, Callable, Config, Engine, ExportType, Extern, ExternType, Func, FuncType, Global,
GlobalType, HostInfo, HostRef, ImportType, Instance, Limits, Memory, MemoryType, Module, Store,
Table, TableType, Trap, Val, ValType,
};
mod ext;
mod wasi;
pub use crate::ext::*;
pub use crate::wasi::*;
macro_rules! declare_vec {
($name:ident, $elem_ty:path) => {
#[repr(C)]
#[derive(Clone)]
pub struct $name {
pub size: usize,
pub data: *mut $elem_ty,
}
impl $name {
#[allow(dead_code)]
fn set_from_slice(&mut self, source: &[$elem_ty]) {
let mut buffer = Vec::with_capacity(source.len());
buffer.extend_from_slice(source);
assert_eq!(buffer.len(), buffer.capacity());
self.size = buffer.len();
self.data = buffer.as_mut_ptr();
mem::forget(buffer);
}
#[allow(dead_code)]
fn set_buffer(&mut self, mut buffer: Vec<$elem_ty>) {
assert_eq!(buffer.len(), buffer.capacity());
self.size = buffer.len();
self.data = buffer.as_mut_ptr();
mem::forget(buffer);
}
#[allow(dead_code)]
fn set_uninitialized(&mut self, size: usize) {
let mut buffer = vec![Default::default(); size];
self.size = size;
self.data = buffer.as_mut_ptr();
mem::forget(buffer);
}
#[allow(dead_code)]
fn uninitialize(&mut self) {
let _ = unsafe { Vec::from_raw_parts(self.data, self.size, self.size) };
}
#[allow(dead_code)]
fn as_slice(&self) -> &[$elem_ty] {
unsafe { slice::from_raw_parts(self.data, self.size) }
}
}
impl From<Vec<$elem_ty>> for $name {
fn from(mut vec: Vec<$elem_ty>) -> Self {
assert_eq!(vec.len(), vec.capacity());
let result = $name {
size: vec.len(),
data: vec.as_mut_ptr(),
};
mem::forget(vec);
result
}
}
impl Drop for $name {
fn drop(&mut self) {
self.uninitialize();
}
}
};
($name:ident, *mut $elem_ty:path) => {
#[repr(C)]
#[derive(Clone)]
pub struct $name {
pub size: usize,
pub data: *mut *mut $elem_ty,
}
impl $name {
#[allow(dead_code)]
fn set_from_slice(&mut self, source: &[*mut $elem_ty]) {
let mut buffer = Vec::with_capacity(source.len());
buffer.extend_from_slice(source);
assert_eq!(buffer.len(), buffer.capacity());
self.size = buffer.len();
self.data = buffer.as_mut_ptr();
mem::forget(buffer);
}
#[allow(dead_code)]
fn set_buffer(&mut self, mut buffer: Vec<*mut $elem_ty>) {
assert_eq!(buffer.len(), buffer.capacity());
self.size = buffer.len();
self.data = buffer.as_mut_ptr();
mem::forget(buffer);
}
#[allow(dead_code)]
fn set_uninitialized(&mut self, size: usize) {
let mut buffer = vec![ptr::null_mut(); size];
self.size = size;
self.data = buffer.as_mut_ptr();
mem::forget(buffer);
}
#[allow(dead_code)]
fn uninitialize(&mut self) {
for element in unsafe { Vec::from_raw_parts(self.data, self.size, self.size) } {
let _ = unsafe { Box::from_raw(element) };
}
}
#[allow(dead_code)]
fn as_slice(&self) -> &[*mut $elem_ty] {
unsafe { slice::from_raw_parts(self.data, self.size) }
}
}
impl From<Vec<*mut $elem_ty>> for $name {
fn from(mut vec: Vec<*mut $elem_ty>) -> Self {
assert_eq!(vec.len(), vec.capacity());
let result = $name {
size: vec.len(),
data: vec.as_mut_ptr(),
};
mem::forget(vec);
result
}
}
impl Drop for $name {
fn drop(&mut self) {
self.uninitialize();
}
}
};
}
pub type float32_t = f32;
pub type float64_t = f64;
pub type wasm_byte_t = u8;
declare_vec!(wasm_byte_vec_t, wasm_byte_t);
pub type wasm_name_t = wasm_byte_vec_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasm_config_t {
pub(crate) config: Config,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_engine_t {
engine: HostRef<Engine>,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_store_t {
store: HostRef<Store>,
}
#[doc = ""]
pub type wasm_mutability_t = u8;
#[repr(C)]
#[derive(Clone)]
pub struct wasm_limits_t {
pub min: u32,
pub max: u32,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_valtype_t {
ty: ValType,
}
declare_vec!(wasm_valtype_vec_t, *mut wasm_valtype_t);
pub type wasm_valkind_t = u8;
#[repr(C)]
#[derive(Clone)]
pub struct wasm_functype_t {
functype: FuncType,
params_cache: Option<wasm_valtype_vec_t>,
returns_cache: Option<wasm_valtype_vec_t>,
}
declare_vec!(wasm_functype_vec_t, *mut wasm_functype_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_globaltype_t {
globaltype: GlobalType,
content_cache: Option<wasm_valtype_t>,
}
declare_vec!(wasm_globaltype_vec_t, *mut wasm_globaltype_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_tabletype_t {
tabletype: TableType,
element_cache: Option<wasm_valtype_t>,
limits_cache: Option<wasm_limits_t>,
}
declare_vec!(wasm_tabletype_vec_t, *mut wasm_tabletype_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_memorytype_t {
memorytype: MemoryType,
limits_cache: Option<wasm_limits_t>,
}
declare_vec!(wasm_memorytype_vec_t, *mut wasm_memorytype_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_externtype_t {
ty: ExternType,
cache: wasm_externtype_t_type_cache,
}
#[derive(Clone)]
enum wasm_externtype_t_type_cache {
Empty,
Func(wasm_functype_t),
Global(wasm_globaltype_t),
Memory(wasm_memorytype_t),
Table(wasm_tabletype_t),
}
declare_vec!(wasm_externtype_vec_t, *mut wasm_externtype_t);
pub type wasm_externkind_t = u8;
const WASM_EXTERN_FUNC: wasm_externkind_t = 0;
const WASM_EXTERN_GLOBAL: wasm_externkind_t = 1;
const WASM_EXTERN_TABLE: wasm_externkind_t = 2;
const WASM_EXTERN_MEMORY: wasm_externkind_t = 3;
#[repr(C)]
#[derive(Clone)]
pub struct wasm_importtype_t {
ty: ImportType,
module_cache: Option<wasm_name_t>,
name_cache: Option<wasm_name_t>,
type_cache: Option<wasm_externtype_t>,
}
declare_vec!(wasm_importtype_vec_t, *mut wasm_importtype_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_exporttype_t {
ty: ExportType,
name_cache: Option<wasm_name_t>,
type_cache: Option<wasm_externtype_t>,
}
declare_vec!(wasm_exporttype_vec_t, *mut wasm_exporttype_t);
#[doc = ""]
#[repr(C)]
#[derive(Clone)]
pub struct wasm_ref_t {
r: AnyRef,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct wasm_val_t {
pub kind: wasm_valkind_t,
pub of: wasm_val_t__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union wasm_val_t__bindgen_ty_1 {
pub i32: i32,
pub i64: i64,
pub u32: u32,
pub u64: u64,
pub f32: float32_t,
pub f64: float64_t,
pub ref_: *mut wasm_ref_t,
_bindgen_union_align: u64,
}
impl Default for wasm_val_t {
fn default() -> Self {
wasm_val_t {
kind: 0,
of: wasm_val_t__bindgen_ty_1 { i32: 0 },
}
}
}
declare_vec!(wasm_val_vec_t, wasm_val_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_frame_t {
_unused: [u8; 0],
}
declare_vec!(wasm_frame_vec_t, *mut wasm_frame_t);
#[repr(C)]
#[derive(Clone)]
pub struct wasm_instance_t {
instance: HostRef<Instance>,
exports_cache: RefCell<Option<Vec<ExternHost>>>,
}
pub type wasm_message_t = wasm_name_t;
#[repr(C)]
#[derive(Clone)]
pub struct wasm_trap_t {
trap: HostRef<Trap>,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_foreign_t {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_module_t {
module: HostRef<Module>,
imports: Vec<wasm_importtype_t>,
exports: Vec<wasm_exporttype_t>,
}
#[repr(C)]
#[derive(Clone)]
pub struct wasm_shared_module_t {
_unused: [u8; 0],
}
#[derive(Clone)]
#[repr(transparent)]
pub struct wasm_func_t {
ext: wasm_extern_t,
}
impl wasm_func_t {
fn func(&self) -> &HostRef<Func> {
match &self.ext.which {
ExternHost::Func(f) => f,
_ => unsafe { std::hint::unreachable_unchecked() },
}
}
}
pub type wasm_func_callback_t = std::option::Option<
unsafe extern "C" fn(args: *const wasm_val_t, results: *mut wasm_val_t) -> *mut wasm_trap_t,
>;
pub type wasm_func_callback_with_env_t = std::option::Option<
unsafe extern "C" fn(
env: *mut std::ffi::c_void,
args: *const wasm_val_t,
results: *mut wasm_val_t,
) -> *mut wasm_trap_t,
>;
#[derive(Clone)]
#[repr(transparent)]
pub struct wasm_global_t {
ext: wasm_extern_t,
}
impl wasm_global_t {
fn global(&self) -> &HostRef<Global> {
match &self.ext.which {
ExternHost::Global(g) => g,
_ => unsafe { std::hint::unreachable_unchecked() },
}
}
}
#[derive(Clone)]
#[repr(transparent)]
pub struct wasm_table_t {
ext: wasm_extern_t,
}
impl wasm_table_t {
fn table(&self) -> &HostRef<Table> {
match &self.ext.which {
ExternHost::Table(t) => t,
_ => unsafe { std::hint::unreachable_unchecked() },
}
}
}
pub type wasm_table_size_t = u32;
#[derive(Clone)]
#[repr(transparent)]
pub struct wasm_memory_t {
ext: wasm_extern_t,
}
impl wasm_memory_t {
fn memory(&self) -> &HostRef<Memory> {
match &self.ext.which {
ExternHost::Memory(m) => m,
_ => unsafe { std::hint::unreachable_unchecked() },
}
}
}
pub type wasm_memory_pages_t = u32;
#[derive(Clone)]
pub struct wasm_extern_t {
which: ExternHost,
}
#[derive(Clone)]
enum ExternHost {
Func(HostRef<Func>),
Global(HostRef<Global>),
Memory(HostRef<Memory>),
Table(HostRef<Table>),
}
declare_vec!(wasm_extern_vec_t, *mut wasm_extern_t);
#[no_mangle]
pub unsafe extern "C" fn wasm_byte_vec_delete(v: *mut wasm_byte_vec_t) {
(*v).uninitialize();
}
#[no_mangle]
pub unsafe extern "C" fn wasm_byte_vec_new_uninitialized(out: *mut wasm_byte_vec_t, size: usize) {
(*out).set_uninitialized(size);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_engine_delete(engine: *mut wasm_engine_t) {
let _ = Box::from_raw(engine);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_config_new() -> *mut wasm_config_t {
let config = Box::new(wasm_config_t {
config: Config::default(),
});
Box::into_raw(config)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_engine_new() -> *mut wasm_engine_t {
let engine = Box::new(wasm_engine_t {
engine: HostRef::new(Engine::default()),
});
Box::into_raw(engine)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_engine_new_with_config(c: *mut wasm_config_t) -> *mut wasm_engine_t {
let config = Box::from_raw(c).config;
let engine = Box::new(wasm_engine_t {
engine: HostRef::new(Engine::new(&config)),
});
Box::into_raw(engine)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_extern_as_func(e: *mut wasm_extern_t) -> *mut wasm_func_t {
match &(*e).which {
ExternHost::Func(_) => e.cast(),
_ => ptr::null_mut(),
}
}
#[no_mangle]
pub unsafe extern "C" fn wasm_extern_vec_delete(v: *mut wasm_extern_vec_t) {
(*v).uninitialize();
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_as_extern(f: *mut wasm_func_t) -> *mut wasm_extern_t {
&mut (*f).ext
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_call(
func: *const wasm_func_t,
args: *const wasm_val_t,
results: *mut wasm_val_t,
) -> *mut wasm_trap_t {
let func = (*func).func().borrow();
let mut params = Vec::with_capacity(func.param_arity());
for i in 0..func.param_arity() {
let val = &(*args.add(i));
params.push(val.val());
}
// We're calling arbitrary code here most of the time, and we in general
// want to try to insulate callers against bugs in wasmtime/wasi/etc if we
// can. As a result we catch panics here and transform them to traps to
// allow the caller to have any insulation possible against Rust panics.
let result = panic::catch_unwind(AssertUnwindSafe(|| func.call(¶ms)));
match result {
Ok(Ok(out)) => {
for i in 0..func.result_arity() {
let val = &mut (*results.add(i));
*val = wasm_val_t::from_val(&out[i]);
}
ptr::null_mut()
}
Ok(Err(trap)) => {
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
Box::into_raw(trap)
}
Err(panic) => {
let trap = if let Some(msg) = panic.downcast_ref::<String>() {
Trap::new(msg)
} else if let Some(msg) = panic.downcast_ref::<&'static str>() {
Trap::new(*msg)
} else {
Trap::new("rust panic happened")
};
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
Box::into_raw(trap)
}
}
}
impl wasm_val_t {
fn default() -> wasm_val_t {
wasm_val_t {
kind: 0,
of: wasm_val_t__bindgen_ty_1 { i32: 0 },
}
}
fn set(&mut self, val: Val) {
match val {
Val::I32(i) => {
self.kind = from_valtype(&ValType::I32);
self.of = wasm_val_t__bindgen_ty_1 { i32: i };
}
Val::I64(i) => {
self.kind = from_valtype(&ValType::I64);
self.of = wasm_val_t__bindgen_ty_1 { i64: i };
}
Val::F32(f) => {
self.kind = from_valtype(&ValType::F32);
self.of = wasm_val_t__bindgen_ty_1 { u32: f };
}
Val::F64(f) => {
self.kind = from_valtype(&ValType::F64);
self.of = wasm_val_t__bindgen_ty_1 { u64: f };
}
_ => unimplemented!("wasm_val_t::from_val {:?}", val),
}
}
fn from_val(val: &Val) -> wasm_val_t {
match val {
Val::I32(i) => wasm_val_t {
kind: from_valtype(&ValType::I32),
of: wasm_val_t__bindgen_ty_1 { i32: *i },
},
Val::I64(i) => wasm_val_t {
kind: from_valtype(&ValType::I64),
of: wasm_val_t__bindgen_ty_1 { i64: *i },
},
Val::F32(f) => wasm_val_t {
kind: from_valtype(&ValType::F32),
of: wasm_val_t__bindgen_ty_1 { u32: *f },
},
Val::F64(f) => wasm_val_t {
kind: from_valtype(&ValType::F64),
of: wasm_val_t__bindgen_ty_1 { u64: *f },
},
_ => unimplemented!("wasm_val_t::from_val {:?}", val),
}
}
fn val(&self) -> Val {
match into_valtype(self.kind) {
ValType::I32 => Val::from(unsafe { self.of.i32 }),
ValType::I64 => Val::from(unsafe { self.of.i64 }),
ValType::F32 => Val::from(unsafe { self.of.f32 }),
ValType::F64 => Val::from(unsafe { self.of.f64 }),
_ => unimplemented!("wasm_val_t::val {:?}", self.kind),
}
}
}
struct Callback {
callback: wasm_func_callback_t,
}
impl Callable for Callback {
fn call(&self, params: &[Val], results: &mut [Val]) -> Result<(), Trap> {
let params = params
.iter()
.map(|p| wasm_val_t::from_val(p))
.collect::<Vec<_>>();
let mut out_results = vec![wasm_val_t::default(); results.len()];
let func = self.callback.expect("wasm_func_callback_t fn");
let out = unsafe { func(params.as_ptr(), out_results.as_mut_ptr()) };
if !out.is_null() {
let trap: Box<wasm_trap_t> = unsafe { Box::from_raw(out) };
return Err(trap.trap.borrow().clone());
}
for i in 0..results.len() {
results[i] = out_results[i].val();
}
Ok(())
}
}
struct CallbackWithEnv {
callback: wasm_func_callback_with_env_t,
env: *mut std::ffi::c_void,
finalizer: std::option::Option<unsafe extern "C" fn(env: *mut std::ffi::c_void)>,
}
impl Callable for CallbackWithEnv {
fn call(&self, params: &[Val], results: &mut [Val]) -> Result<(), Trap> {
let params = params
.iter()
.map(|p| wasm_val_t::from_val(p))
.collect::<Vec<_>>();
let mut out_results = vec![wasm_val_t::default(); results.len()];
let func = self.callback.expect("wasm_func_callback_with_env_t fn");
let out = unsafe { func(self.env, params.as_ptr(), out_results.as_mut_ptr()) };
if !out.is_null() {
let trap: Box<wasm_trap_t> = unsafe { Box::from_raw(out) };
return Err(trap.trap.borrow().clone());
}
for i in 0..results.len() {
results[i] = out_results[i].val();
}
Ok(())
}
}
impl Drop for CallbackWithEnv {
fn drop(&mut self) {
if let Some(finalizer) = self.finalizer {
unsafe {
finalizer(self.env);
}
}
}
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_new(
store: *mut wasm_store_t,
ty: *const wasm_functype_t,
callback: wasm_func_callback_t,
) -> *mut wasm_func_t {
let store = &(*store).store.borrow();
let ty = (*ty).functype.clone();
let callback = Rc::new(Callback { callback });
let func = Box::new(wasm_func_t {
ext: wasm_extern_t {
which: ExternHost::Func(HostRef::new(Func::new(store, ty, callback))),
},
});
Box::into_raw(func)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_delete(f: *mut wasm_func_t) {
let _ = Box::from_raw(f);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_functype_new(
params: *mut wasm_valtype_vec_t,
results: *mut wasm_valtype_vec_t,
) -> *mut wasm_functype_t {
let params = Vec::from_raw_parts((*params).data, (*params).size, (*params).size)
.into_iter()
.map(|vt| (*vt).ty.clone())
.collect::<Vec<_>>();
let results = Vec::from_raw_parts((*results).data, (*results).size, (*results).size)
.into_iter()
.map(|vt| (*vt).ty.clone())
.collect::<Vec<_>>();
let functype = FuncType::new(params.into_boxed_slice(), results.into_boxed_slice());
let functype = Box::new(wasm_functype_t {
functype,
params_cache: None, // TODO get from args?
returns_cache: None, // TODO get from args?
});
Box::into_raw(functype)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_functype_delete(ft: *mut wasm_functype_t) {
let _ = Box::from_raw(ft);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_instance_delete(instance: *mut wasm_instance_t) {
let _ = Box::from_raw(instance);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_instance_new(
store: *mut wasm_store_t,
module: *const wasm_module_t,
imports: *const *const wasm_extern_t,
result: *mut *mut wasm_trap_t,
) -> *mut wasm_instance_t {
let mut externs: Vec<Extern> = Vec::with_capacity((*module).imports.len());
for i in 0..(*module).imports.len() {
let import = *imports.add(i);
externs.push(match &(*import).which {
ExternHost::Func(e) => Extern::Func(e.borrow().clone()),
ExternHost::Table(e) => Extern::Table(e.borrow().clone()),
ExternHost::Global(e) => Extern::Global(e.borrow().clone()),
ExternHost::Memory(e) => Extern::Memory(e.borrow().clone()),
});
}
let store = &(*store).store.borrow();
let module = &(*module).module.borrow();
// FIXME(WebAssembly/wasm-c-api#126) what else can we do with the `store`
// argument?
if !Store::same(&store, module.store()) {
if !result.is_null() {
let trap = Trap::new("wasm_store_t must match store in wasm_module_t");
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
(*result) = Box::into_raw(trap);
}
return ptr::null_mut();
}
match Instance::new(module, &externs) {
Ok(instance) => {
let instance = Box::new(wasm_instance_t {
instance: HostRef::new(instance),
exports_cache: RefCell::new(None),
});
if !result.is_null() {
(*result) = ptr::null_mut();
}
Box::into_raw(instance)
}
Err(trap) => {
if !result.is_null() {
let trap = match trap.downcast::<Trap>() {
Ok(trap) => trap,
Err(e) => Trap::new(format!("{:?}", e)),
};
let trap = Box::new(wasm_trap_t {
trap: HostRef::new(trap),
});
(*result) = Box::into_raw(trap);
}
ptr::null_mut()
}
}
}
#[no_mangle]
pub unsafe extern "C" fn wasm_instance_exports(
instance: *const wasm_instance_t,
out: *mut wasm_extern_vec_t,
) {
let mut cache = (*instance).exports_cache.borrow_mut();
let exports = cache.get_or_insert_with(|| {
let instance = &(*instance).instance.borrow();
instance
.exports()
.iter()
.map(|e| match e {
Extern::Func(f) => ExternHost::Func(HostRef::new(f.clone())),
Extern::Global(f) => ExternHost::Global(HostRef::new(f.clone())),
Extern::Memory(f) => ExternHost::Memory(HostRef::new(f.clone())),
Extern::Table(f) => ExternHost::Table(HostRef::new(f.clone())),
})
.collect()
});
let mut buffer = Vec::with_capacity(exports.len());
for e in exports {
let ext = Box::new(wasm_extern_t { which: e.clone() });
buffer.push(Box::into_raw(ext));
}
(*out).set_buffer(buffer);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_module_delete(module: *mut wasm_module_t) {
let _ = Box::from_raw(module);
}
impl wasm_name_t {
fn from_name(name: &str) -> wasm_name_t {
name.to_string().into_bytes().into()
}
}
/// Note that this function does not perform validation on the wasm
/// binary. To perform validation, use `wasm_module_validate`.
#[no_mangle]
pub unsafe extern "C" fn wasm_module_new(
store: *mut wasm_store_t,
binary: *const wasm_byte_vec_t,
) -> *mut wasm_module_t {
let binary = (*binary).as_slice();
let store = &(*store).store.borrow();
let module = match Module::from_binary(store, binary) {
Ok(module) => module,
Err(_) => return ptr::null_mut(),
};
let imports = module
.imports()
.iter()
.map(|i| wasm_importtype_t {
ty: i.clone(),
module_cache: None,
name_cache: None,
type_cache: None,
})
.collect::<Vec<_>>();
let exports = module
.exports()
.iter()
.map(|e| wasm_exporttype_t {
ty: e.clone(),
name_cache: None,
type_cache: None,
})
.collect::<Vec<_>>();
let module = Box::new(wasm_module_t {
module: HostRef::new(module),
imports,
exports,
});
Box::into_raw(module)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_module_validate(
store: *mut wasm_store_t,
binary: *const wasm_byte_vec_t,
) -> bool {
let binary = (*binary).as_slice();
let store = &(*store).store.borrow();
Module::validate(store, binary).is_ok()
}
#[no_mangle]
pub unsafe extern "C" fn wasm_store_delete(store: *mut wasm_store_t) {
let _ = Box::from_raw(store);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_store_new(engine: *mut wasm_engine_t) -> *mut wasm_store_t {
let engine = &(*engine).engine;
let store = Box::new(wasm_store_t {
store: HostRef::new(Store::new(&engine.borrow())),
});
Box::into_raw(store)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_valtype_vec_new_empty(out: *mut wasm_valtype_vec_t) {
(*out).set_uninitialized(0);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_valtype_vec_new(
out: *mut wasm_valtype_vec_t,
size: usize,
data: *const *mut wasm_valtype_t,
) {
let slice = slice::from_raw_parts(data, size);
(*out).set_from_slice(slice);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_valtype_vec_new_uninitialized(
out: *mut wasm_valtype_vec_t,
size: usize,
) {
(*out).set_uninitialized(size);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_func_new_with_env(
store: *mut wasm_store_t,
ty: *const wasm_functype_t,
callback: wasm_func_callback_with_env_t,
env: *mut std::ffi::c_void,
finalizer: std::option::Option<unsafe extern "C" fn(arg1: *mut std::ffi::c_void)>,
) -> *mut wasm_func_t {
let store = &(*store).store.borrow();
let ty = (*ty).functype.clone();
let callback = Rc::new(CallbackWithEnv {
callback,
env,
finalizer,
});
let func = Box::new(wasm_func_t {
ext: wasm_extern_t {
which: ExternHost::Func(HostRef::new(Func::new(store, ty, callback))),
},
});
Box::into_raw(func)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_val_copy(out: *mut wasm_val_t, source: *const wasm_val_t) {
*out = match into_valtype((*source).kind) {
ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 => *source,
_ => unimplemented!("wasm_val_copy arg"),
};
}
fn into_valtype(kind: wasm_valkind_t) -> ValType {
match kind {
0 => ValType::I32,
1 => ValType::I64,
2 => ValType::F32,
3 => ValType::F64,
128 => ValType::AnyRef,
129 => ValType::FuncRef,
_ => panic!("unexpected kind: {}", kind),
}
}
fn from_valtype(ty: &ValType) -> wasm_valkind_t {
match ty {
ValType::I32 => 0,
ValType::I64 => 1,
ValType::F32 => 2,
ValType::F64 => 3,
ValType::AnyRef => 128,
ValType::FuncRef => 129,
_ => panic!("wasm_valkind_t has no known conversion for {:?}", ty),
}
}
#[no_mangle]
pub unsafe extern "C" fn wasm_valtype_new(kind: wasm_valkind_t) -> *mut wasm_valtype_t {
let ty = Box::new(wasm_valtype_t {
ty: into_valtype(kind),
});
Box::into_raw(ty)
}
#[no_mangle]
pub unsafe extern "C" fn wasm_valtype_delete(vt: *mut wasm_valtype_t) {
drop(Box::from_raw(vt));
}
#[no_mangle]
pub unsafe extern "C" fn wasm_byte_vec_new(
out: *mut wasm_byte_vec_t,
size: usize,
data: *const wasm_byte_t,
) {
let slice = slice::from_raw_parts(data, size);
(*out).set_from_slice(slice);
}
#[no_mangle]
pub unsafe extern "C" fn wasm_frame_delete(_arg1: *mut wasm_frame_t) {
unimplemented!("wasm_frame_delete")
}
#[no_mangle]
pub unsafe extern "C" fn wasm_frame_func_index(_arg1: *const wasm_frame_t) -> u32 {
unimplemented!("wasm_frame_func_index")
}
#[no_mangle]