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
use crate::error::Error;
use crate::module::{AddrDetails, GlobalSpec, HeapSpec, Module, ModuleInternal, TableElement};
use libc::c_void;
use lucet_module::owned::{
    OwnedExportFunction, OwnedFunctionMetadata, OwnedGlobalSpec, OwnedImportFunction,
    OwnedLinearMemorySpec, OwnedModuleData, OwnedSparseData,
};
use lucet_module::{
    FunctionHandle, FunctionIndex, FunctionPointer, FunctionSpec, ModuleData, ModuleFeatures,
    Signature, TrapSite, UniqueSignatureIndex,
};
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

#[derive(Default)]
pub struct MockModuleBuilder {
    heap_spec: HeapSpec,
    sparse_page_data: Vec<Option<Vec<u8>>>,
    globals: BTreeMap<usize, OwnedGlobalSpec>,
    table_elements: BTreeMap<usize, TableElement>,
    export_funcs: HashMap<&'static str, FunctionPointer>,
    func_table: HashMap<(u32, u32), FunctionPointer>,
    start_func: Option<FunctionPointer>,
    function_manifest: Vec<FunctionSpec>,
    function_info: Vec<OwnedFunctionMetadata>,
    imports: Vec<OwnedImportFunction>,
    exports: Vec<OwnedExportFunction>,
    signatures: Vec<Signature>,
}

impl MockModuleBuilder {
    pub fn new() -> Self {
        const DEFAULT_HEAP_SPEC: HeapSpec = HeapSpec {
            reserved_size: 4 * 1024 * 1024,
            guard_size: 4 * 1024 * 1024,
            initial_size: 64 * 1024,
            max_size: Some(64 * 1024),
        };
        MockModuleBuilder::default().with_heap_spec(DEFAULT_HEAP_SPEC)
    }

    pub fn with_heap_spec(mut self, heap_spec: HeapSpec) -> Self {
        self.heap_spec = heap_spec;
        self
    }

    pub fn with_initial_heap(mut self, heap: &[u8]) -> Self {
        self.sparse_page_data = heap
            .chunks(4096)
            .map(|page| {
                if page.iter().all(|b| *b == 0) {
                    None
                } else {
                    let mut page = page.to_vec();
                    if page.len() < 4096 {
                        page.resize(4096, 0);
                    }
                    Some(page)
                }
            })
            .collect();
        self
    }

    pub fn with_global(mut self, idx: u32, init_val: i64) -> Self {
        self.globals
            .insert(idx as usize, OwnedGlobalSpec::new_def(init_val, vec![]));
        self
    }

    pub fn with_exported_global(mut self, idx: u32, init_val: i64, export_name: &str) -> Self {
        self.globals.insert(
            idx as usize,
            OwnedGlobalSpec::new_def(init_val, vec![export_name.to_string()]),
        );
        self
    }

    pub fn with_import(mut self, idx: u32, import_module: &str, import_field: &str) -> Self {
        self.globals.insert(
            idx as usize,
            OwnedGlobalSpec::new_import(
                import_module.to_string(),
                import_field.to_string(),
                vec![],
            ),
        );
        self
    }

    pub fn with_exported_import(
        mut self,
        idx: u32,
        import_module: &str,
        import_field: &str,
        export_name: &str,
    ) -> Self {
        self.globals.insert(
            idx as usize,
            OwnedGlobalSpec::new_import(
                import_module.to_string(),
                import_field.to_string(),
                vec![export_name.to_string()],
            ),
        );
        self
    }

    pub fn with_table_element(mut self, idx: u32, element: &TableElement) -> Self {
        self.table_elements.insert(idx as usize, element.clone());
        self
    }

    fn record_sig(&mut self, sig: Signature) -> UniqueSignatureIndex {
        let idx = self
            .signatures
            .iter()
            .enumerate()
            .find(|(_, v)| *v == &sig)
            .map(|(key, _)| key)
            .unwrap_or_else(|| {
                self.signatures.push(sig);
                self.signatures.len() - 1
            });
        UniqueSignatureIndex::from_u32(idx as u32)
    }

