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
use crate::callable::{Callable, NativeCallable, WasmtimeFn, WrappedCallable};
use crate::r#ref::{AnyRef, HostRef};
use crate::runtime::Store;
use crate::trampoline::{generate_global_export, generate_memory_export, generate_table_export};
use crate::trap::Trap;
use crate::types::{ExternType, FuncType, GlobalType, MemoryType, TableType, ValType};
use crate::values::{from_checked_anyfunc, into_checked_anyfunc, Val};
use std::fmt;
use std::rc::Rc;
use std::slice;
use wasmtime_runtime::InstanceHandle;

// Externals

#[derive(Clone)]
pub enum Extern {
    Func(HostRef<Func>),
    Global(HostRef<Global>),
    Table(HostRef<Table>),
    Memory(HostRef<Memory>),
}

impl Extern {
    pub fn func(&self) -> Option<&HostRef<Func>> {
        match self {
            Extern::Func(func) => Some(func),
            _ => None,
        }
    }
    pub fn global(&self) -> Option<&HostRef<Global>> {
        match self {
            Extern::Global(global) => Some(global),
            _ => None,
        }
    }
    pub fn table(&self) -> Option<&HostRef<Table>> {
        match self {
            Extern::Table(table) => Some(table),
            _ => None,
        }
    }
    pub fn memory(&self) -> Option<&HostRef<Memory>> {
        match self {
            Extern::Memory(memory) => Some(memory),
            _ => None,
        }
    }

