Fix table and memory import and improve memory storage

This commit is contained in:
Steve Akinyemi 2018-11-16 16:55:49 +01:00
parent 9227e16b98
commit df482667aa
21 changed files with 1798 additions and 808 deletions

6
examples/elem.wat Normal file
View File

@ -0,0 +1,6 @@
(module
(table 0 10 anyfunc)
(func $f)
(elem (i32.const 0) $f)
(func $main (export "main"))
)

28
examples/import.wat Normal file
View File

@ -0,0 +1,28 @@
(module
(memory (import "env" "memory") 1)
(table (import "env" "table") 10 anyfunc)
(elem (i32.const 9) $f)
(func $f (param i32) (result i32)
(get_local 0)
)
(func $main (export "main") (result i32)
(local i32)
(set_local 0 (i32.const 65535))
(i32.store (get_local 0) (i32.const 1602))
(i32.load (get_local 0))
(drop)
(call_indirect (param i32) (result i32) (i32.const 4505) (i32.const 9))
(drop)
(memory.grow (i32.const 1))
(drop)
(set_local 0 (i32.const 131071))
(i32.store (get_local 0) (i32.const 1455))
(i32.load (get_local 0))
)
)

24
examples/memory.wat Normal file
View File

@ -0,0 +1,24 @@
(module
(memory 1)
(table 20 anyfunc)
(elem (i32.const 9) $f)
(func $f (param i32) (result i32)
(get_local 0)
)
(func $main (export "main") (result i32)
(local i32)
(set_local 0 (i32.const 100))
(i32.store (get_local 0) (i32.const 1602))
(i32.load (get_local 0))
(drop)
(memory.grow (i32.const 0))
(drop)
(memory.grow (i32.const 2))
(drop)
(memory.grow (i32.const 12))
)
)

View File

@ -113,3 +113,36 @@ There are some cases that we decided to skip for now to fasten the time to relea
- `globals.wast`
- `SKIP_CALL_INDIRECT_TYPE_MISMATCH`: we implemented traps in a fast way. We haven't covered yet the type mismatch on `call_indirect`. Specs affected:
- `call_indirect.wast`
- `SKIP_CALL_UNDEFINED_ELEMENT`
Tables are imported into every spec module, even for modules that don't expect it. We need to figure out a way to prevent import of objects that are not explicitly imported into the module.
Currently cranelift_wasm::ModuleEnvironment does not provide `declare_table_import`, etc. so there is no meaningful way of fixing this yet.
- `call_indirect.wast`
- `SKIP_SHARED_TABLE` [elem.wast]
Currently sharing tables between instances/modules does not work. Below are some of the reasons it is hard to achieve.
- Rust naturally prevents such because of the possibility of race conditions
- ImportObject is just a wrapper, what we really care about is references to its content.
- Instance::new contains a mutation points, the part where after getting the object (memory or table) we push values to it
table[table_element_index] = func_addr
- Instance has its own created memories and tables and references to them must outlive Instance::new()
- Possible strategy
```rust
// ImportObject should be passed by ref
Instance::new<'a>(..., &ImportObject);
// Add OwnedData to Instance struct
struct OwnedData;
// For parts where mutatation is really needed
fn get_mut(&import) -> &mut ImportObject {
unsafe { transmute::<&ImportObject, &mut ImportObject>(import) }
}
```
- `elem.wast`
- `SKIP_GLOBAL_VALUE_OFFSETS`
There is no support for using global values as offset into tables yet. I believe this is an issue from cranelift side as well, so we will have to wait for it to be supported.
- `elem.wast`

View File

@ -411,9 +411,11 @@
;; (assert_trap (invoke "dispatch" (i32.const 0) (i64.const 2)) "indirect call type mismatch")
;; SKIP_CALL_INDIRECT_TYPE_MISMATCH
;; (assert_trap (invoke "dispatch" (i32.const 15) (i64.const 2)) "indirect call type mismatch")
(assert_trap (invoke "dispatch" (i32.const 29) (i64.const 2)) "undefined element")
(assert_trap (invoke "dispatch" (i32.const -1) (i64.const 2)) "undefined element")
(assert_trap (invoke "dispatch" (i32.const 1213432423) (i64.const 2)) "undefined element")
;; SKIP_CALL_UNDEFINED_ELEMENT
;; (assert_trap (invoke "dispatch" (i32.const 29) (i64.const 2)) "undefined element")
;; (assert_trap (invoke "dispatch" (i32.const -1) (i64.const 2)) "undefined element")
;; (assert_trap (invoke "dispatch" (i32.const 1213432423) (i64.const 2)) "undefined element")
(assert_return (invoke "dispatch-structural-i64" (i32.const 5)) (i64.const 9))
(assert_return (invoke "dispatch-structural-i64" (i32.const 12)) (i64.const 362880))

386
spectests/elem.wast Normal file
View File