    pub fn with_export_func(mut self, export: MockExportBuilder) -> Self {
        self.export_funcs.insert(export.sym(), export.func());
        let sig_idx = self.record_sig(export.sig());
        self.function_info.push(OwnedFunctionMetadata {
            signature: sig_idx,
            name: Some(export.sym().to_string()),
        });
        self.exports.push(OwnedExportFunction {
            fn_idx: FunctionIndex::from_u32(self.function_manifest.len() as u32),
            names: vec![export.sym().to_string()],
        });
        self.function_manifest.push(FunctionSpec::new(
            export.func().as_usize() as u64,
            export.func_len() as u32,
            export.traps().as_ptr() as u64,
            export.traps().len() as u64,
        ));
        self
    }

    pub fn with_exported_import_func(
        mut self,
        export_name: &'static str,
        import_fn_ptr: FunctionPointer,
        sig: Signature,
    ) -> Self {
        self.export_funcs.insert(export_name, import_fn_ptr);
        let sig_idx = self.record_sig(sig);
        self.function_info.push(OwnedFunctionMetadata {
            signature: sig_idx,
            name: Some(export_name.to_string()),
        });
        self.exports.push(OwnedExportFunction {
            fn_idx: FunctionIndex::from_u32(self.function_manifest.len() as u32),
            names: vec![export_name.to_string()],
        });
        self.function_manifest.push(FunctionSpec::new(
            import_fn_ptr.as_usize() as u64,
            0u32,
            0u64,
            0u64,
        ));
        self
    }

    pub fn with_table_func(mut self, table_idx: u32, func_idx: u32, func: FunctionPointer) -> Self {
        self.func_table.insert((table_idx, func_idx), func);
        self
    }

    pub fn with_start_func(mut self, func: FunctionPointer) -> Self {
        self.start_func = Some(func);
        self
    }

    pub fn build(self) -> Arc<dyn Module> {
        assert!(
            self.sparse_page_data.len() * 4096 <= self.heap_spec.initial_size as usize,
            "heap must fit in heap spec initial size"
        );

        let table_elements = self
            .table_elements
            .into_iter()
            .enumerate()
            .map(|(expected_idx, (idx, te))| {
                assert_eq!(
                    idx, expected_idx,
                    "table element indices must be contiguous starting from 0"
                );
                te
            })
            .collect();
        let globals_spec = self
            .globals
            .into_iter()
            .enumerate()
            .map(|(expected_idx, (idx, gs))| {
                assert_eq!(
                    idx, expected_idx,
                    "global indices must be contiguous starting from 0"
                );
                gs
            })
            .collect();
        let owned_module_data = OwnedModuleData::new(
            Some(OwnedLinearMemorySpec {
                heap: self.heap_spec,
                initializer: OwnedSparseData::new(self.sparse_page_data)
                    .expect("sparse data pages are valid"),
            }),
            globals_spec,
            self.function_info.clone(),
            self.imports,
            self.exports,
            self.signatures,
            ModuleFeatures::none(),
        );
        let serialized_module_data = owned_module_data
            .to_ref()
            .serialize()
            .expect("serialization of module_data succeeds");
        let module_data = ModuleData::deserialize(&serialized_module_data)
            .map(|md| unsafe { std::mem::transmute(md) })
            .expect("module data can be deserialized");
        let mock = MockModule {
            serialized_module_data,
            module_data,
            table_elements,
            export_funcs: self.export_funcs,
            func_table: self.func_table,
            start_func: self.start_func,
            function_manifest: self.function_manifest,
        };
        Arc::new(mock)
    }
}

