wasmer/src/webassembly/instance.rs

589 lines
22 KiB
Rust
Raw Normal View History

//! A webassembly::Instance object is a stateful, executable instance of a
//! webassembly::Module. Instance objects contain all the Exported
//! WebAssembly functions that allow calling into WebAssembly code.
//! The webassembly::Instance() constructor function can be called to
//! synchronously instantiate a given webassembly::Module object. However, the
//! primary way to get an Instance is through the asynchronous
2018-10-24 12:36:43 +02:00
//! webassembly::instantiate_streaming() function.
2018-11-21 20:59:23 -08:00
use cranelift_codegen::ir::{Function, LibCall};
2018-11-14 23:10:35 -08:00
use cranelift_codegen::isa::TargetIsa;
2018-11-21 20:59:23 -08:00
use cranelift_codegen::{binemit, Context};
2018-10-15 03:03:00 +02:00
use cranelift_entity::EntityRef;
use cranelift_wasm::{FuncIndex, GlobalInit};
use rayon::prelude::*;
2018-10-15 03:03:00 +02:00
use region;
2018-11-21 20:59:23 -08:00
use std::iter::FromIterator;
2018-10-16 03:21:49 +02:00
use std::iter::Iterator;
2018-11-21 20:59:23 -08:00
use std::mem::size_of;
use std::ptr::write_unaligned;
2018-11-06 15:51:01 +01:00
use std::slice;
2018-10-14 13:59:11 +02:00
use std::sync::Arc;
2018-10-15 03:03:00 +02:00
use super::super::common::slice::{BoundedSlice, UncheckedSlice};
use super::super::recovery;
2018-10-15 02:48:59 +02:00
use super::errors::ErrorKind;
use super::import_object::{ImportObject, ImportValue};
2018-11-21 20:59:23 -08:00
use super::math_intrinsics;
2018-10-15 02:48:59 +02:00
use super::memory::LinearMemory;
2018-11-20 20:11:58 +01:00
use super::module::{Export, ImportableExportable, Module};
use super::relocation::{Reloc, RelocSink, RelocationType};
2018-10-15 17:10:49 +02:00
type TablesSlice = UncheckedSlice<BoundedSlice<usize>>;
type MemoriesSlice = UncheckedSlice<BoundedSlice<u8>>;
type GlobalsSlice = UncheckedSlice<u8>;
2018-10-15 17:10:49 +02:00
pub fn protect_codebuf(code_buf: &Vec<u8>) -> Result<(), String> {
match unsafe {
region::protect(
code_buf.as_ptr(),
code_buf.len(),
region::Protection::ReadWriteExecute,
)
} {
Err(err) => {
return Err(format!(
"failed to give executable permission to code: {}",
err
))
2018-10-16 03:21:49 +02:00
}
2018-10-15 17:10:49 +02:00
Ok(()) => Ok(()),
}
}
2018-10-17 11:22:45 +02:00
fn get_function_addr(
2018-10-14 23:48:59 +02:00
func_index: &FuncIndex,
2018-10-17 11:22:45 +02:00
import_functions: &Vec<*const u8>,
functions: &Vec<Vec<u8>>,
) -> *const u8 {
2018-10-17 11:22:45 +02:00
let index = func_index.index();
let len = import_functions.len();
let func_pointer = if index < len {
import_functions[index]
} else {
2018-11-15 13:30:00 -08:00
(functions[index - len]).as_ptr()
2018-10-17 11:22:45 +02:00
};
func_pointer
2018-10-14 13:59:11 +02:00
}
2018-10-12 02:45:09 +02:00
2018-10-14 13:59:11 +02:00
/// An Instance of a WebAssembly module
/// NOTE: There is an assumption that data_pointers is always the
/// first field
#[repr(C)]
2018-10-14 13:59:11 +02:00
#[derive(Debug)]
#[repr(C)]
2018-10-14 13:59:11 +02:00
pub struct Instance {
// C-like pointers to data (heaps, globals, tables)
pub data_pointers: DataPointers,
2018-10-14 13:59:11 +02:00
/// WebAssembly table data
2018-10-15 17:10:49 +02:00
// pub tables: Arc<Vec<RwLock<Vec<usize>>>>,
pub tables: Arc<Vec<Vec<usize>>>,
2018-10-14 13:59:11 +02:00
/// WebAssembly linear memory data
pub memories: Arc<Vec<LinearMemory>>,
2018-10-14 13:59:11 +02:00
/// WebAssembly global variable data
pub globals: Vec<u8>,
2018-10-15 15:58:06 +02:00
/// Webassembly functions
2018-10-15 17:10:49 +02:00
// functions: Vec<usize>,
functions: Vec<Vec<u8>>,
2018-10-17 11:22:45 +02:00
/// Imported functions
import_functions: Vec<*const u8>,
/// The module start function
2018-10-17 16:45:24 +02:00
pub start_func: Option<FuncIndex>,
// Region start memory location
// code_base: *const (),
2018-11-07 11:18:55 +01:00
}
/// Contains pointers to data (heaps, globals, tables) needed
/// by Cranelift.
/// NOTE: Rearranging the fields will break the memory arrangement model
#[repr(C)]
2018-11-07 11:18:55 +01:00
#[derive(Debug)]
#[repr(C)]
2018-11-07 11:18:55 +01:00
pub struct DataPointers {
// Pointer to tables
pub tables: TablesSlice,
2018-11-07 11:18:55 +01:00
// Pointer to memories
pub memories: MemoriesSlice,
2018-11-07 11:18:55 +01:00
// Pointer to globals
pub globals: GlobalsSlice,
2018-10-14 13:59:11 +02:00
}
pub struct InstanceOptions {
// Shall we mock automatically the imported functions if they don't exist?
pub mock_missing_imports: bool,
pub mock_missing_globals: bool,
pub mock_missing_tables: bool,
2018-11-14 23:10:35 -08:00
pub isa: Box<TargetIsa>,
}
2018-11-21 20:59:23 -08:00
extern "C" fn mock_fn() -> i32 {
2018-11-20 20:11:58 +01:00
return 0;
}
2018-11-18 22:12:22 -08:00
struct CompiledFunction {
code_buf: Vec<u8>,
reloc_sink: RelocSink,
trap_sink: binemit::NullTrapSink,
}
2018-11-21 20:59:23 -08:00
fn compile_function(
isa: &TargetIsa,
function_body: &Function,
) -> Result<CompiledFunction, ErrorKind> {
2018-11-18 22:12:22 -08:00
let mut func_context = Context::for_function(function_body.to_owned());
let mut code_buf: Vec<u8> = Vec::new();
let mut reloc_sink = RelocSink::new();
let mut trap_sink = binemit::NullTrapSink {};
func_context
.compile_and_emit(isa, &mut code_buf, &mut reloc_sink, &mut trap_sink)
.map_err(|e| {
debug!("CompileError: {}", e.to_string());
ErrorKind::CompileError(e.to_string())
})?;
Ok(CompiledFunction {
code_buf,
reloc_sink,
2018-11-21 20:59:23 -08:00
trap_sink,
2018-11-18 22:12:22 -08:00
})
}
2018-10-14 13:59:11 +02:00
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
2018-10-14 13:59:11 +02:00
/// 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
2018-10-17 11:22:45 +02:00
pub fn new(
module: &Module,
import_object: ImportObject<&str, &str>,
options: InstanceOptions,
2018-10-17 11:22:45 +02:00
) -> Result<Instance, ErrorKind> {
2018-10-14 13:59:11 +02:00
let mut tables: Vec<Vec<usize>> = Vec::new();
let mut memories: Vec<LinearMemory> = Vec::new();
let mut globals: Vec<u8> = Vec::new();
2018-10-15 17:10:49 +02:00
let mut functions: Vec<Vec<u8>> = Vec::new();
2018-10-17 11:22:45 +02:00
let mut import_functions: Vec<*const u8> = Vec::new();
debug!("Instance - Instantiating functions");
2018-10-15 11:46:04 +02:00
// Instantiate functions
2018-10-15 02:48:59 +02:00
{
2018-10-17 11:22:45 +02:00
functions.reserve_exact(module.info.functions.len());
let mut relocations = Vec::new();
2018-10-15 02:48:59 +02:00
// let imported_functions: Vec<String> = module.info.imported_funcs.iter().map(|(module, field)| {
// format!(" * {}.{}", module, field)
// }).collect();
// println!("Instance imported functions: \n{}", imported_functions.join("\n"));
2018-11-01 17:58:05 +01:00
// 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)
2018-10-17 11:22:45 +02:00
for (module, field) in module.info.imported_funcs.iter() {
2018-11-21 20:59:23 -08:00
let imported = import_object.get(&module.as_str(), &field.as_str());
2018-11-20 20:11:58 +01:00
let function: &*const u8 = match imported {
Some(ImportValue::Func(f)) => f,
None => {
2018-11-20 20:11:58 +01:00
if options.mock_missing_imports {
2018-11-21 20:59:23 -08:00
debug!(
"The import {}.{} is not provided, therefore will be mocked.",
module, field
);
2018-11-20 20:11:58 +01:00
&(mock_fn as *const u8)
2018-11-21 20:59:23 -08:00
} else {
2018-11-20 20:11:58 +01:00
return Err(ErrorKind::LinkError(format!(
"Imported function {}.{} was not provided in the import_functions",
module, field
)));
}
2018-11-21 20:59:23 -08:00
}
other => panic!("Expected function import, received {:?}", other),
};
2018-10-17 11:22:45 +02:00
// println!("GET FUNC {:?}", function);
import_functions.push(*function);
2018-10-17 11:22:45 +02:00
relocations.push(vec![]);
}
2018-11-07 11:18:55 +01:00
debug!("Instance - Compiling functions");
2018-10-15 11:46:04 +02:00
// Compile the functions (from cranelift IR to machine code)
let values: Vec<&Function> = Vec::from_iter(module.info.function_bodies.values());
// let isa: &TargetIsa = &*options.isa;
2018-11-21 20:59:23 -08:00
let compiled_funcs: Vec<CompiledFunction> = values
.par_iter()
.map(|function_body| -> CompiledFunction {
// let r = *Arc::from_raw(isa_ptr);
compile_function(&*options.isa, function_body).unwrap()
// unimplemented!()
})
.collect();
for compiled_func in compiled_funcs.into_iter() {
2018-11-21 20:59:23 -08:00
let CompiledFunction {
code_buf,
reloc_sink,
..
} = compiled_func;
// let func_offset = code_buf;
protect_codebuf(&code_buf).unwrap();
functions.push(code_buf);
2018-10-15 17:10:49 +02:00
2018-10-17 11:22:45 +02:00
// context_and_offsets.push(func_context);
2018-10-16 00:04:05 +02:00
relocations.push(reloc_sink.func_relocs);
2018-10-15 02:48:59 +02:00
}
2018-11-18 22:12:22 -08:00
// compiled_funcs?;
2018-10-15 02:48:59 +02:00
debug!("Instance - Relocating functions");
2018-10-16 00:04:05 +02:00
// For each of the functions used, we see what are the calls inside this functions
// and relocate each call to the proper memory address.
// The relocations are relative to the relocation's address plus four bytes
// TODO: Support architectures other than x64, and other reloc kinds.
for (i, function_relocs) in relocations.iter().enumerate() {
2018-10-24 11:39:00 +02:00
for ref reloc in function_relocs {
let target_func_address: isize = match reloc.target {
2018-10-16 00:04:05 +02:00
RelocationType::Normal(func_index) => {
2018-10-24 11:39:00 +02:00
get_function_addr(&FuncIndex::new(func_index as usize), &import_functions, &functions) as isize
2018-10-16 00:04:05 +02:00
},
RelocationType::CurrentMemory => {
current_memory as isize
},
RelocationType::GrowMemory => {
grow_memory as isize
2018-10-24 01:15:20 +02:00
},
RelocationType::LibCall(LibCall::CeilF32) => {
math_intrinsics::ceilf32 as isize
2018-10-24 01:15:20 +02:00
},
RelocationType::LibCall(LibCall::FloorF32) => {
math_intrinsics::floorf32 as isize
2018-10-24 01:15:20 +02:00
},
RelocationType::LibCall(LibCall::TruncF32) => {
math_intrinsics::truncf32 as isize
2018-10-24 01:15:20 +02:00
},
RelocationType::LibCall(LibCall::NearestF32) => {
math_intrinsics::nearbyintf32 as isize
},
2018-10-24 01:22:16 +02:00
RelocationType::LibCall(LibCall::CeilF64) => {
math_intrinsics::ceilf64 as isize
2018-10-24 01:22:16 +02:00
},
RelocationType::LibCall(LibCall::FloorF64) => {
math_intrinsics::floorf64 as isize
2018-10-24 01:22:16 +02:00
},
RelocationType::LibCall(LibCall::TruncF64) => {
math_intrinsics::truncf64 as isize
2018-10-24 01:22:16 +02:00
},
RelocationType::LibCall(LibCall::NearestF64) => {
math_intrinsics::nearbyintf64 as isize
2018-10-24 01:22:16 +02:00
},
2018-10-16 00:04:05 +02:00
_ => unimplemented!()
// RelocationType::Intrinsic(name) => {
// get_abi_intrinsic(name)?
// },
};
2018-10-24 11:39:00 +02:00
2018-10-17 11:22:45 +02:00
let func_addr =
get_function_addr(&FuncIndex::new(i), &import_functions, &functions);
2018-10-16 00:04:05 +02:00
match reloc.reloc {
Reloc::Abs8 => unsafe {
2018-10-17 11:22:45 +02:00
let reloc_address = func_addr.offset(reloc.offset as isize) as i64;
2018-10-16 00:04:05 +02:00
let reloc_addend = reloc.addend;
let reloc_abs = target_func_address as i64 + reloc_addend;
write_unaligned(reloc_address as *mut i64, reloc_abs);
},
Reloc::X86PCRel4 => unsafe {
2018-10-17 11:22:45 +02:00
let reloc_address = func_addr.offset(reloc.offset as isize) as isize;
2018-10-16 00:04:05 +02:00
let reloc_addend = reloc.addend as isize;
// TODO: Handle overflow.
let reloc_delta_i32 =
(target_func_address - reloc_address + reloc_addend) as i32;
write_unaligned(reloc_address as *mut i32, reloc_delta_i32);
},
_ => panic!("unsupported reloc kind"),
}
}
}
2018-10-15 02:48:59 +02:00
}
2018-10-16 00:04:05 +02:00
2018-11-20 20:11:58 +01:00
debug!("Instance - Instantiating globals");
// Instantiate Globals
let globals_data = {
let globals_count = module.info.globals.len();
// Allocate the underlying memory and initialize it to zeros
let globals_data_size = globals_count * 8;
globals.resize(globals_data_size, 0);
// cast the globals slice to a slice of i64.
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() {
2018-11-21 20:59:23 -08:00
let ImportableExportable {
entity,
import_name,
..
} = global;
2018-11-20 20:11:58 +01:00
let value: i64 = match entity.initializer {
GlobalInit::I32Const(n) => n as _,
GlobalInit::I64Const(n) => n,
GlobalInit::F32Const(f) => f as _, // unsafe { mem::transmute(f as f64) },
GlobalInit::F64Const(f) => f as _, // unsafe { mem::transmute(f) },
2018-11-21 20:59:23 -08:00
GlobalInit::GlobalRef(global_index) => globals_data[global_index.index()],
2018-11-20 20:11:58 +01:00
GlobalInit::Import() => {
2018-11-21 20:59:23 -08:00
let (module_name, field_name) = import_name
.as_ref()
.expect("Expected a import name for the global import");
let imported =
import_object.get(&module_name.as_str(), &field_name.as_str());
2018-11-20 20:11:58 +01:00
match imported {
2018-11-21 20:59:23 -08:00
Some(ImportValue::Global(value)) => *value,
None => {
if options.mock_missing_globals {
0
2018-11-21 20:59:23 -08:00
} else {
panic!(
"Imported global value was not provided ({}.{})",
module_name, field_name
)
}
}
2018-11-21 20:59:23 -08:00
_ => panic!(
"Expected global import, but received {:?} ({}.{})",
imported, module_name, field_name
),
2018-11-20 20:11:58 +01:00
}
}
};
globals_data[i] = value;
}
2018-11-20 20:11:58 +01:00
globals_data
};
2018-10-15 03:03:00 +02:00
debug!("Instance - Instantiating tables");
2018-10-15 11:46:04 +02:00
// Instantiate tables
2018-10-14 13:59:11 +02:00
{
// Reserve space for tables
2018-11-20 20:11:58 +01:00
tables.reserve_exact(module.info.tables.len());
// Get tables in module
2018-10-14 13:59:11 +02:00
for table in &module.info.tables {
2018-11-20 20:11:58 +01:00
let table: Vec<usize> = match table.import_name.as_ref() {
Some((module_name, field_name)) => {
2018-11-21 20:59:23 -08:00
let imported =
import_object.get(&module_name.as_str(), &field_name.as_str());
2018-11-20 20:11:58 +01:00
match imported {
2018-11-21 20:59:23 -08:00
Some(ImportValue::Table(t)) => t.to_vec(),
None => {
if options.mock_missing_tables {
let len = table.entity.size;
let mut v = Vec::with_capacity(len);
v.resize(len, 0);
v
2018-11-21 20:59:23 -08:00
} else {
panic!(
"Imported table value was not provided ({}.{})",
module_name, field_name
)
}
}
2018-11-21 20:59:23 -08:00
_ => panic!(
"Expected global table, but received {:?} ({}.{})",
imported, module_name, field_name
),
2018-11-20 20:11:58 +01:00
}
2018-11-21 20:59:23 -08:00
}
2018-11-20 20:11:58 +01:00
None => {
let len = table.entity.size;
let mut v = Vec::with_capacity(len);
v.resize(len, 0);
v
}
};
tables.push(table);
2018-10-14 13:59:11 +02:00
}
2018-10-14 13:59:11 +02:00
// instantiate tables
for table_element in &module.info.table_elements {
2018-11-20 20:11:58 +01:00
let base = match table_element.base {
2018-11-21 20:59:23 -08:00
Some(global_index) => globals_data[global_index.index()] as usize,
None => 0,
2018-11-20 20:11:58 +01:00
};
2018-11-14 23:10:35 -08:00
let table = &mut tables[table_element.table_index.index()];
2018-10-14 13:59:11 +02:00
for (i, func_index) in table_element.elements.iter().enumerate() {
// since the table just contains functions in the MVP
// we get the address of the specified function indexes
// to populate the table.
2018-10-13 15:31:56 +02:00
2018-10-14 13:59:11 +02:00
// let func_index = *elem_index - module.info.imported_funcs.len() as u32;
2018-10-17 11:22:45 +02:00
// let func_addr = functions[func_index.index()].as_ptr();
let func_addr = get_function_addr(&func_index, &import_functions, &functions);
2018-10-14 13:59:11 +02:00
table[base + table_element.offset + i] = func_addr as _;
}
}
2018-10-15 03:03:00 +02:00
}
2018-10-13 15:31:56 +02:00
debug!("Instance - Instantiating memories");
2018-10-15 11:46:04 +02:00
// Instantiate memories
2018-10-14 13:59:11 +02:00
{
// Reserve space for memories
2018-11-20 20:11:58 +01:00
memories.reserve_exact(module.info.memories.len());
// Get memories in module
for memory in &module.info.memories {
let memory = memory.entity;
2018-11-21 20:59:23 -08:00
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 {
2018-10-14 13:59:11 +02:00
debug_assert!(init.base.is_none(), "globalvar base not supported yet");
2018-11-06 15:51:01 +01:00
let offset = init.offset;
2018-11-14 23:10:35 -08:00
let mem_mut = memories[init.memory_index.index()].as_mut();
let to_init = &mut mem_mut[offset..offset + init.data.len()];
2018-10-14 13:59:11 +02:00
to_init.copy_from_slice(&init.data);
}
2018-10-15 03:03:00 +02:00
}
2018-10-13 15:31:56 +02:00
2018-10-16 03:21:49 +02:00
let start_func: Option<FuncIndex> =
module
.info
.start_func
.or_else(|| match module.info.exports.get("main") {
2018-11-15 13:30:00 -08:00
Some(Export::Function(index)) => Some(*index),
2018-10-16 03:21:49 +02:00
_ => None,
});
2018-11-07 11:18:55 +01:00
// TODO: Refactor repetitive code
let tables_pointer: Vec<BoundedSlice<usize>> =
tables.iter().map(|table| table[..].into()).collect();
2018-11-21 20:59:23 -08:00
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();
2018-11-07 11:18:55 +01:00
let data_pointers = DataPointers {
memories: memories_pointer[..].into(),
globals: globals_pointer,
tables: tables_pointer[..].into(),
};
// let mem = data_pointers.memories;
2018-11-07 11:18:55 +01:00
2018-10-15 02:48:59 +02:00
Ok(Instance {
data_pointers,
2018-10-15 17:10:49 +02:00
tables: Arc::new(tables.into_iter().collect()), // tables.into_iter().map(|table| RwLock::new(table)).collect()),
2018-10-14 13:59:11 +02:00
memories: Arc::new(memories.into_iter().collect()),
2018-11-07 11:18:55 +01:00
globals,
functions,
import_functions,
start_func,
2018-10-15 02:48:59 +02:00
})
2018-10-14 13:59:11 +02:00
}
2018-10-13 15:31:56 +02:00
2018-10-24 02:32:06 +02:00
pub fn memory_mut(&mut self, memory_index: usize) -> &mut LinearMemory {
let memories = Arc::get_mut(&mut self.memories).unwrap_or_else(|| {
panic!("Can't get memories as a mutable pointer (there might exist more mutable pointers to the memories)")
});
2018-10-24 02:32:06 +02:00
memories
.get_mut(memory_index)
.unwrap_or_else(|| panic!("no memory for index {}", memory_index))
}
2018-10-14 13:59:11 +02:00
pub fn memories(&self) -> Arc<Vec<LinearMemory>> {
self.memories.clone()
2018-10-13 15:31:56 +02:00
}
2018-11-06 13:18:16 +01:00
pub fn get_function_pointer(&self, func_index: FuncIndex) -> *const u8 {
get_function_addr(&func_index, &self.import_functions, &self.functions)
}
pub fn start(&self) -> Result<(), ErrorKind> {
if let Some(func_index) = self.start_func {
let func: fn(&Instance) = get_instance_function!(&self, func_index);
call_protected!(func(self))
}
else {
Ok(())
}
}
2018-10-15 15:58:06 +02:00
/// Returns a slice of the contents of allocated linear memory.
pub fn inspect_memory(&self, memory_index: usize, address: usize, len: usize) -> &[u8] {
&self
.memories
.get(memory_index)
.unwrap_or_else(|| panic!("no memory for index {}", memory_index))
.as_ref()[address..address + len]
}
2018-11-20 20:11:58 +01:00
pub fn memory_offset_addr(&self, index: usize, offset: usize) -> *const usize {
let mem = &self.memories[index];
2018-11-21 20:59:23 -08:00
unsafe { mem.mmap.as_ptr().offset(offset as isize) as *const usize }
2018-11-20 20:11:58 +01:00
}
// Shows the value of a global variable.
// pub fn inspect_global(&self, global_index: GlobalIndex, ty: ir::Type) -> &[u8] {
// let offset = global_index * 8;
// let len = ty.bytes() as usize;
// &self.globals[offset..offset + len]
2018-10-15 15:58:06 +02:00
// }
2018-10-14 20:37:42 +02:00
// pub fn start_func(&self) -> extern fn(&VmCtx) {
// self.start_func
// }
2018-10-14 13:59:11 +02:00
}
2018-10-13 15:31:56 +02:00
2018-11-20 20:11:58 +01:00
// TODO: Needs to be moved to more appropriate place
2018-11-07 14:44:17 +01:00
extern "C" fn grow_memory(size: u32, memory_index: u32, instance: &mut Instance) -> i32 {
2018-11-07 11:47:06 +01:00
// TODO: Support for only one LinearMemory for now.
2018-11-07 14:44:17 +01:00
debug_assert_eq!(
memory_index, 0,
"non-default memory_index (0) not supported yet"
);
2018-11-07 11:18:55 +01:00
let old_mem_size = instance
2018-10-24 11:39:00 +02:00
.memory_mut(memory_index as usize)
.grow(size)
2018-11-17 22:13:59 +01:00
.unwrap_or(-1);
2018-11-07 11:18:55 +01:00
2018-11-17 22:13:59 +01:00
if old_mem_size != -1 {
// Get new memory bytes
2018-11-21 20:59:23 -08:00
let new_mem_bytes = (old_mem_size as usize + size as usize) * LinearMemory::WASM_PAGE_SIZE;
2018-11-17 22:13:59 +01:00
// Update data_pointer
2018-11-21 20:59:23 -08:00
instance
.data_pointers
.memories
.get_unchecked_mut(memory_index as usize)
.len = new_mem_bytes;
2018-11-17 22:13:59 +01:00
}
2018-11-07 11:18:55 +01:00
old_mem_size
2018-10-16 00:04:05 +02:00
}
2018-11-06 13:18:16 +01:00
extern "C" fn current_memory(memory_index: u32, instance: &mut Instance) -> u32 {
2018-10-22 21:03:43 +02:00
let memory = &instance.memories[memory_index as usize];
memory.current_size() as u32
2018-10-16 00:04:05 +02:00
}