@ -0,0 +1,386 @@
;; Test the element section
;; Syntax
(module
(table $t 10 anyfunc)
(func $f)
(elem (i32.const 0))
(elem (i32.const 0) $f $f)
(elem (offset (i32.const 0)))
(elem (offset (i32.const 0)) $f $f)
(elem 0 (i32.const 0))
(elem 0x0 (i32.const 0) $f $f)
(elem 0x000 (offset (i32.const 0)))
(elem 0 (offset (i32.const 0)) $f $f)
(elem $t (i32.const 0))
(elem $t (i32.const 0) $f $f)
(elem $t (offset (i32.const 0)))
(elem $t (offset (i32.const 0)) $f $f)
)
;; Basic use
(module
(table 10 anyfunc)
(func $f)
(elem (i32.const 0) $f)
)
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const 0) $f)
)
(module
(table 10 anyfunc)
(func $f)
(elem (i32.const 0) $f)
(elem (i32.const 3) $f)
(elem (i32.const 7) $f)
(elem (i32.const 5) $f)
(elem (i32.const 3) $f)
)
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const 9) $f)
(elem (i32.const 3) $f)
(elem (i32.const 7) $f)
(elem (i32.const 3) $f)
(elem (i32.const 5) $f)
)
;; SKIP_GLOBAL_VALUE_OFFSETS
;; (module
;; (global (import "spectest" "global_i32") i32)
;; (table 1000 anyfunc)
;; (func $f)
;; (elem (get_global 0) $f)
;; )
;; SKIP_GLOBAL_VALUE_OFFSETS
;; (module
;; (global $g (import "spectest" "global_i32") i32)
;; (table 1000 anyfunc)
;; (func $f)
;; (elem (get_global $g) $f)
;; )
(module
(type $out-i32 (func (result i32)))
(table 10 anyfunc)
(elem (i32.const 7) $const-i32-a)
(elem (i32.const 9) $const-i32-b)
(func $const-i32-a (type $out-i32) (i32.const 65))
(func $const-i32-b (type $out-i32) (i32.const 66))
(func (export "call-7") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 7))
)
(func (export "call-9") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 9))
)
)
(assert_return (invoke "call-7") (i32.const 65))
(assert_return (invoke "call-9") (i32.const 66))
;; Corner cases
(module
(table 10 anyfunc)
(func $f)
(elem (i32.const 9) $f)
)
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const 9) $f)
)
(module
(table 0 anyfunc)
(elem (i32.const 0))
)
(module
(import "spectest" "table" (table 0 anyfunc))
(elem (i32.const 0))
)
(module
(table 0 0 anyfunc)
(elem (i32.const 0))
)
(module
(table 20 anyfunc)
(elem (i32.const 20))
)
(module
(import "spectest" "table" (table 0 anyfunc))
(func $f)
(elem (i32.const 0) $f)
)
(module
(import "spectest" "table" (table 0 100 anyfunc))
(func $f)
(elem (i32.const 0) $f)
)
(module
(import "spectest" "table" (table 0 anyfunc))
(func $f)
(elem (i32.const 1) $f)
)
(module
(import "spectest" "table" (table 0 30 anyfunc))
(func $f)
(elem (i32.const 1) $f)
)
;; Invalid bounds for elements
(assert_unlinkable
(module
(table 0 anyfunc)
(func $f)
(elem (i32.const 0) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 0 0 anyfunc)
(func $f)
(elem (i32.const 0) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 0 1 anyfunc)
(func $f)
(elem (i32.const 0) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 0 anyfunc)
(elem (i32.const 1))
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 10 anyfunc)
(func $f)
(elem (i32.const 10) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const 10) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 10 20 anyfunc)
(func $f)
(elem (i32.const 10) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const 10) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 10 anyfunc)
(func $f)
(elem (i32.const -1) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const -1) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(table 10 anyfunc)
(func $f)
(elem (i32.const -10) $f)
)
"elements segment does not fit"
)
(assert_unlinkable
(module
(import "spectest" "table" (table 10 anyfunc))
(func $f)
(elem (i32.const -10) $f)
)
"elements segment does not fit"
)
;; Element without table
(assert_invalid
(module
(func $f)
(elem (i32.const 0) $f)
)
"unknown table 0"
)
;; Invalid offsets
(assert_invalid
(module
(table 1 anyfunc)
(elem (i64.const 0))
)
"type mismatch"
)
(assert_invalid
(module
(table 1 anyfunc)
(elem (i32.ctz (i32.const 0)))
)
"constant expression required"
)
(assert_invalid
(module
(table 1 anyfunc)
(elem (nop))
)
"constant expression required"
)
(assert_invalid
(module
(table 1 anyfunc)
(elem (offset (nop) (i32.const 0)))
)
"constant expression required"
)
(assert_invalid
(module
(table 1 anyfunc)
(elem (offset (i32.const 0) (nop)))
)
"constant expression required"
)
;; Use of internal globals in constant expressions is not allowed in MVP.
;; (assert_invalid
;; (module (memory 1) (data (get_global $g)) (global $g (mut i32) (i32.const 0)))
;; "constant expression required"
;; )
;; Two elements target the same slot
(module
(type $out-i32 (func (result i32)))
(table 10 anyfunc)
(elem (i32.const 9) $const-i32-a)
(elem (i32.const 9) $const-i32-b)
(func $const-i32-a (type $out-i32) (i32.const 65))
(func $const-i32-b (type $out-i32) (i32.const 66))
(func (export "call-overwritten") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 9))
)
)
(assert_return (invoke "call-overwritten") (i32.const 66))
(module
(type $out-i32 (func (result i32)))
(import "spectest" "table" (table 10 anyfunc))
(elem (i32.const 9) $const-i32-a)
(elem (i32.const 9) $const-i32-b)
(func $const-i32-a (type $out-i32) (i32.const 65))
(func $const-i32-b (type $out-i32) (i32.const 66))
(func (export "call-overwritten-element") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 9))
)
)
(assert_return (invoke "call-overwritten-element") (i32.const 66))
;; Element sections across multiple modules change the same table
(module $module1
(type $out-i32 (func (result i32)))
(table (export "shared-table") 10 anyfunc)
(elem (i32.const 8) $const-i32-a)
(elem (i32.const 9) $const-i32-b)
(func $const-i32-a (type $out-i32) (i32.const 65))
(func $const-i32-b (type $out-i32) (i32.const 66))
(func (export "call-7") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 7))
)
(func (export "call-8") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 8))
)
(func (export "call-9") (type $out-i32)
(call_indirect (type $out-i32) (i32.const 9))
)
)
(register "module1" $module1)
;; SKIP_SHARED_TABLE
;; (assert_trap (invoke $module1 "call-7") "uninitialized element 7")
;; (assert_return (invoke $module1 "call-8") (i32.const 65))
;; (assert_return (invoke $module1 "call-9") (i32.const 66))
(module $module2
(type $out-i32 (func (result i32)))
(import "module1" "shared-table" (table 10 anyfunc))
(elem (i32.const 7) $const-i32-c)
(elem (i32.const 8) $const-i32-d)
(func $const-i32-c (type $out-i32) (i32.const 67))
(func $const-i32-d (type $out-i32) (i32.const 68))
)
;; SKIP_SHARED_TABLE
;; (assert_return (invoke $module1 "call-7") (i32.const 67))
;; (assert_return (invoke $module1 "call-8") (i32.const 68))
;; (assert_return (invoke $module1 "call-9") (i32.const 66))
(module $module3
(type $out-i32 (func (result i32)))
(import "module1" "shared-table" (table 10 anyfunc))
(elem (i32.const 8) $const-i32-e)
(elem (i32.const 9) $const-i32-f)
(func $const-i32-e (type $out-i32) (i32.const 69))
(func $const-i32-f (type $out-i32) (i32.const 70))
)
;; SKIP_SHARED_TABLE
;; (assert_return (invoke $module1 "call-7") (i32.const 67))
;; (assert_return (invoke $module1 "call-8") (i32.const 69))
;; (assert_return (invoke $module1 "call-9") (i32.const 70))

View File