pub struct MockModule {
    #[allow(dead_code)]
    serialized_module_data: Vec<u8>,
    module_data: ModuleData<'static>,
    pub table_elements: Vec<TableElement>,
    pub export_funcs: HashMap<&'static str, FunctionPointer>,
    pub func_table: HashMap<(u32, u32), FunctionPointer>,
    pub start_func: Option<FunctionPointer>,
    pub function_manifest: Vec<FunctionSpec>,
}

unsafe impl Send for MockModule {}
unsafe impl Sync for MockModule {}

impl Module for MockModule {}

impl ModuleInternal for MockModule {
    fn heap_spec(&self) -> Option<&HeapSpec> {
        self.module_data.heap_spec()
    }

    fn globals(&self) -> &[GlobalSpec<'_>] {
        self.module_data.globals_spec()
    }

    fn get_sparse_page_data(&self, page: usize) -> Option<&[u8]> {
        if let Some(ref sparse_data) = self.module_data.sparse_data() {
            *sparse_data.get_page(page)
        } else {
            None
        }
    }

    fn sparse_page_data_len(&self) -> usize {
        self.module_data.sparse_data().map(|d| d.len()).unwrap_or(0)
    }

    fn table_elements(&self) -> Result<&[TableElement], Error> {
        Ok(&self.table_elements)
    }

    fn get_export_func(&self, sym: &str) -> Result<FunctionHandle, Error> {
        let ptr = *self
            .export_funcs
            .get(sym)
            .ok_or(Error::SymbolNotFound(sym.to_string()))?;

        Ok(self.function_handle_from_ptr(ptr))
    }

    fn get_func_from_idx(&self, table_id: u32, func_id: u32) -> Result<FunctionHandle, Error> {
        let ptr = self
            .func_table
            .get(&(table_id, func_id))
            .cloned()
            .ok_or(Error::FuncNotFound(table_id, func_id))?;

        Ok(self.function_handle_from_ptr(ptr))
    }

    fn get_start_func(&self) -> Result<Option<FunctionHandle>, Error> {
        Ok(self
            .start_func
            .map(|start| self.function_handle_from_ptr(start)))
    }

    fn function_manifest(&self) -> &[FunctionSpec] {
        &self.function_manifest
    }

    fn addr_details(&self, _addr: *const c_void) -> Result<Option<AddrDetails>, Error> {
        // we can call `dladdr` on Rust code, but unless we inspect the stack I don't think there's
        // a way to determine whether or not we're in "module" code; punt for now
        Ok(None)
    }

    fn get_signature(&self, fn_id: FunctionIndex) -> &Signature {
        self.module_data.get_signature(fn_id)
    }
}

pub struct MockExportBuilder {
    sym: &'static str,
    func: FunctionPointer,
    func_len: Option<usize>,
    traps: Option<&'static [TrapSite]>,
    sig: Signature,
}

impl MockExportBuilder {
    pub fn new(name: &'static str, func: FunctionPointer) -> MockExportBuilder {
        MockExportBuilder {
            sym: name,
            func: func,
            func_len: None,
            traps: None,
            sig: Signature {
                params: vec![],
                ret_ty: None,
            },
        }
    }

    pub fn with_func_len(mut self, len: usize) -> MockExportBuilder {
        self.func_len = Some(len);
        self
    }

    pub fn with_traps(mut self, traps: &'static [TrapSite]) -> MockExportBuilder {
        self.traps = Some(traps);
        self
    }

    pub fn with_sig(mut self, sig: Signature) -> MockExportBuilder {
        self.sig = sig;
        self
    }

    pub fn sym(&self) -> &'static str {
        self.sym
    }
    pub fn func(&self) -> FunctionPointer {
        self.func
    }
    pub fn func_len(&self) -> usize {
        self.func_len.unwrap_or(1)
    }
    pub fn traps(&self) -> &'static [TrapSite] {
        self.traps.unwrap_or(&[])
    }
    pub fn sig(&self) -> Signature {
        self.sig.clone()
    }
}