    pub fn r#type(&self) -> ExternType {
        match self {
            Extern::Func(ft) => ExternType::ExternFunc(ft.borrow().r#type().clone()),
            Extern::Memory(ft) => ExternType::ExternMemory(ft.borrow().r#type().clone()),
            Extern::Table(tt) => ExternType::ExternTable(tt.borrow().r#type().clone()),
            Extern::Global(gt) => ExternType::ExternGlobal(gt.borrow().r#type().clone()),
        }
    }

    pub(crate) fn get_wasmtime_export(&mut self) -> wasmtime_runtime::Export {
        match self {
            Extern::Func(f) => f.borrow().wasmtime_export().clone(),
            Extern::Global(g) => g.borrow().wasmtime_export().clone(),
            Extern::Memory(m) => m.borrow().wasmtime_export().clone(),
            Extern::Table(t) => t.borrow().wasmtime_export().clone(),
        }
    }

    pub(crate) fn from_wasmtime_export(
        store: &HostRef<Store>,
        instance_handle: InstanceHandle,
        export: wasmtime_runtime::Export,
    ) -> Extern {
        match export {
            wasmtime_runtime::Export::Function { .. } => Extern::Func(HostRef::new(
                Func::from_wasmtime_function(export, store, instance_handle),
            )),
            wasmtime_runtime::Export::Memory { .. } => Extern::Memory(HostRef::new(
                Memory::from_wasmtime_memory(export, store, instance_handle),
            )),
            wasmtime_runtime::Export::Global { .. } => {
                Extern::Global(HostRef::new(Global::from_wasmtime_global(export, store)))
            }
            wasmtime_runtime::Export::Table { .. } => Extern::Table(HostRef::new(
                Table::from_wasmtime_table(export, store, instance_handle),
            )),
        }
    }
}

impl From<HostRef<Func>> for Extern {
    fn from(r: HostRef<Func>) -> Self {
        Extern::Func(r)
    }
}

impl From<HostRef<Global>> for Extern {
    fn from(r: HostRef<Global>) -> Self {
        Extern::Global(r)
    }
}

impl From<HostRef<Memory>> for Extern {
    fn from(r: HostRef<Memory>) -> Self {
        Extern::Memory(r)
    }
}

impl From<HostRef<Table>> for Extern {
    fn from(r: HostRef<Table>) -> Self {
        Extern::Table(r)
    }
}

pub struct Func {
    _store: HostRef<Store>,
    callable: Rc<dyn WrappedCallable + 'static>,
    r#type: FuncType,
}

impl Func {
    pub fn new(store: &HostRef<Store>, ty: FuncType, callable: Rc<dyn Callable + 'static>) -> Self {
        let callable = Rc::new(NativeCallable::new(callable, &ty, &store));
        Func::from_wrapped(store, ty, callable)
    }

    fn from_wrapped(
        store: &HostRef<Store>,
        r#type: FuncType,
        callable: Rc<dyn WrappedCallable + 'static>,
    ) -> Func {
        Func {
            _store: store.clone(),
            callable,
            r#type,
        }
    }

    pub fn r#type(&self) -> &FuncType {
        &self.r#type
    }

    pub fn param_arity(&self) -> usize {
        self.r#type.params().len()
    }

    pub fn result_arity(&self) -> usize {
        self.r#type.results().len()
    }

    pub fn call(&self, params: &[Val]) -> Result<Box<[Val]>, HostRef<Trap>> {
        let mut results = vec![Val::default(); self.result_arity()];
        self.callable.call(params, &mut results)?;
        Ok(results.into_boxed_slice())
    }

    pub(crate) fn wasmtime_export(&self) -> &wasmtime_runtime::Export {
        self.callable.wasmtime_export()
    }

    pub(crate) fn from_wasmtime_function(
        export: wasmtime_runtime::Export,
        store: &HostRef<Store>,
        instance_handle: InstanceHandle,
    ) -> Self {
        let ty = if let wasmtime_runtime::Export::Function { signature, .. } = &export {
            FuncType::from_cranelift_signature(signature.clone())
        } else {
            panic!("expected function export")
        };
        let callable = WasmtimeFn::new(store, instance_handle, export.clone());
        Func::from_wrapped(store, ty, Rc::new(callable))
    }
}

impl fmt::Debug for Func {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Func")
    }
}

pub struct Global {
    _store: HostRef<Store>,
    r#type: GlobalType,
    wasmtime_export: wasmtime_runtime::Export,
    #[allow(dead_code)]
    wasmtime_state: Option<crate::trampoline::GlobalState>,
}

impl Global {
    pub fn new(store: &HostRef<Store>, r#type: GlobalType, val: Val) -> Global {
        let (wasmtime_export, wasmtime_state) =
            generate_global_export(&r#type, val).expect("generated global");
        Global {
            _store: store.clone(),
            r#type,
            wasmtime_export,
            wasmtime_state: Some(wasmtime_state),
        }
    }

    pub fn r#type(&self) -> &GlobalType {
        &self.r#type
    }

    fn wasmtime_global_definition(&self) -> *mut wasmtime_runtime::VMGlobalDefinition {
        match self.wasmtime_export {
            wasmtime_runtime::Export::Global { definition, .. } => definition,
            _ => panic!("global definition not found"),
        }
    }

    pub fn get(&self) -> Val {
        let definition = unsafe { &mut *self.wasmtime_global_definition() };
        unsafe {
            match self.r#type().content() {
                ValType::I32 => Val::from(*definition.as_i32()),
                ValType::I64 => Val::from(*definition.as_i64()),
                ValType::F32 => Val::from_f32_bits(*definition.as_u32()),
                ValType::F64 => Val::from_f64_bits(*definition.as_u64()),
                _ => unimplemented!("Global::get for {:?}", self.r#type().content()),
            }
        }
    }

    pub fn set(&mut self, val: Val) {
        if val.r#type() != *self.r#type().content() {
            panic!(
                "global of type {:?} cannot be set to {:?}",
                self.r#type().content(),
                val.r#type()
            );
        }
        let definition = unsafe { &mut *self.wasmtime_global_definition() };
        unsafe {
            match val {
                Val::I32(i) => *definition.as_i32_mut() = i,
                Val::I64(i) => *definition.as_i64_mut() = i,
                Val::F32(f) => *definition.as_u32_mut() = f,
                Val::F64(f) => *definition.as_u64_mut() = f,
                _ => unimplemented!("Global::set for {:?}", val.r#type()),
            }
        }
    }

