wasmer_engine/
resolver.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
//! Define the `Resolver` trait, allowing custom resolution for external
//! references.

use crate::{Engine, ImportError, LinkError};
use more_asserts::assert_ge;
use wasmer_types::entity::{BoxedSlice, EntityRef, PrimaryMap};
use wasmer_types::{ExternType, FunctionIndex, ImportCounts, MemoryType, TableType};

use wasmer_vm::{
    Export, ExportFunctionMetadata, FunctionBodyPtr, ImportFunctionEnv, Imports, MemoryStyle,
    Resolver, VMFunctionBody, VMFunctionEnvironment, VMFunctionImport, VMFunctionKind,
    VMGlobalImport, VMImport, VMImportType, VMMemoryImport, VMTableImport,
};

fn is_compatible_table(ex: &TableType, im: &TableType) -> bool {
    (ex.ty == wasmer_types::Type::FuncRef || ex.ty == im.ty)
        && im.minimum <= ex.minimum
        && (im.maximum.is_none()
            || (!ex.maximum.is_none() && im.maximum.unwrap() >= ex.maximum.unwrap()))
}

fn is_compatible_memory(ex: &MemoryType, im: &MemoryType) -> bool {
    im.minimum <= ex.minimum
        && (im.maximum.is_none()
            || (!ex.maximum.is_none() && im.maximum.unwrap() >= ex.maximum.unwrap()))
        && ex.shared == im.shared
}