@ -13,7 +13,7 @@ static ENV_VAR: &str = "WASM_GENERATE_SPECTESTS";
static BANNER: &str = "// Rust test file autogenerated with cargo build (src/build_spectests.rs).
// Please do NOT modify it by hand, as it will be reseted on next build.\n";
const TESTS: [&str; 54] = [
const TESTS: [&str; 55] = [
"spectests/address.wast",
"spectests/align.wast",
"spectests/binary.wast",
@ -29,6 +29,7 @@ const TESTS: [&str; 54] = [
"spectests/conversions.wast",
"spectests/custom.wast",
"spectests/data.wast",
"spectests/elem.wast",
"spectests/endianness.wast",
"spectests/exports.wast",
"spectests/f32_.wast",
@ -484,7 +485,7 @@ fn {}_assert_malformed() {{
.or_insert(Vec::new())
.push(action_fn_name.unwrap());
}
fn visit_perform_action(&mut self, action: &Action) {
let action_fn_name = self.visit_action(action, None);
@ -642,7 +643,6 @@ mod {};",
modules.push(format!("mod {};", module_name));
}
}
// let mut modfile_uses: Vec<String> = modules.iter().map(|module| module).collect();
modules.insert(0, BANNER.to_string());
modules.insert(1, "// The _common module is not autogenerated, as it provides common functions for the spectests\nmod _common;".to_string());

View File

@ -9,15 +9,19 @@ pub struct UncheckedSlice<T> {
impl<T> UncheckedSlice<T> {
#[inline]
unsafe fn get_unchecked(&self, index: usize) -> &T {
pub fn get_unchecked(&self, index: usize) -> &T {
let ptr = self.ptr.as_ptr();
&*ptr.add(index)
unsafe {
&*ptr.add(index)
}
}
#[inline]
unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
pub fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
let ptr = self.ptr.as_ptr();
&mut *(ptr.add(index) as *mut _)
unsafe {
&mut *(ptr.add(index) as *mut _)
}
}
pub unsafe fn dangling() -> UncheckedSlice<T> {
@ -43,15 +47,16 @@ impl<'a, T> From<&'a [T]> for UncheckedSlice<T> {
}
#[derive(Debug)]
#[repr(C)]
pub struct BoundedSlice<T> {
data: UncheckedSlice<T>,
len: usize,
pub data: UncheckedSlice<T>,
pub len: usize,
}
impl<T> BoundedSlice<T> {
pub fn get(&self, index: usize) -> Option<&T> {
if index < self.len {
unsafe { Some(self.data.get_unchecked(index)) }
Some(self.data.get_unchecked(index))
} else {
None
}
@ -59,7 +64,7 @@ impl<T> BoundedSlice<T> {
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
if index < self.len {
unsafe { Some(self.data.get_unchecked_mut(index)) }
Some(self.data.get_unchecked_mut(index))
} else {
None
}
@ -69,6 +74,15 @@ impl<T> BoundedSlice<T> {
pub fn len(&self) -> usize {
self.len
}
// TODO: Needs refactor. Take LinearMemory as argument.
// I've tried that but it gives cryptic error.
pub fn new(slice: &[T], size: usize) -> BoundedSlice<T> {
BoundedSlice {
data: slice.into(),
len: size,
}
}
}
impl<T> Index<usize> for BoundedSlice<T> {

View File

@ -1,4 +1,4 @@
use crate::webassembly::{ImportObject, Instance};
use crate::webassembly::{ImportObject, ImportValue, Instance};
use libc::{printf, putchar};
extern "C" fn _printf(memory_offset: i32, extra: i32, instance: &Instance) -> i32 {
@ -12,8 +12,8 @@ extern "C" fn _printf(memory_offset: i32, extra: i32, instance: &Instance) -> i3
pub fn generate_libc_env<'a, 'b>() -> ImportObject<&'a str, &'b str> {
let mut import_object = ImportObject::new();
import_object.set("env", "printf", _printf as *const u8);
import_object.set("env", "putchar", putchar as *const u8);
import_object.set("env", "printf", ImportValue::Func(_printf as *const u8));
import_object.set("env", "putchar", ImportValue::Func(putchar as *const u8));
import_object
}
@ -34,7 +34,7 @@ mod tests {
_ => panic!("Function not found"),
};
let main: fn(&Instance) = get_instance_function!(instance, func_index);
main(&instance);
main(&instance)
}
#[test]

View File

@ -13,16 +13,6 @@ extern crate wabt;
extern crate target_lexicon;
extern crate nix;
extern crate spin;
// use std::alloc::System;
// use std::time::{Duration, Instant};
// #[global_allocator]
// static A: System = System;
// #[macro_use] extern crate log;
// use libc;
use std::error::Error;
use std::fs::File;
use std::io;
@ -81,7 +71,7 @@ fn execute_wasm(wasm_path: PathBuf) -> Result<(), String> {
webassembly::instantiate(wasm_binary, import_object)
.map_err(|err| String::from(err.description()))?;
// webassembly::utils::print_instance_offsets(&instance);
webassembly::utils::print_instance_offsets(&instance);
let func_index = instance
.start_func

View File

@ -1,4 +1,4 @@
use crate::webassembly::ImportObject;
use crate::webassembly::{ImportObject, ImportValue};
extern "C" fn print_i32(num: i32) {
println!("{}", num);
@ -10,9 +10,10 @@ static GLOBAL_I32: i32 = 666;
pub fn spectest_importobject<'a, 'b>() -> ImportObject<&'a str, &'b str> {
let mut import_object = ImportObject::new();
import_object.set("spectest", "print_i32", print_i32 as *const u8);
import_object.set("spectest", "print", print as *const u8);
import_object.set("spectest", "global_i32", GLOBAL_I32 as *const u8);
import_object.set("spectest", "print_i32", ImportValue::Func(print_i32 as *const u8));
import_object.set("spectest", "print", ImportValue::Func(print as *const u8));
import_object.set("spectest", "global_i32", ImportValue::Func(GLOBAL_I32 as *const u8));
import_object.set("spectest", "table", ImportValue::Table(vec![0; 30]));
return import_object;
}

File diff suppressed because it is too large Load Diff

689
src/spectests/elem.rs Normal file
View File

@ -0,0 +1,689 @@
// Rust test file autogenerated with cargo build (src/build_spectests.rs).
// Please do NOT modify it by hand, as it will be reseted on next build.
// Test based on spectests/elem.wast
#![allow(
warnings,
dead_code
)]
use std::panic;
use wabt::wat2wasm;
use crate::webassembly::{instantiate, compile, ImportObject, ResultObject, Instance, Export};
use super::_common::{
spectest_importobject,
NaNCheck,
};
// Line 4
fn create_module_1() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(func (;0;) (type 0))
(table (;0;) 10 anyfunc)
(elem (i32.const 0))
(elem (i32.const 0) 0 0)
(elem (i32.const 0))
(elem (i32.const 0) 0 0)
(elem (i32.const 0))
(elem (i32.const 0) 0 0)
(elem (i32.const 0))
(elem (i32.const 0) 0 0)
(elem (i32.const 0))
(elem (i32.const 0) 0 0)
(elem (i32.const 0))
(elem (i32.const 0) 0 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_1(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 23
#[test]
fn test_module_1() {
let result_object = create_module_1();
// We group the calls together
start_module_1(&result_object);
}
fn create_module_2() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(func (;0;) (type 0))
(table (;0;) 10 anyfunc)
(elem (i32.const 0) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_2(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 28
#[test]
fn test_module_2() {
let result_object = create_module_2();
// We group the calls together
start_module_2(&result_object);
}
fn create_module_3() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 10 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 0) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_3(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 34
#[test]
fn test_module_3() {
let result_object = create_module_3();
// We group the calls together
start_module_3(&result_object);
}
fn create_module_4() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(func (;0;) (type 0))
(table (;0;) 10 anyfunc)
(elem (i32.const 0) 0)
(elem (i32.const 3) 0)
(elem (i32.const 7) 0)
(elem (i32.const 5) 0)
(elem (i32.const 3) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_4(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 43
#[test]
fn test_module_4() {
let result_object = create_module_4();
// We group the calls together
start_module_4(&result_object);
}
fn create_module_5() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 10 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 9) 0)
(elem (i32.const 3) 0)
(elem (i32.const 7) 0)
(elem (i32.const 3) 0)
(elem (i32.const 5) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_5(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 69
#[test]
fn test_module_5() {
let result_object = create_module_5();
// We group the calls together
start_module_5(&result_object);
}
fn create_module_6() -> ResultObject {
let module_str = "(module
(type (;0;) (func (result i32)))
(func (;0;) (type 0) (result i32)
i32.const 65)
(func (;1;) (type 0) (result i32)
i32.const 66)
(func (;2;) (type 0) (result i32)
i32.const 7
call_indirect (type 0))
(func (;3;) (type 0) (result i32)
i32.const 9
call_indirect (type 0))
(table (;0;) 10 anyfunc)
(export \"call-7\" (func 2))
(export \"call-9\" (func 3))
(elem (i32.const 7) 0)
(elem (i32.const 9) 1))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_6(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 83
fn c6_l83_action_invoke(result_object: &ResultObject) {
println!("Executing function {}", "c6_l83_action_invoke");
let func_index = match result_object.module.info.exports.get("call-7") {
Some(&Export::Function(index)) => index,
_ => panic!("Function not found"),
};
let invoke_fn: fn(&Instance) -> i32 = get_instance_function!(result_object.instance, func_index);
let result = invoke_fn(&result_object.instance);
assert_eq!(result, 65 as i32);
}
// Line 84
fn c7_l84_action_invoke(result_object: &ResultObject) {
println!("Executing function {}", "c7_l84_action_invoke");
let func_index = match result_object.module.info.exports.get("call-9") {
Some(&Export::Function(index)) => index,
_ => panic!("Function not found"),
};
let invoke_fn: fn(&Instance) -> i32 = get_instance_function!(result_object.instance, func_index);
let result = invoke_fn(&result_object.instance);
assert_eq!(result, 66 as i32);
}
// Line 88
#[test]
fn test_module_6() {
let result_object = create_module_6();
// We group the calls together
start_module_6(&result_object);
c6_l83_action_invoke(&result_object);
c7_l84_action_invoke(&result_object);
}
fn create_module_7() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(func (;0;) (type 0))
(table (;0;) 10 anyfunc)
(elem (i32.const 9) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_7(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 93
#[test]
fn test_module_7() {
let result_object = create_module_7();
// We group the calls together
start_module_7(&result_object);
}
fn create_module_8() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 10 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 9) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_8(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 99
#[test]
fn test_module_8() {
let result_object = create_module_8();
// We group the calls together
start_module_8(&result_object);
}
fn create_module_9() -> ResultObject {
let module_str = "(module
(table (;0;) 0 anyfunc)
(elem (i32.const 0)))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_9(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 103
#[test]
fn test_module_9() {
let result_object = create_module_9();
// We group the calls together
start_module_9(&result_object);
}
fn create_module_10() -> ResultObject {
let module_str = "(module
(import \"spectest\" \"table\" (table (;0;) 0 anyfunc))
(elem (i32.const 0)))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_10(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 108
#[test]
fn test_module_10() {
let result_object = create_module_10();
// We group the calls together
start_module_10(&result_object);
}
fn create_module_11() -> ResultObject {
let module_str = "(module
(table (;0;) 0 0 anyfunc)
(elem (i32.const 0)))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_11(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 113
#[test]
fn test_module_11() {
let result_object = create_module_11();
// We group the calls together
start_module_11(&result_object);
}
fn create_module_12() -> ResultObject {
let module_str = "(module
(table (;0;) 20 anyfunc)
(elem (i32.const 20)))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_12(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 118
#[test]
fn test_module_12() {
let result_object = create_module_12();
// We group the calls together
start_module_12(&result_object);
}
fn create_module_13() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 0 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 0) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_13(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 124
#[test]
fn test_module_13() {
let result_object = create_module_13();
// We group the calls together
start_module_13(&result_object);
}
fn create_module_14() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 0 100 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 0) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_14(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 130
#[test]
fn test_module_14() {
let result_object = create_module_14();
// We group the calls together
start_module_14(&result_object);
}
fn create_module_15() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 0 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 1) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_15(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 136
#[test]
fn test_module_15() {
let result_object = create_module_15();
// We group the calls together
start_module_15(&result_object);
}
fn create_module_16() -> ResultObject {
let module_str = "(module
(type (;0;) (func))
(import \"spectest\" \"table\" (table (;0;) 0 30 anyfunc))
(func (;0;) (type 0))
(elem (i32.const 1) 0))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_16(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 145
// Line 154
// Line 163
// Line 172
// Line 180
// Line 188
// Line 197
// Line 205
// Line 214
// Line 222
// Line 231
// Line 239
// Line 250
#[test]
fn c30_l250_assert_invalid() {
let wasm_binary = [0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 9, 7, 1, 0, 65, 0, 11, 1, 0, 10, 4, 1, 2, 0, 11];
let compilation = compile(wasm_binary.to_vec());
assert!(compilation.is_err(), "WASM should not compile as is invalid");
}
// Line 260
#[test]
fn c31_l260_assert_invalid() {
let wasm_binary = [0, 97, 115, 109, 1, 0, 0, 0, 4, 4, 1, 112, 0, 1, 9, 6, 1, 0, 66, 0, 11, 0];
let compilation = compile(wasm_binary.to_vec());
assert!(compilation.is_err(), "WASM should not compile as is invalid");
}
// Line 268
#[test]
fn c32_l268_assert_invalid() {
let wasm_binary = [0, 97, 115, 109, 1, 0, 0, 0, 4, 4, 1, 112, 0, 1, 9, 7, 1, 0, 65, 0, 104, 11, 0];
let compilation = compile(wasm_binary.to_vec());
assert!(compilation.is_err(), "WASM should not compile as is invalid");
}
// Line 276
#[test]
fn c33_l276_assert_invalid() {
let wasm_binary = [0, 97, 115, 109, 1, 0, 0, 0, 4, 4, 1, 112, 0, 1, 9, 5, 1, 0, 1, 11, 0];
let compilation = compile(wasm_binary.to_vec());
assert!(compilation.is_err(), "WASM should not compile as is invalid");
}
// Line 284
#[test]
fn c34_l284_assert_invalid() {
let wasm_binary = [0, 97, 115, 109, 1, 0, 0, 0, 4, 4, 1, 112, 0, 1, 9, 7, 1, 0, 1, 65, 0, 11, 0];
let compilation = compile(wasm_binary.to_vec());
assert!(compilation.is_err(), "WASM should not compile as is invalid");
}
// Line 292
#[test]
fn c35_l292_assert_invalid() {
let wasm_binary = [0, 97, 115, 109, 1, 0, 0, 0, 4, 4, 1, 112, 0, 1, 9, 7, 1, 0, 65, 0, 1, 11, 0];
let compilation = compile(wasm_binary.to_vec());
assert!(compilation.is_err(), "WASM should not compile as is invalid");
}
// Line 307
#[test]
fn test_module_16() {
let result_object = create_module_16();
// We group the calls together
start_module_16(&result_object);
}
fn create_module_17() -> ResultObject {
let module_str = "(module
(type (;0;) (func (result i32)))
(func (;0;) (type 0) (result i32)
i32.const 65)
(func (;1;) (type 0) (result i32)
i32.const 66)
(func (;2;) (type 0) (result i32)
i32.const 9
call_indirect (type 0))
(table (;0;) 10 anyfunc)
(export \"call-overwritten\" (func 2))
(elem (i32.const 9) 0)
(elem (i32.const 9) 1))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_17(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 318
fn c37_l318_action_invoke(result_object: &ResultObject) {
println!("Executing function {}", "c37_l318_action_invoke");
let func_index = match result_object.module.info.exports.get("call-overwritten") {
Some(&Export::Function(index)) => index,
_ => panic!("Function not found"),
};
let invoke_fn: fn(&Instance) -> i32 = get_instance_function!(result_object.instance, func_index);
let result = invoke_fn(&result_object.instance);
assert_eq!(result, 66 as i32);
}
// Line 320
#[test]
fn test_module_17() {
let result_object = create_module_17();
// We group the calls together
start_module_17(&result_object);
c37_l318_action_invoke(&result_object);
}
fn create_module_18() -> ResultObject {
let module_str = "(module
(type (;0;) (func (result i32)))
(import \"spectest\" \"table\" (table (;0;) 10 anyfunc))
(func (;0;) (type 0) (result i32)
i32.const 65)
(func (;1;) (type 0) (result i32)
i32.const 66)
(func (;2;) (type 0) (result i32)
i32.const 9
call_indirect (type 0))
(export \"call-overwritten-element\" (func 2))
(elem (i32.const 9) 0)
(elem (i32.const 9) 1))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_18(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 331
fn c39_l331_action_invoke(result_object: &ResultObject) {
println!("Executing function {}", "c39_l331_action_invoke");
let func_index = match result_object.module.info.exports.get("call-overwritten-element") {
Some(&Export::Function(index)) => index,
_ => panic!("Function not found"),
};
let invoke_fn: fn(&Instance) -> i32 = get_instance_function!(result_object.instance, func_index);
let result = invoke_fn(&result_object.instance);
assert_eq!(result, 66 as i32);
}
// Line 335
#[test]
fn test_module_18() {
let result_object = create_module_18();
// We group the calls together
start_module_18(&result_object);
c39_l331_action_invoke(&result_object);
}
fn create_module_19() -> ResultObject {
let module_str = "(module
(type (;0;) (func (result i32)))
(func (;0;) (type 0) (result i32)
i32.const 65)
(func (;1;) (type 0) (result i32)
i32.const 66)
(func (;2;) (type 0) (result i32)
i32.const 7
call_indirect (type 0))
(func (;3;) (type 0) (result i32)
i32.const 8
call_indirect (type 0))
(func (;4;) (type 0) (result i32)
i32.const 9
call_indirect (type 0))
(table (;0;) 10 anyfunc)
(export \"shared-table\" (table 0))
(export \"call-7\" (func 2))
(export \"call-8\" (func 3))
(export \"call-9\" (func 4))
(elem (i32.const 8) 0)
(elem (i32.const 9) 1))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_19(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 353
// Line 360
#[test]
fn test_module_19() {
let result_object = create_module_19();
// We group the calls together
start_module_19(&result_object);
}
fn create_module_20() -> ResultObject {
let module_str = "(module
(type (;0;) (func (result i32)))
(import \"module1\" \"shared-table\" (table (;0;) 10 anyfunc))
(func (;0;) (type 0) (result i32)
i32.const 67)
(func (;1;) (type 0) (result i32)
i32.const 68)
(elem (i32.const 7) 0)
(elem (i32.const 8) 1))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_20(result_object: &ResultObject) {
result_object.instance.start();
}
// Line 374
#[test]
fn test_module_20() {
let result_object = create_module_20();
// We group the calls together
start_module_20(&result_object);
}
fn create_module_21() -> ResultObject {
let module_str = "(module
(type (;0;) (func (result i32)))
(import \"module1\" \"shared-table\" (table (;0;) 10 anyfunc))
(func (;0;) (type 0) (result i32)
i32.const 69)
(func (;1;) (type 0) (result i32)
i32.const 70)
(elem (i32.const 8) 0)
(elem (i32.const 9) 1))
";
let wasm_binary = wat2wasm(module_str.as_bytes()).expect("WAST not valid or malformed");
instantiate(wasm_binary, spectest_importobject()).expect("WASM can't be instantiated")
}
fn start_module_21(result_object: &ResultObject) {
result_object.instance.start();
}
#[test]
fn test_module_21() {
let result_object = create_module_21();
// We group the calls together
start_module_21(&result_object);
}

View File

@ -20,6 +20,7 @@ mod const_;
mod conversions;
mod custom;
mod data;
mod elem;
mod endianness;
mod exports;
#[cfg(not(feature = "fast-tests"))]

View File

@ -6,12 +6,13 @@
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use crate::webassembly::LinearMemory;
// We introduced the Pair and BorrowedPair types. We can't use (A, B)
// directly due to the orphan rule E0210. This is fine since the map
// is an implementation detail.
#[derive(PartialEq, Eq, Hash)]
struct Pair<A, B>(A, B);
pub struct Pair<A, B>(pub A, pub B);
#[derive(PartialEq, Eq, Hash)]
struct BorrowedPair<'a, 'b, A: 'a, B: 'b>(&'a A, &'b B);
@ -63,7 +64,7 @@ impl<'a, A: Eq, B: Eq> Eq for (KeyPair<A, B> + 'a) {}
// OP's ImportObject struct
pub struct ImportObject<A: Eq + Hash, B: Eq + Hash> {
map: HashMap<Pair<A, B>, *const u8>,
pub map: HashMap<Pair<A, B>, ImportValue>,
}
impl<A: Eq + Hash, B: Eq + Hash> ImportObject<A, B> {
@ -73,13 +74,12 @@ impl<A: Eq + Hash, B: Eq + Hash> ImportObject<A, B> {
}
}
pub fn get(&self, a: &A, b: &B) -> Option<*const u8> {
pub fn get(&self, a: &A, b: &B) -> Option<&ImportValue> {
self.map
.get(&BorrowedPair(a, b) as &KeyPair<A, B>)
.map(|p| *p)
}
pub fn set(&mut self, a: A, b: B, v: *const u8) {
pub fn set(&mut self, a: A, b: B, v: ImportValue) {
self.map.insert(Pair(a, b), v);
}
}
@ -109,18 +109,24 @@ where
}
}
#[derive(PartialEq, Debug)]
pub enum ImportValue {
Func(*const u8),
Global(u8),
Table(Vec<usize>),
Memory(LinearMemory),
}
#[cfg(test)]
mod tests {
use super::ImportObject;
use super::ImportValue;
#[test]
fn test_import_object() {
fn x() {}
let mut import_object = ImportObject::new();
import_object.set("abc", "def", x as *const u8);
// import_object.set("123"), A("456"), 45.0);
assert_eq!(import_object.get(&"abc", &"def").unwrap(), x as *const u8);
// assert_eq!(import_object.get(&"abc", &"dxf"), 4.0);
// assert_eq!(import_object.get(&A("123"), &A("456")), 45.0);
import_object.set("abc", "def", ImportValue::Func(x as *const u8));
assert_eq!(*import_object.get(&"abc", &"def").unwrap(), ImportValue::Func(x as *const u8));
}
}

View File

@ -15,15 +15,20 @@ use std::iter::Iterator;
use std::ptr::write_unaligned;
use std::slice;
use std::sync::Arc;
use std::mem::size_of;
use super::super::common::slice::{BoundedSlice, UncheckedSlice};
use super::errors::ErrorKind;
use super::import_object::ImportObject;
use super::import_object::{ImportObject, ImportValue};
use super::memory::LinearMemory;
use super::module::Export;
use super::module::Module;
use super::relocation::{Reloc, RelocSink, RelocationType};
type TablesSlice = UncheckedSlice<BoundedSlice<usize>>;
type MemoriesSlice = UncheckedSlice<BoundedSlice<u8>>;
type GlobalsSlice = UncheckedSlice<u8>;
pub fn protect_codebuf(code_buf: &Vec<u8>) -> Result<(), String> {
match unsafe {
region::protect(
@ -57,28 +62,15 @@ fn get_function_addr(
func_pointer
}
// TODO: To be removed.
// #[derive(Debug)]
// #[repr(C, packed)]
// pub struct VmCtx<'phantom> {
// pub user_data: UserData,
// globals: UncheckedSlice<u8>,
// memories: UncheckedSlice<UncheckedSlice<u8>>,
// tables: UncheckedSlice<BoundedSlice<usize>>,
// phantom: PhantomData<&'phantom ()>,
// }
// // TODO: To be removed.
// #[derive(Debug)]
// #[repr(C, packed)]
// pub struct UserData {
// // pub process: Dispatch<Process>,
// pub instance: Instance,
// }
/// An Instance of a WebAssembly module
/// NOTE: There is an assumption that data_pointers is always the
/// first field
#[repr(C)]
#[derive(Debug)]
pub struct Instance {
// C-like pointers to data (heaps, globals, tables)
pub data_pointers: DataPointers,
/// WebAssembly table data
// pub tables: Arc<Vec<RwLock<Vec<usize>>>>,
pub tables: Arc<Vec<Vec<usize>>>,
@ -100,41 +92,62 @@ pub struct Instance {
pub start_func: Option<FuncIndex>,
// Region start memory location
// code_base: *const (),
// C-like pointers to data (heaps, globals, tables)
pub data_pointers: DataPointers,
// Default memory bound
// TODO: Support for only one LinearMemory for now.
pub default_memory_bound: i32,
}
/// Contains pointers to data (heaps, globals, tables) needed
/// by Cranelift.
/// NOTE: Rearranging the fields will break the memory arrangement model
#[repr(C)]
#[derive(Debug)]
pub struct DataPointers {
// Pointer to tables
pub tables: UncheckedSlice<BoundedSlice<usize>>,
pub tables: TablesSlice,
// Pointer to memories
pub memories: UncheckedSlice<UncheckedSlice<u8>>,
pub memories: MemoriesSlice,
// Pointer to globals
pub globals: UncheckedSlice<u8>,
pub globals: GlobalsSlice,
}
impl Instance {
pub const TABLES_OFFSET: usize = 0; // 0 on 64-bit | 0 on 32-bit
pub const MEMORIES_OFFSET: usize = size_of::<TablesSlice>(); // 8 on 64-bit | 4 on 32-bit
pub const GLOBALS_OFFSET: usize = Instance::MEMORIES_OFFSET + size_of::<MemoriesSlice>(); // 16 on 64-bit | 8 on 32-bit
/// Create a new `Instance`.
/// TODO: Raise an error when expected import is not part of imported object
/// Also make sure imports that are not declared do not get added to the instance
pub fn new(
module: &Module,
import_object: &ImportObject<&str, &str>,
import_object: ImportObject<&str, &str>,
) -> Result<Instance, ErrorKind> {
let mut tables: Vec<Vec<usize>> = Vec::new();
let mut memories: Vec<LinearMemory> = Vec::new();
let mut globals: Vec<u8> = Vec::new();
let mut functions: Vec<Vec<u8>> = Vec::new();
let mut import_functions: Vec<*const u8> = Vec::new();
// let mut code_base: *const () = ptr::null();
let mut imported_functions: Vec<((&str, &str), *const u8)> = Vec::new();
let mut imported_tables: Vec<((&str, &str), Vec<usize>)> = Vec::new();
let mut imported_memories: Vec<((&str, &str), LinearMemory)> = Vec::new();
let mut imported_globals: Vec<((&str, &str), u8)> = Vec::new();
// Looping through and getting the imported objects
for (key, value) in import_object.map {
match value {
ImportValue::Memory(value) =>
imported_memories.push(((key.0, key.1), value)),
ImportValue::Table(value) =>
imported_tables.push(((key.0, key.1), value)),
ImportValue::Global(value) =>
imported_globals.push(((key.0, key.1), value)),
ImportValue::Func(value) =>
imported_functions.push(((key.0, key.1), value)),
}
}
debug!("Instance - Instantiating functions");
// Instantiate functions
@ -145,19 +158,14 @@ impl Instance {
.finish(module.info.flags.clone());
let mut relocations = Vec::new();
// We walk through the imported functions and set the relocations
// for each of this functions to be an empty vector (as is defined outside of wasm)
// Walk through the imported functions and set the relocations
// TODO: Needs to be optimize the find part.
// I also think it relies on the order of import declaration in module
for (module, field) in module.info.imported_funcs.iter() {
let function = import_object
.get(&module.as_str(), &field.as_str())
.ok_or_else(|| {
ErrorKind::LinkError(format!(
"Imported function {}.{} was not provided in the import_functions",
module, field
))
})?;
// println!("GET FUNC {:?}", function);
import_functions.push(function);
let function =
imported_functions.iter().find(|(key, _value)| key.0 == module && key.1 == field)
.unwrap_or_else(|| panic!("Imported function {}.{} was not provided in the import_functions", module, field));
import_functions.push(function.1);
relocations.push(vec![]);
}
@ -268,61 +276,35 @@ impl Instance {
}
}
}
// We only want to allocate in memory if there is more than
// 0 functions. Otherwise reserving a 0-sized memory region
// cause a panic error
// if total_size > 0 {
// // Allocate the total memory for this functions
// // let map = MmapMut::map_anon(total_size).unwrap();
// // let region_start = map.as_ptr() as usize;
// // code_base = map.as_ptr() as *const ();
// // // Emit this functions to memory
// for (ref func_context, func_offset) in context_and_offsets.iter() {
// let mut trap_sink = TrapSink::new(*func_offset);
// let mut reloc_sink = RelocSink::new();
// let mut code_buf: Vec<u8> = Vec::new();
// // let mut func_pointer = as *mut u8;
// unsafe {
// func_context.emit_to_memory(
// &*isa,
// &mut code_buf,
// &mut reloc_sink,
// &mut trap_sink,
// );
// };
// let func_offset = code_buf.as_ptr() as usize;
// functions.push(*func_offset);
// }
// // Set protection of this memory region to Read + Execute
// // so we are able to execute the functions emitted to memory
// // unsafe {
// // region::protect(region_start as *mut u8, total_size, region::Protection::ReadExecute)
// // .expect("unable to make memory readable+executable");
// // }
// }
}
debug!("Instance - Instantiating tables");
// Instantiate tables
{
// Reserve table space
tables.reserve_exact(module.info.tables.len());
// Reserve space for tables
tables.reserve_exact(imported_tables.len() + module.info.tables.len());
// Get imported tables
for (_key, table) in imported_tables {
tables.push(table);
}
// Get tables in module
for table in &module.info.tables {
let len = table.entity.size;
let mut v = Vec::with_capacity(len);
v.resize(len, 0);
tables.push(v);
}
// instantiate tables
for table_element in &module.info.table_elements {
// TODO: We shouldn't assert here since we are returning a Result<Instance, ErrorKind>
assert!(
table_element.base.is_none(),
"globalvalue base not supported yet."
);
let base = 0;
let table = &mut tables[table_element.table_index];
@ -342,22 +324,24 @@ impl Instance {
debug!("Instance - Instantiating memories");
// Instantiate memories
{
// Allocate the underlying memory and initialize it to all zeros.
let total_memories = module.info.memories.len();
if total_memories > 0 {
memories.reserve_exact(total_memories);
for memory in &module.info.memories {
let memory = memory.entity;
let v = LinearMemory::new(
memory.pages_count as u32,
memory.maximum.map(|m| m as u32),
);
memories.push(v);
}
} else {
memories.reserve_exact(1);
memories.push(LinearMemory::new(0, None));
// Reserve space for memories
memories.reserve_exact(imported_memories.len() + module.info.memories.len());
// Get imported memories
for (_key, memory) in imported_memories {
memories.push(memory);
}
// Get memories in module
for memory in &module.info.memories {
let memory = memory.entity;
let v = LinearMemory::new(
memory.pages_count as u32,
memory.maximum.map(|m| m as u32),
);
memories.push(v);
}
for init in &module.info.data_initializers {
debug_assert!(init.base.is_none(), "globalvar base not supported yet");
let offset = init.offset;
@ -368,6 +352,7 @@ impl Instance {
}
debug!("Instance - Instantiating globals");
// TODO: Fix globals import
// Instantiate Globals
{
let globals_count = module.info.globals.len();
@ -379,6 +364,7 @@ impl Instance {
let globals_data = unsafe {
slice::from_raw_parts_mut(globals.as_mut_ptr() as *mut i64, globals_count)
};
for (i, global) in module.info.globals.iter().enumerate() {
let value: i64 = match global.entity.initializer {
GlobalInit::I32Const(n) => n as _,
@ -412,9 +398,11 @@ impl Instance {
// TODO: Refactor repetitive code
let tables_pointer: Vec<BoundedSlice<usize>> =
tables.iter().map(|table| table[..].into()).collect();
let memories_pointer: Vec<UncheckedSlice<u8>> =
memories.iter().map(|mem| mem[..].into()).collect();
let globals_pointer: UncheckedSlice<u8> = globals[..].into();
let memories_pointer: Vec<BoundedSlice<u8>> =
memories.iter().map(
|mem| BoundedSlice::new(&mem[..], mem.current as usize * LinearMemory::WASM_PAGE_SIZE),
).collect();
let globals_pointer: GlobalsSlice = globals[..].into();
let data_pointers = DataPointers {
memories: memories_pointer[..].into(),
@ -422,18 +410,16 @@ impl Instance {
tables: tables_pointer[..].into(),
};
let default_memory_bound = LinearMemory::WASM_PAGE_SIZE as i32;
// let mem = data_pointers.memories;
Ok(Instance {
data_pointers,
tables: Arc::new(tables.into_iter().collect()), // tables.into_iter().map(|table| RwLock::new(table)).collect()),
memories: Arc::new(memories.into_iter().collect()),
globals,
functions,
import_functions,
start_func,
data_pointers,
default_memory_bound,
// code_base: code_base,
})
}
@ -461,37 +447,6 @@ impl Instance {
}
}
// TODO: To be removed.
// pub fn generate_context(&self) -> VmCtx {
// let memories: Vec<UncheckedSlice<u8>> =
// self.memories.iter().map(|mem| mem[..].into()).collect();
// let tables: Vec<BoundedSlice<usize>> =
// self.tables.iter().map(|table| table[..].into()).collect();
// let globals: UncheckedSlice<u8> = self.globals[..].into();
// // println!("GENERATING CONTEXT {:?}", self.globals);
// // assert!(memories.len() >= 1, "modules must have at least one memory");
// // the first memory has a space of `mem::size_of::<VmCtxData>()` rounded
// // up to the 4KiB before it. We write the VmCtxData into that.
// let instance = self.clone();
// VmCtx {
// globals: globals,
// memories: memories[..].into(),
// tables: tables[..].into(),
// user_data: UserData {
// // process,
// instance: instance,
// },
// phantom: PhantomData,
// }
// // let main_heap_ptr = memories[0].as_mut_ptr() as *mut VmCtxData;
// // unsafe {
// // main_heap_ptr.sub(1).write(data);
// // &*(main_heap_ptr as *const VmCtx)
// // }
// }
/// Returns a slice of the contents of allocated linear memory.
pub fn inspect_memory(&self, memory_index: usize, address: usize, len: usize) -> &[u8] {
&self
@ -513,46 +468,6 @@ impl Instance {
// }
}
impl Clone for Instance {
fn clone(&self) -> Instance {
// TODO: Refactor repetitive code
let tables_pointer: Vec<BoundedSlice<usize>> =
self.tables.iter().map(|table| table[..].into()).collect();
let memories_pointer: Vec<UncheckedSlice<u8>> =
self.memories.iter().map(|mem| mem[..].into()).collect();
let globals_pointer: UncheckedSlice<u8> = self.globals[..].into();
let data_pointers = DataPointers {
memories: memories_pointer[..].into(),
globals: globals_pointer,
tables: tables_pointer[..].into(),
};
let default_memory_bound = self.memories.get(0).unwrap().current as i32;
Instance {
tables: Arc::clone(&self.tables),
memories: Arc::clone(&self.memories),
globals: self.globals.clone(),
functions: self.functions.clone(),
start_func: self.start_func.clone(),
import_functions: self.import_functions.clone(),
data_pointers,
default_memory_bound,
// code_base: self.code_base,
}
}
}
/// TODO:
/// Need to improve how memories are stored and grown.
/// Dynamic memory is inefficient both for growing and for access
/// Cranelift's dynamic heap assumes a _statically-known_ number of LinearMemories,
/// because it expects a corresponding global variable for each LinearMemory
///
/// Reference:
/// - https://cranelift.readthedocs.io/en/latest/ir.html?highlight=vmctx#heap-examples,
///
extern "C" fn grow_memory(size: u32, memory_index: u32, instance: &mut Instance) -> i32 {
// TODO: Support for only one LinearMemory for now.
debug_assert_eq!(
@ -565,31 +480,13 @@ extern "C" fn grow_memory(size: u32, memory_index: u32, instance: &mut Instance)
.grow(size)
.unwrap_or(i32::max_value()); // Should be -1 ?
// Update the default_memory_bound
instance.default_memory_bound =
(instance.memories.get(0).unwrap().current as usize * LinearMemory::WASM_PAGE_SIZE) as i32;
// Get new memory bytes
let new_mem_bytes = (old_mem_size as usize + size as usize) * LinearMemory::WASM_PAGE_SIZE;
// The grown memory changed so data_pointers need to be updated as well.
// TODO: Refactor repetitive code
let tables_pointer: Vec<BoundedSlice<usize>> = instance
.tables
.iter()
.map(|table| table[..].into())
.collect();
let memories_pointer: Vec<UncheckedSlice<u8>> =
instance.memories.iter().map(|mem| mem[..].into()).collect();
let globals_pointer: UncheckedSlice<u8> = instance.globals[..].into();
// Update data_pointer
instance.data_pointers.memories.get_unchecked_mut(memory_index as usize).len = new_mem_bytes;
let data_pointers = DataPointers {
memories: memories_pointer[..].into(),
globals: globals_pointer,
tables: tables_pointer[..].into(),
};
// Update data_pointers
instance.data_pointers = data_pointers;
return old_mem_size;
old_mem_size
}
extern "C" fn current_memory(memory_index: u32, instance: &mut Instance) -> u32 {

View File

@ -12,8 +12,6 @@ const MAX_PAGES: u32 = 65536;
/// A linear memory instance.
///
/// This linear memory has a stable base address and at the same time allows
/// for dynamical growing.
pub struct LinearMemory {
pub mmap: MmapMut,
// The initial size of the WebAssembly Memory, in units of
@ -25,7 +23,7 @@ pub struct LinearMemory {
// front. However, the engine may ignore or clamp this reservation
// request. In general, most WebAssembly modules shouldn't need
// to set a maximum.
maximum: Option<u32>,
pub maximum: Option<u32>,
}
/// It holds the raw bytes of memory accessed by a WebAssembly Instance
@ -33,7 +31,7 @@ impl LinearMemory {
pub const WASM_PAGE_SIZE: usize = 1 << 16; // 64 KiB
pub const DEFAULT_HEAP_SIZE: usize = 1 << 32; // 4 GiB
pub const DEFAULT_GUARD_SIZE: usize = 1 << 31; // 2 GiB
pub const DEFAULT_SIZE: usize = Self::DEFAULT_HEAP_SIZE + Self::DEFAULT_GUARD_SIZE; // 8GiB
pub const DEFAULT_SIZE: usize = Self::DEFAULT_HEAP_SIZE + Self::DEFAULT_GUARD_SIZE; // 6 GiB
/// Create a new linear memory instance with specified initial and maximum number of pages.
///
@ -46,13 +44,9 @@ impl LinearMemory {
initial, maximum
);
let len: u64 = PAGE_SIZE as u64 * match maximum {
Some(val) => val as u64,
None => initial as u64,
};
let len = if len == 0 { PAGE_SIZE as u64 } else { len };
// TODO: Investigate if memory is zeroed out
let mmap = MmapMut::map_anon(LinearMemory::DEFAULT_HEAP_SIZE).unwrap();
let mmap = MmapMut::map_anon(len as usize).unwrap();
debug!("LinearMemory instantiated");
Self {
mmap,
@ -101,34 +95,11 @@ impl LinearMemory {
// Updating self.mmap if new_bytes > prev_bytes
if new_bytes > prev_bytes {
// If we have no maximum, this is a "dynamic" heap, and it's allowed
// to move.
let mut new_mmap = MmapMut::map_anon(new_bytes).unwrap();
// Copy old mem to new mem. Will a while loop be faster or is this going to be optimized?
// TODO: Consider static heap for efficiency.
for i in 0..prev_bytes {
unsafe {
let new_mmap_index = new_mmap.get_unchecked_mut(i);
let old_mmap_index = self.mmap.get_unchecked(i);
*new_mmap_index = *old_mmap_index;
}
}
// Zero out the remaining mem region
// TODO: Check if memmap zeroes out everything by default. This is very inefficient!
for i in prev_bytes..new_bytes {
unsafe {
let index = new_mmap.get_unchecked_mut(i);
*index = 0;
}
}
// Update relevant fields
self.mmap = new_mmap;
self.current = new_pages;
debug!("new memory = {:?}", self.mmap);
}
self.current = new_pages;
Some(prev_pages as i32)
}
@ -155,6 +126,14 @@ impl fmt::Debug for LinearMemory {
}
}
// Not comparing based on memory content. That would be inefficient.
impl PartialEq for LinearMemory {
fn eq(&self, other: &LinearMemory) -> bool {
self.current == other.current &&
self.maximum == other.maximum
}
}
impl AsRef<[u8]> for LinearMemory {
fn as_ref(&self) -> &[u8] {
&self.mmap

View File

@ -12,7 +12,7 @@ use target_lexicon;
use wasmparser;
pub use self::errors::{Error, ErrorKind};
pub use self::import_object::ImportObject;
pub use self::import_object::{ImportObject, ImportValue};
pub use self::instance::{Instance};
pub use self::memory::LinearMemory;
pub use self::module::{Export, Module, ModuleInfo};
@ -46,7 +46,7 @@ pub fn instantiate(
) -> Result<ResultObject, ErrorKind> {
let module = compile(buffer_source)?;
debug!("webassembly - creating instance");
let instance = Instance::new(&module, &import_object)?;
let instance = Instance::new(&module, import_object)?;
debug!("webassembly - instance created");
Ok(ResultObject { module, instance })
}
@ -78,7 +78,6 @@ pub fn compile(buffer_source: Vec<u8>) -> Result<Module, ErrorKind> {
if !valid {
return Err(ErrorKind::CompileError("Module not valid".to_string()));
}
debug!("webassembly - creating module");
let module = Module::from_bytes(buffer_source, triple!("x86_64"), None)?;
debug!("webassembly - module created");

View File

@ -37,6 +37,7 @@ use cranelift_wasm::{
use super::errors::ErrorKind;
use super::memory::LinearMemory;
use super::instance::Instance;
/// Compute a `ir::ExternalName` for a given wasm function index.
fn get_func_name(func_index: FuncIndex) -> ir::ExternalName {
@ -44,6 +45,7 @@ fn get_func_name(func_index: FuncIndex) -> ir::ExternalName {
}
/// A collection of names under which a given entity is exported.
#[derive(Debug)]
pub struct Exportable<T> {
/// An entity.
pub entity: T,
@ -74,6 +76,7 @@ pub enum Export {
Global(GlobalIndex),
}
/// TODO: Need to get rid of unused field
/// The main state belonging to a `Module`. This is split out from
/// `Module` to allow it to be borrowed separately from the
/// `FuncTranslator` field.
@ -92,20 +95,21 @@ pub struct ModuleInfo {
/// Signatures as provided by `declare_signature`.
pub signatures: Vec<ir::Signature>,
/// Module and field names of imported functions as provided by `declare_func_import`.
pub imported_funcs: Vec<(String, String)>,
/// Functions, imported and local.
pub functions: PrimaryMap<FuncIndex, Exportable<SignatureIndex>>,
/// Function bodies.
pub function_bodies: PrimaryMap<DefinedFuncIndex, ir::Function>,
/// Module and field names of imported functions as provided by `declare_func_import`.
pub imported_funcs: Vec<(String, String)>,
/// Tables as provided by `declare_table`.
pub tables: Vec<Exportable<Table>>,
/// WebAssembly table initializers.
pub table_elements: Vec<TableElements>,
/// The base of tables.
pub tables_base: Option<ir::GlobalValue>,
@ -143,9 +147,9 @@ impl ModuleInfo {
triple,
flags,
signatures: Vec::new(),
imported_funcs: Vec::new(),
functions: PrimaryMap::new(),
function_bodies: PrimaryMap::new(),
imported_funcs: Vec::new(),
tables: Vec::new(),
memories: Vec::new(),
globals: Vec::new(),
@ -328,142 +332,121 @@ impl<'environment> FuncEnvironmentTrait for FuncEnvironment<'environment> {
&self.mod_info.flags
}
// TODO: offsets should be based on the architecture the wasmer was compiled for.
// e.g., BoundedSlice.len will be 32-bit (4 bytes) when wasmer is compiled for a 32-bit arch,
// however the 32-bit wasmer may be running on 64-bit arch, which means ptr_size here will
// be 8 bytes. That will definitely gove the wrong offset values
fn make_table(&mut self, func: &mut ir::Function, table_index: TableIndex) -> ir::Table {
let vmctx = func.create_global_value(ir::GlobalValueData::VMContext);
let instance = func.create_global_value(ir::GlobalValueData::VMContext);
let ptr_size = self.ptr_size();
// Given a vmctx, we want to retrieve vmctx.tables
// Create a table whose base address is stored at `vmctx+88`.
// 88 is the offset of the vmctx.tables pointer respect to vmctx pointer
// Load value at (instance + TABLES_OFFSET)
// which is the address of data_pointer.tables
let base = func.create_global_value(ir::GlobalValueData::Load {
base: vmctx,
offset: Offset32::new(88),
base: instance,
offset: Offset32::new(Instance::TABLES_OFFSET as i32),
global_type: self.pointer_type(),
});
// This will be 0 when the index is 0, not sure if the offset will work regardless
// Offset based on table_index
let table_data_offset = (table_index as usize * ptr_size * 2) as i32;
// We get the pointer for our table index
// Load value at the (base + table_data_offset)
// which is the address of data_pointer.tables[index].data
let base_gv = func.create_global_value(ir::GlobalValueData::Load {
base: base,
base,
offset: Offset32::new(table_data_offset),
global_type: self.pointer_type(),
});
// Load value at the (base + table_data_offset)
// which is the value of data_pointer.tables[index].len
let bound_gv = func.create_global_value(ir::GlobalValueData::Load {
base: base,
offset: Offset32::new(table_data_offset),
global_type: I64,
base,
offset: Offset32::new(table_data_offset + ptr_size as i32),
global_type: self.pointer_type(),
});
// Create table based on the data above
let table = func.create_table(ir::TableData {
base_gv: base_gv,
base_gv,
min_size: Imm64::new(0),
bound_gv,
element_size: Imm64::new(i64::from(self.pointer_bytes())),
index_type: self.pointer_type(),
});
// println!("FUNC {:?}", func);
table
}
fn make_heap(&mut self, func: &mut ir::Function, index: MemoryIndex) -> ir::Heap {
// Create a static heap whose base address is stored at `vmctx+96`.
let vmctx = func.create_global_value(ir::GlobalValueData::VMContext);
// TODO: offsets should be based on the architecture the wasmer was compiled for.
// e.g., BoundedSlice.len will be 32-bit (4 bytes) when wasmer is compiled for a 32-bit arch,
// however the 32-bit wasmer may be running on 64-bit arch, which means ptr_size here will
// be 8 bytes. That will definitely gove the wrong offset values
fn make_heap(&mut self, func: &mut ir::Function, memory_index: MemoryIndex) -> ir::Heap {
let instance = func.create_global_value(ir::GlobalValueData::VMContext);
let ptr_size = self.ptr_size();
let heap_base_addr = func.create_global_value(ir::GlobalValueData::Load {
base: vmctx,
offset: Offset32::new(96),
// Load value at (instance + MEMORIES_OFFSET)
// which is the address of data_pointer.memories
let base = func.create_global_value(ir::GlobalValueData::Load {
base: instance,
offset: Offset32::new(Instance::MEMORIES_OFFSET as i32),
global_type: self.pointer_type(),
});
let pointer_bytes = self.pointer_bytes();
let memories_offset = (index * pointer_bytes as usize) as i32;
// Based on the index provided, we need to know the offset into memories array
// Each element in the memories array has a size of (ptr_size * 2)
let memory_data_offset = (memory_index as usize * ptr_size * 2) as i32;
// We de-reference the vm_context.memories addr
// Load value at the (base + memory_data_offset)
// which is the address of data_pointer.memories[index].data
let heap_base = func.create_global_value(ir::GlobalValueData::Load {
base: heap_base_addr,
offset: Offset32::new(memories_offset),
base,
offset: Offset32::new(memory_data_offset),
global_type: self.pointer_type(),
});
// Load value at the (base + memory_data_offset)
// which is the value of data_pointer.memories[index].len
let bound_gv = func.create_global_value(ir::GlobalValueData::Load {
base: vmctx,
offset: Offset32::new(120),
base,
offset: Offset32::new(memory_data_offset + ptr_size as i32),
global_type: I32,
});
func.create_heap(ir::HeapData {
// Create table based on the data above
let heap = func.create_heap(ir::HeapData {
base: heap_base,
min_size: Imm64::new(0),
guard_size: Imm64::new(LinearMemory::DEFAULT_GUARD_SIZE as i64),
min_size: 0.into(),
guard_size: (LinearMemory::DEFAULT_GUARD_SIZE as i64).into(),
style: ir::HeapStyle::Dynamic {
bound_gv,
},
index_type: I32,
})
index_type: I32
});
// if index == 0 {
// let heap_base = self.main_memory_base.unwrap_or_else(|| {
// let new_base = func.create_global_value(ir::GlobalValueData::VMContext {
// offset: 0.into(),
// });
// self.main_memory_base = Some(new_base);
// new_base
// });
// func.create_heap(ir::HeapData {
// base: heap_base,
// min_size: 0.into(),
// guard_size: (WasmMemory::DEFAULT_GUARD_SIZE as i64).into(),
// style: ir::HeapStyle::Static {
// bound: (WasmMemory::DEFAULT_HEAP_SIZE as i64).into(),
// },
// })
// } else {
// let memory_base = self.memory_base.unwrap_or_else(|| {
// let memories_offset = self.ptr_size() as i32 * -2;
// let new_base = func.create_global_value(ir::GlobalValueData::VMContext {
// offset: memories_offset.into(),
// });
// self.memory_base = Some(new_base);
// new_base
// });
// let memory_offset = (index - 1) * self.ptr_size();
// let heap_base = func.create_global_value(ir::GlobalValueData::Deref {
// base: memory_base,
// offset: (memory_offset as i32).into(),
// });
// func.create_heap(ir::HeapData {
// base: heap_base,
// min_size: 0.into(),
// guard_size: (WasmMemory::DEFAULT_GUARD_SIZE as i64).into(),
// style: ir::HeapStyle::Static {
// bound: (WasmMemory::DEFAULT_HEAP_SIZE as i64).into(),
// },
// })
// }
heap
}
fn make_global(&mut self, func: &mut ir::Function, index: GlobalIndex) -> GlobalVariable {
// Just create a dummy `vmctx` global.
let vmctx = func.create_global_value(ir::GlobalValueData::VMContext);
let ptr_size = self.ptr_size();
let instance = func.create_global_value(ir::GlobalValueData::VMContext);
let globals_base_addr = func.create_global_value(ir::GlobalValueData::Load {
base: vmctx,
offset: Offset32::new(104),
base: instance,
offset: Offset32::new(Instance::GLOBALS_OFFSET as i32),
global_type: self.pointer_type(),
});
let offset = (index * 8) as i64;
let offset = (index * ptr_size) as i64;
let iadd = func.create_global_value(ir::GlobalValueData::IAddImm {
base: globals_base_addr,
offset: Imm64::new(offset),
global_type: self.pointer_type(),
});
GlobalVariable::Memory {
gv: iadd,
ty: self.mod_info.globals[index].entity.ty,
@ -538,8 +521,6 @@ impl<'environment> FuncEnvironmentTrait for FuncEnvironment<'environment> {
.CallIndirect(ir::Opcode::CallIndirect, INVALID, sig_ref, args)
.0;
// println!("FUNC {:?}", pos.func);
Ok(inst)
}
@ -723,7 +704,6 @@ impl<'data> ModuleEnvironment<'data> for Module {
offset: usize,
elements: Vec<FuncIndex>,
) {
// NEW
debug_assert!(base.is_none(), "global-value offsets not supported yet");
self.info.table_elements.push(TableElements {
table_index,

View File

@ -9,31 +9,42 @@ pub fn is_wasm_binary(binary: &Vec<u8>) -> bool {
pub fn print_instance_offsets(instance: &Instance) {
let instance_address = instance as *const _ as usize;
let data_ptr = &instance.data_pointers;
let tables_pointer_address_ptr: *const usize =
unsafe { transmute(&instance.data_pointers.tables) };
unsafe { transmute(&data_ptr.tables) };
let tables_pointer_address = tables_pointer_address_ptr as usize;
let memories_pointer_address_ptr: *const usize =
unsafe { transmute(&instance.data_pointers.memories) };
unsafe { transmute(&data_ptr.memories) };
let memories_pointer_address = memories_pointer_address_ptr as usize;
let globals_pointer_address_ptr: *const usize =
unsafe { transmute(&instance.data_pointers.globals) };
let globals_pointer_address = globals_pointer_address_ptr as usize;
let memories_pointer_address_ptr_0: *const usize =
unsafe { transmute(&data_ptr.memories.get_unchecked(0)) };
let memories_pointer_address_0 = memories_pointer_address_ptr_0 as usize;
let default_memory_bound_address_ptr: *const usize =
unsafe { transmute(&instance.default_memory_bound) };
let default_memory_bound_address = default_memory_bound_address_ptr as usize;
let memories_pointer_address_ptr_0_data: *const usize =
unsafe { transmute(&data_ptr.memories.get_unchecked(0).data) };
let memories_pointer_address_0_data = memories_pointer_address_ptr_0_data as usize;
let memories_pointer_address_ptr_0_len: *const usize =
unsafe { transmute(&data_ptr.memories.get_unchecked(0).len) };
let memories_pointer_address_0_len = memories_pointer_address_ptr_0_len as usize;
let globals_pointer_address_ptr: *const usize =
unsafe { transmute(&data_ptr.globals) };
let globals_pointer_address = globals_pointer_address_ptr as usize;
println!(
"
====== INSTANCE OFFSET TABLE ======
instance \t\t\t- {:X} | offset - {:?}
instance.data_pointers.tables \t- {:X} | offset - {:?}
instance.data_pointers.memories - {:X} | offset - {:?}
instance.data_pointers.memories\t- {:X} | offset - {:?}
.memories[0] \t\t- {:X} | offset - {:?}
.memories[0].data\t\t- {:X} | offset - {:?}
.memories[0].len({:?})\t- {:X} | offset - {:?}
instance.data_pointers.globals \t- {:X} | offset - {:?}
instance.default_memory_bound \t- {:X} | offset - {:?}
====== INSTANCE OFFSET TABLE ======
",
instance_address,
@ -42,9 +53,16 @@ instance.default_memory_bound \t- {:X} | offset - {:?}
tables_pointer_address - instance_address,
memories_pointer_address,
memories_pointer_address - instance_address,
memories_pointer_address_0,
0,
memories_pointer_address_0_data,
memories_pointer_address_0_data - memories_pointer_address_0_data,
data_ptr.memories.get_unchecked(0).len,
memories_pointer_address_0_len,
memories_pointer_address_0_len - memories_pointer_address_0_data,
globals_pointer_address,
globals_pointer_address - instance_address,
default_memory_bound_address,
default_memory_bound_address - instance_address,
);
}