    pub(crate) fn wasmtime_export(&self) -> &wasmtime_runtime::Export {
        &self.wasmtime_export
    }

    pub(crate) fn from_wasmtime_global(
        export: wasmtime_runtime::Export,
        store: &HostRef<Store>,
    ) -> Global {
        let global = if let wasmtime_runtime::Export::Global { ref global, .. } = export {
            global
        } else {
            panic!("wasmtime export is not memory")
        };
        let ty = GlobalType::from_cranelift_global(&global);
        Global {
            _store: store.clone(),
            r#type: ty,
            wasmtime_export: export,
            wasmtime_state: None,
        }
    }
}

pub struct Table {
    store: HostRef<Store>,
    r#type: TableType,
    wasmtime_handle: InstanceHandle,
    wasmtime_export: wasmtime_runtime::Export,
}

fn get_table_item(
    handle: &InstanceHandle,
    store: &HostRef<Store>,
    table_index: cranelift_wasm::DefinedTableIndex,
    item_index: u32,
) -> Val {
    if let Some(item) = handle.table_get(table_index, item_index) {
        from_checked_anyfunc(item, store)
    } else {
        AnyRef::null().into()
    }
}

fn set_table_item(
    handle: &mut InstanceHandle,
    store: &HostRef<Store>,
    table_index: cranelift_wasm::DefinedTableIndex,
    item_index: u32,
    val: Val,
) -> bool {
    let item = into_checked_anyfunc(val, store);
    if let Some(item_ref) = handle.table_get_mut(table_index, item_index) {
        *item_ref = item;
        true
    } else {
        false
    }
}

impl Table {
    pub fn new(store: &HostRef<Store>, r#type: TableType, init: Val) -> Table {
        match r#type.element() {
            ValType::FuncRef => (),
            _ => panic!("table is not for funcref"),
        }
        let (mut wasmtime_handle, wasmtime_export) =
            generate_table_export(&r#type).expect("generated table");

        // Initialize entries with the init value.
        match wasmtime_export {
            wasmtime_runtime::Export::Table { definition, .. } => {
                let index = wasmtime_handle.table_index(unsafe { &*definition });
                let len = unsafe { (*definition).current_elements };
                for i in 0..len {
                    let _success =
                        set_table_item(&mut wasmtime_handle, store, index, i, init.clone());
                    assert!(_success);
                }
            }
            _ => panic!("global definition not found"),
        }

        Table {
            store: store.clone(),
            r#type,
            wasmtime_handle,
            wasmtime_export,
        }
    }

    pub fn r#type(&self) -> &TableType {
        &self.r#type
    }

    fn wasmtime_table_index(&self) -> cranelift_wasm::DefinedTableIndex {
        match self.wasmtime_export {
            wasmtime_runtime::Export::Table { definition, .. } => {
                self.wasmtime_handle.table_index(unsafe { &*definition })
            }
            _ => panic!("global definition not found"),
        }
    }

    pub fn get(&self, index: u32) -> Val {
        let table_index = self.wasmtime_table_index();
        get_table_item(&self.wasmtime_handle, &self.store, table_index, index)
    }

    pub fn set(&self, index: u32, val: Val) -> bool {
        let table_index = self.wasmtime_table_index();
        let mut wasmtime_handle = self.wasmtime_handle.clone();
        set_table_item(&mut wasmtime_handle, &self.store, table_index, index, val)
    }

    pub fn size(&self) -> u32 {
        match self.wasmtime_export {
            wasmtime_runtime::Export::Table { definition, .. } => unsafe {
                (*definition).current_elements
            },
            _ => panic!("global definition not found"),
        }
    }