/// This function allows to match all imports of a `ModuleInfo` with concrete definitions provided by
/// a `Resolver`.
///
/// If all imports are satisfied returns an `Imports` instance required for a module instantiation.
pub fn resolve_imports(
    engine: &dyn Engine,
    resolver: &dyn Resolver,
    import_counts: &ImportCounts,
    imports: &[VMImport],
    finished_dynamic_function_trampolines: &BoxedSlice<FunctionIndex, FunctionBodyPtr>,
) -> Result<Imports, LinkError> {
    let mut function_imports = PrimaryMap::with_capacity(import_counts.functions as _);
    let mut host_function_env_initializers =
        PrimaryMap::with_capacity(import_counts.functions as _);
    let mut table_imports = PrimaryMap::with_capacity(import_counts.tables as _);
    let mut memory_imports = PrimaryMap::with_capacity(import_counts.memories as _);
    let mut global_imports = PrimaryMap::with_capacity(import_counts.globals as _);
    for VMImport {
        import_no,
        module,
        field,
        ty,
    } in imports
    {
        let resolved = resolver.resolve(*import_no, module, field);
        let import_extern = || match ty {
            &VMImportType::Table(t) => ExternType::Table(t),
            &VMImportType::Memory(t, _) => ExternType::Memory(t),
            &VMImportType::Global(t) => ExternType::Global(t),
            &VMImportType::Function {
                sig,
                static_trampoline: _,
            } => ExternType::Function(
                engine
                    .lookup_signature(sig)
                    .expect("VMSharedSignatureIndex is not valid?"),
            ),
        };
        let resolved = match resolved {
            Some(r) => r,
            None => {
                return Err(LinkError::Import(
                    module.to_string(),
                    field.to_string(),
                    ImportError::UnknownImport(import_extern()),
                ));
            }
        };
        let export_extern = || match resolved {
            Export::Function(ref f) => ExternType::Function(
                engine
                    .lookup_signature(f.vm_function.signature)
                    .expect("VMSharedSignatureIndex not registered with engine (wrong engine?)")
                    .clone(),
            ),
            Export::Table(ref t) => ExternType::Table(*t.ty()),
            Export::Memory(ref m) => ExternType::Memory(m.ty()),
            Export::Global(ref g) => {
                let global = g.from.ty();
                ExternType::Global(*global)
            }
        };
        match (&resolved, ty) {
            (
                Export::Function(ex),
                VMImportType::Function {
                    sig,
                    static_trampoline,
                },
            ) if ex.vm_function.signature == *sig => {
                let address = match ex.vm_function.kind {
                    VMFunctionKind::Dynamic => {
                        // If this is a dynamic imported function,
                        // the address of the function is the address of the
                        // reverse trampoline.
                        let index = FunctionIndex::new(function_imports.len());
                        finished_dynamic_function_trampolines[index].0 as *mut VMFunctionBody as _

                        // TODO: We should check that the f.vmctx actually matches
                        // the shape of `VMDynamicFunctionImportContext`
                    }
                    VMFunctionKind::Static => ex.vm_function.address,
                };

                // Clone the host env for this `Instance`.
                let env = if let Some(ExportFunctionMetadata {
                    host_env_clone_fn: clone,
                    ..
                }) = ex.metadata.as_deref()
                {
                    // TODO: maybe start adding asserts in all these
                    // unsafe blocks to prevent future changes from
                    // horribly breaking things.
                    unsafe {
                        assert!(!ex.vm_function.vmctx.host_env.is_null());
                        (clone)(ex.vm_function.vmctx.host_env)
                    }
                } else {
                    // No `clone` function means we're dealing with some
                    // other kind of `vmctx`, not a host env of any
                    // kind.
                    unsafe { ex.vm_function.vmctx.host_env }
                };

                let trampoline = if let Some(t) = ex.vm_function.call_trampoline {
                    Some(t)
                } else if let VMFunctionKind::Static = ex.vm_function.kind {
                    // Look up a trampoline by finding one by the signature and fill it in.
                    Some(*static_trampoline)
                } else {
                    // FIXME: remove this possibility entirely.
                    None
                };

                function_imports.push(VMFunctionImport {
                    body: FunctionBodyPtr(address),
                    signature: *sig,
                    environment: VMFunctionEnvironment { host_env: env },
                    trampoline,
                });

                let initializer = ex
                    .metadata
                    .as_ref()
                    .and_then(|m| m.import_init_function_ptr);
                let clone = ex.metadata.as_ref().map(|m| m.host_env_clone_fn);
                let destructor = ex.metadata.as_ref().map(|m| m.host_env_drop_fn);
                let import_function_env =
                    if let (Some(clone), Some(destructor)) = (clone, destructor) {
                        ImportFunctionEnv::Env {
                            env,
                            clone,
                            initializer,
                            destructor,
                        }
                    } else {
                        ImportFunctionEnv::NoEnv
                    };

                host_function_env_initializers.push(import_function_env);
            }
            (Export::Table(ex), VMImportType::Table(im)) if is_compatible_table(ex.ty(), im) => {
                let import_table_ty = ex.from.ty();
                if import_table_ty.ty != im.ty {
                    return Err(LinkError::Import(
                        module.to_string(),
                        field.to_string(),
                        ImportError::IncompatibleType(import_extern(), export_extern()),
                    ));
                }
                table_imports.push(VMTableImport {
                    definition: ex.from.vmtable(),
                    from: ex.from.clone(),
                });
            }
            (Export::Memory(ex), VMImportType::Memory(im, import_memory_style))
                if is_compatible_memory(&ex.ty(), im) =>
            {
                // Sanity-check: Ensure that the imported memory has at least
                // guard-page protections the importing module expects it to have.
                let export_memory_style = ex.style();
                if let (
                    MemoryStyle::Static { bound, .. },
                    MemoryStyle::Static {
                        bound: import_bound,
                        ..
                    },
                ) = (export_memory_style.clone(), &import_memory_style)
                {
                    assert_ge!(bound, *import_bound);
                }
                assert_ge!(
                    export_memory_style.offset_guard_size(),
                    import_memory_style.offset_guard_size()
                );
                memory_imports.push(VMMemoryImport {
                    definition: ex.from.vmmemory(),
                    from: ex.from.clone(),
                });
            }

            (Export::Global(ex), VMImportType::Global(im)) if ex.from.ty() == im => {
                global_imports.push(VMGlobalImport {
                    definition: ex.from.vmglobal(),
                    from: ex.from.clone(),
                });
            }
            _ => {
                return Err(LinkError::Import(
                    module.to_string(),
                    field.to_string(),
                    ImportError::IncompatibleType(import_extern(), export_extern()),
                ));
            }
        }
    }
    Ok(Imports::new(
        function_imports,
        host_function_env_initializers,
        table_imports,
        memory_imports,
        global_imports,
    ))
}