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
use super::create_handle::create_handle;
use crate::trampoline::StoreInstanceHandle;
use crate::{GlobalType, Mutability, Store, Val};
use anyhow::Result;
use wasmtime_environ::entity::PrimaryMap;
use wasmtime_environ::{
    wasm::{self, SignatureIndex},
    Module, ModuleType,
};
use wasmtime_runtime::VMFunctionImport;

pub fn create_global(store: &Store, gt: &GlobalType, val: Val) -> Result<StoreInstanceHandle> {
    let mut module = Module::new();
    let mut func_imports = Vec::new();
    let mut externref_init = None;
    let mut shared_signature_id = None;

    let global = wasm::Global {
        wasm_ty: gt.content().to_wasm_type(),
        ty: gt.content().get_wasmtime_type(),
        mutability: match gt.mutability() {
            Mutability::Const => false,
            Mutability::Var => true,
        },
        initializer: match val {
            Val::I32(i) => wasm::GlobalInit::I32Const(i),
            Val::I64(i) => wasm::GlobalInit::I64Const(i),
            Val::F32(f) => wasm::GlobalInit::F32Const(f),
            Val::F64(f) => wasm::GlobalInit::F64Const(f),
            Val::ExternRef(None) | Val::FuncRef(None) => wasm::GlobalInit::RefNullConst,
            Val::ExternRef(Some(x)) => {
                // There is no `GlobalInit` variant for using an existing
                // `externref` that isn't an import (because Wasm can't create
                // an `externref` by itself). Therefore, initialize the global
                // as null, and then monkey patch it after instantiation below.
                externref_init = Some(x);
                wasm::GlobalInit::RefNullConst
            }
            Val::FuncRef(Some(f)) => {
                // Add a function import to the stub module, and then initialize
                // our global with a `ref.func` to grab that imported function.
                let shared_sig_index = f.sig_index();
                shared_signature_id = Some(shared_sig_index);
                let sig_id = SignatureIndex::from_u32(u32::max_value() - 1);
                module.types.push(ModuleType::Function(sig_id));
                let func_index = module.functions.push(sig_id);
                module.num_imported_funcs = 1;
                module
                    .initializers
                    .push(wasmtime_environ::Initializer::Import {
                        module: "".into(),
                        field: None,
                        index: wasm::EntityIndex::Function(func_index),
                    });

                let f = f.caller_checked_anyfunc();
                let f = unsafe { f.as_ref() };
                func_imports.push(VMFunctionImport {
                    body: f.func_ptr,
                    vmctx: f.vmctx,
                });

                wasm::GlobalInit::RefFunc(func_index)
            }
            _ => unimplemented!("create_global for {:?}", gt),
        },
    };

    let global_id = module.globals.push(global);
    module
        .exports
        .insert(String::new(), wasm::EntityIndex::Global(global_id));
    let handle = create_handle(
        module,
        store,
        PrimaryMap::new(),
        Box::new(()),
        &func_imports,
        shared_signature_id,
    )?;

    if let Some(x) = externref_init {
        match handle.lookup("").unwrap() {
            wasmtime_runtime::Export::Global(g) => unsafe {
                *(*g.definition).as_externref_mut() = Some(x.inner);
            },
            _ => unreachable!(),
        }
    }

    Ok(handle)
}