    pub fn grow(&mut self, delta: u32, init: Val) -> bool {
        let index = self.wasmtime_table_index();
        if let Some(len) = self.wasmtime_handle.table_grow(index, delta) {
            let mut wasmtime_handle = self.wasmtime_handle.clone();
            for i in 0..delta {
                let i = len - (delta - i);
                let _success =
                    set_table_item(&mut wasmtime_handle, &self.store, index, i, init.clone());
                assert!(_success);
            }
            true
        } else {
            false
        }
    }

    pub(crate) fn wasmtime_export(&self) -> &wasmtime_runtime::Export {
        &self.wasmtime_export
    }

    pub(crate) fn from_wasmtime_table(
        export: wasmtime_runtime::Export,
        store: &HostRef<Store>,
        instance_handle: wasmtime_runtime::InstanceHandle,
    ) -> Table {
        let table = if let wasmtime_runtime::Export::Table { ref table, .. } = export {
            table
        } else {
            panic!("wasmtime export is not table")
        };
        let ty = TableType::from_cranelift_table(&table.table);
        Table {
            store: store.clone(),
            r#type: ty,
            wasmtime_handle: instance_handle,
            wasmtime_export: export,
        }
    }
}

pub struct Memory {
    _store: HostRef<Store>,
    r#type: MemoryType,
    wasmtime_handle: InstanceHandle,
    wasmtime_export: wasmtime_runtime::Export,
}

impl Memory {
    pub fn new(store: &HostRef<Store>, r#type: MemoryType) -> Memory {
        let (wasmtime_handle, wasmtime_export) =
            generate_memory_export(&r#type).expect("generated memory");
        Memory {
            _store: store.clone(),
            r#type,
            wasmtime_handle,
            wasmtime_export,
        }
    }

    pub fn r#type(&self) -> &MemoryType {
        &self.r#type
    }

    fn wasmtime_memory_definition(&self) -> *mut wasmtime_runtime::VMMemoryDefinition {
        match self.wasmtime_export {
            wasmtime_runtime::Export::Memory { definition, .. } => definition,
            _ => panic!("memory definition not found"),
        }
    }

    // Marked unsafe due to posibility that wasmtime can resize internal memory
    // from other threads.
    pub unsafe fn data(&self) -> &mut [u8] {
        let definition = &*self.wasmtime_memory_definition();
        slice::from_raw_parts_mut(definition.base, definition.current_length)
    }

    pub fn data_ptr(&self) -> *mut u8 {
        unsafe { (*self.wasmtime_memory_definition()).base }
    }

    pub fn data_size(&self) -> usize {
        unsafe { (*self.wasmtime_memory_definition()).current_length }
    }

    pub fn size(&self) -> u32 {
        (self.data_size() / wasmtime_environ::WASM_PAGE_SIZE as usize) as u32
    }

    pub fn grow(&mut self, delta: u32) -> bool {
        match self.wasmtime_export {
            wasmtime_runtime::Export::Memory { definition, .. } => {
                let definition = unsafe { &(*definition) };
                let index = self.wasmtime_handle.memory_index(definition);
                self.wasmtime_handle.memory_grow(index, delta).is_some()
            }
            _ => panic!("memory definition not found"),
        }
    }

    pub(crate) fn wasmtime_export(&self) -> &wasmtime_runtime::Export {
        &self.wasmtime_export
    }

    pub(crate) fn from_wasmtime_memory(
        export: wasmtime_runtime::Export,
        store: &HostRef<Store>,
        instance_handle: wasmtime_runtime::InstanceHandle,
    ) -> Memory {
        let memory = if let wasmtime_runtime::Export::Memory { ref memory, .. } = export {
            memory
        } else {
            panic!("wasmtime export is not memory")
        };
        let ty = MemoryType::from_cranelift_memory(&memory.memory);
        Memory {
            _store: store.clone(),
            r#type: ty,
            wasmtime_handle: instance_handle,
            wasmtime_export: export,
        }
    }
}