code
stringlengths
40
729k
docstring
stringlengths
22
46.3k
func_name
stringlengths
1
97
language
stringclasses
1 value
repo
stringlengths
6
48
path
stringlengths
8
176
url
stringlengths
47
228
license
stringclasses
7 values
pub fn data_and_store_mut<'a, T: 'a>( &self, ctx: impl Into<StoreContextMut<'a, T>>, ) -> (&'a mut [u8], &'a mut T) { let (memory, store) = ctx.into().store.resolve_memory_and_state_mut(self); (memory.data_mut(), store) }
Returns an exclusive slice to the bytes underlying the [`Memory`], and an exclusive reference to the user provided state. # Panics Panics if `ctx` does not own this [`Memory`].
data_and_store_mut
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/mod.rs
Apache-2.0
pub fn new(minimum: u32, maximum: Option<u32>) -> Self { let mut b = Self::builder(); b.min(u64::from(minimum)); b.max(maximum.map(u64::from)); b.build().unwrap() }
Creates a new memory type with minimum and optional maximum pages. # Panics - If the `minimum` pages exceeds the `maximum` pages. - If the `minimum` or `maximum` pages are out of bounds.
new
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/ty.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/ty.rs
Apache-2.0
pub fn new64(minimum: u64, maximum: Option<u64>) -> Self { let mut b = Self::builder(); b.memory64(true); b.min(minimum); b.max(maximum); b.build().unwrap() }
Creates a new 64-bit memory type with minimum and optional maximum pages. # Panics - If the `minimum` pages exceeds the `maximum` pages. - If the `minimum` or `maximum` pages are out of bounds. 64-bit memories are part of the [Wasm `memory64` proposal]. [Wasm `memory64` proposal]: https://github.com/WebAssembly/memory64
new64
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/ty.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/ty.rs
Apache-2.0
pub fn memory64(&mut self, memory64: bool) -> &mut Self { self.core.memory64(memory64); self }
Set whether this is a 64-bit memory type or not. By default a memory is a 32-bit, a.k.a. `false`. 64-bit memories are part of the [Wasm `memory64` proposal]. [Wasm `memory64` proposal]: https://github.com/WebAssembly/memory64
memory64
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/ty.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/ty.rs
Apache-2.0
pub fn min(&mut self, minimum: u64) -> &mut Self { self.core.min(minimum); self }
Sets the minimum number of pages the built [`MemoryType`] supports. The default minimum is `0`.
min
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/ty.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/ty.rs
Apache-2.0
pub fn max(&mut self, maximum: Option<u64>) -> &mut Self { self.core.max(maximum); self }
Sets the optional maximum number of pages the built [`MemoryType`] supports. A value of `None` means that there is no maximum number of pages. The default maximum is `None`.
max
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/ty.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/ty.rs
Apache-2.0
pub fn build(self) -> Result<MemoryType, MemoryError> { let core = self.core.build()?; Ok(MemoryType { core }) }
Finalize the construction of the [`MemoryType`]. # Errors If the chosen configuration for the constructed [`MemoryType`] is invalid.
build
rust
wasmi-labs/wasmi
crates/wasmi/src/memory/ty.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/memory/ty.rs
Apache-2.0
pub fn new(engine: &Engine) -> Self { Self { engine: engine.clone(), func_types: Vec::new(), imports: ModuleImportsBuilder::default(), funcs: Vec::new(), tables: Vec::new(), memories: Vec::new(), globals: Vec::new(), globals_init: Vec::new(), exports: Map::new(), start: None, engine_funcs: EngineFuncSpan::default(), element_segments: Box::from([]), } }
Creates a new [`ModuleHeaderBuilder`] for the given [`Engine`].
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn new(header: ModuleHeader, custom_sections: CustomSectionsBuilder) -> Self { Self { header, data_segments: DataSegments::build(), custom_sections, } }
Creates a new [`ModuleBuilder`] for the given [`Engine`].
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_func_types<T>(&mut self, func_types: T) -> Result<(), Error> where T: IntoIterator<Item = Result<FuncType, Error>>, <T as IntoIterator>::IntoIter: ExactSizeIterator, { assert!( self.func_types.is_empty(), "tried to initialize module function types twice" ); let func_types = func_types.into_iter(); // Note: we use `reserve_exact` instead of `reserve` because this // is the last extension of the vector during the build process // and optimizes conversion to boxed slice. self.func_types.reserve_exact(func_types.len()); for func_type in func_types { let func_type = func_type?; let dedup = self.engine.alloc_func_type(func_type); self.func_types.push(dedup) } Ok(()) }
Pushes the given function types to the [`Module`] under construction. # Errors If a function type fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_func_types
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_imports<T>(&mut self, imports: T) -> Result<(), Error> where T: IntoIterator<Item = Result<Import, Error>>, { for import in imports { let import = import?; let (name, kind) = import.into_name_and_type(); match kind { ExternTypeIdx::Func(func_type_idx) => { self.imports.funcs.push(name); let func_type = self.func_types[func_type_idx.into_u32() as usize]; self.funcs.push(func_type); } ExternTypeIdx::Table(table_type) => { self.imports.tables.push(name); self.tables.push(table_type); } ExternTypeIdx::Memory(memory_type) => { self.imports.memories.push(name); self.memories.push(memory_type); } ExternTypeIdx::Global(global_type) => { self.imports.globals.push(name); self.globals.push(global_type); } } } Ok(()) }
Pushes the given imports to the [`Module`] under construction. # Errors If an import fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_imports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_funcs<T>(&mut self, funcs: T) -> Result<(), Error> where T: IntoIterator<Item = Result<FuncTypeIdx, Error>>, <T as IntoIterator>::IntoIter: ExactSizeIterator, { assert_eq!( self.funcs.len(), self.imports.funcs.len(), "tried to initialize module function declarations twice" ); let funcs = funcs.into_iter(); // Note: we use `reserve_exact` instead of `reserve` because this // is the last extension of the vector during the build process // and optimizes conversion to boxed slice. self.funcs.reserve_exact(funcs.len()); self.engine_funcs = self.engine.alloc_funcs(funcs.len()); for func in funcs { let func_type_idx = func?; let func_type = self.func_types[func_type_idx.into_u32() as usize]; self.funcs.push(func_type); } Ok(()) }
Pushes the given function declarations to the [`Module`] under construction. # Errors If a function declaration fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_funcs
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_tables<T>(&mut self, tables: T) -> Result<(), Error> where T: IntoIterator<Item = Result<TableType, Error>>, <T as IntoIterator>::IntoIter: ExactSizeIterator, { assert_eq!( self.tables.len(), self.imports.tables.len(), "tried to initialize module table declarations twice" ); let tables = tables.into_iter(); // Note: we use `reserve_exact` instead of `reserve` because this // is the last extension of the vector during the build process // and optimizes conversion to boxed slice. self.tables.reserve_exact(tables.len()); for table in tables { let table = table?; self.tables.push(table); } Ok(()) }
Pushes the given table types to the [`Module`] under construction. # Errors If a table declaration fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_tables
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_memories<T>(&mut self, memories: T) -> Result<(), Error> where T: IntoIterator<Item = Result<MemoryType, Error>>, <T as IntoIterator>::IntoIter: ExactSizeIterator, { assert_eq!( self.memories.len(), self.imports.memories.len(), "tried to initialize module linear memory declarations twice" ); let memories = memories.into_iter(); // Note: we use `reserve_exact` instead of `reserve` because this // is the last extension of the vector during the build process // and optimizes conversion to boxed slice. self.memories.reserve_exact(memories.len()); for memory in memories { let memory = memory?; self.memories.push(memory); } Ok(()) }
Pushes the given linear memory types to the [`Module`] under construction. # Errors If a linear memory declaration fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_memories
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_globals<T>(&mut self, globals: T) -> Result<(), Error> where T: IntoIterator<Item = Result<Global, Error>>, <T as IntoIterator>::IntoIter: ExactSizeIterator, { assert_eq!( self.globals.len(), self.imports.globals.len(), "tried to initialize module global variable declarations twice" ); let globals = globals.into_iter(); // Note: we use `reserve_exact` instead of `reserve` because this // is the last extension of the vector during the build process // and optimizes conversion to boxed slice. self.globals.reserve_exact(globals.len()); for global in globals { let global = global?; let (global_decl, global_init) = global.into_type_and_init(); self.globals.push(global_decl); self.globals_init.push(global_init); } Ok(()) }
Pushes the given global variables to the [`Module`] under construction. # Errors If a global variable declaration fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_globals
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_exports<T>(&mut self, exports: T) -> Result<(), Error> where T: IntoIterator<Item = Result<(Box<str>, ExternIdx), Error>>, { assert!( self.exports.is_empty(), "tried to initialize module export declarations twice" ); self.exports = exports.into_iter().collect::<Result<Map<_, _>, _>>()?; Ok(()) }
Pushes the given exports to the [`Module`] under construction. # Errors If an export declaration fails to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_exports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn set_start(&mut self, start: FuncIdx) { if let Some(old_start) = &self.start { panic!("encountered multiple start functions: {old_start:?}, {start:?}") } self.start = Some(start); }
Sets the start function of the [`Module`] to the given index. # Panics If this function has already been called on the same [`ModuleBuilder`].
set_start
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn push_element_segments<T>(&mut self, elements: T) -> Result<(), Error> where T: IntoIterator<Item = Result<ElementSegment, Error>>, <T as IntoIterator>::IntoIter: ExactSizeIterator, { assert!( self.element_segments.is_empty(), "tried to initialize module export declarations twice" ); self.element_segments = elements.into_iter().collect::<Result<Box<[_]>, _>>()?; Ok(()) }
Pushes the given table elements to the [`Module`] under construction. # Errors If any of the table elements fail to validate. # Panics If this function has already been called on the same [`ModuleBuilder`].
push_element_segments
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn finish(self, engine: &Engine) -> Module { Module { inner: Arc::new(ModuleInner { engine: engine.clone(), header: self.header, data_segments: self.data_segments.finish(), custom_sections: self.custom_sections.finish(), }), } }
Finishes construction of the WebAssembly [`Module`].
finish
rust
wasmi-labs/wasmi
crates/wasmi/src/module/builder.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/builder.rs
Apache-2.0
pub fn len(&self) -> usize { self.len as usize }
Returns the number of bytes of the [`ActiveDataSegment`] as `usize`.
len
rust
wasmi-labs/wasmi
crates/wasmi/src/module/data.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/data.rs
Apache-2.0
pub fn passive_data_segment_bytes(&self) -> Option<PassiveDataSegmentBytes> { match &self.inner { DataSegmentInner::Active { .. } => None, DataSegmentInner::Passive { bytes } => Some(bytes.clone()), } }
Returns the bytes of the [`DataSegment`] if passive, otherwise returns `None`.
passive_data_segment_bytes
rust
wasmi-labs/wasmi
crates/wasmi/src/module/data.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/data.rs
Apache-2.0
pub fn reserve(&mut self, count: usize) { assert!( self.segments.capacity() == 0, "must not reserve multiple times" ); self.segments.reserve(count); }
Reserves space for at least `additional` new [`DataSegments`].
reserve
rust
wasmi-labs/wasmi
crates/wasmi/src/module/data.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/data.rs
Apache-2.0
pub fn push_data_segment(&mut self, segment: wasmparser::Data) -> Result<(), Error> { match segment.kind { wasmparser::DataKind::Passive => { self.segments.push(DataSegment { inner: DataSegmentInner::Passive { bytes: PassiveDataSegmentBytes { bytes: segment.data.into(), }, }, }); } wasmparser::DataKind::Active { memory_index, offset_expr, } => { let memory_index = MemoryIdx::from(memory_index); let offset = ConstExpr::new(offset_expr); let len = u32::try_from(segment.data.len()).unwrap_or_else(|_x| { panic!("data segment has too many bytes: {}", segment.data.len()) }); self.bytes.extend_from_slice(segment.data); self.segments.push(DataSegment { inner: DataSegmentInner::Active(ActiveDataSegment { memory_index, offset, len, }), }); } } Ok(()) }
Pushes another [`DataSegment`] to the [`DataSegmentsBuilder`]. # Panics If an active data segment has too many bytes.
push_data_segment
rust
wasmi-labs/wasmi
crates/wasmi/src/module/data.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/data.rs
Apache-2.0
pub fn new(kind: wasmparser::ExternalKind, index: u32) -> Result<Self, Error> { match kind { wasmparser::ExternalKind::Func => Ok(ExternIdx::Func(FuncIdx(index))), wasmparser::ExternalKind::Table => Ok(ExternIdx::Table(TableIdx(index))), wasmparser::ExternalKind::Memory => Ok(ExternIdx::Memory(MemoryIdx(index))), wasmparser::ExternalKind::Global => Ok(ExternIdx::Global(GlobalIdx::from(index))), wasmparser::ExternalKind::Tag => { panic!("wasmi does not support the `exception-handling` Wasm proposal") } } }
Create a new [`ExternIdx`] from the given [`wasmparser::ExternalKind`] and `index`. # Errors If an unsupported external definition is encountered.
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/export.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/export.rs
Apache-2.0
pub(super) fn new(module: &'module Module) -> Self { Self { exports: module.module_header().exports.iter(), module, } }
Creates a new [`ModuleExportsIter`] from the given [`Module`].
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/export.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/export.rs
Apache-2.0
pub fn into_type_and_init(self) -> (GlobalType, ConstExpr) { (self.global_type, self.init_expr) }
Splits the [`Global`] into its global type and its global initializer.
into_type_and_init
rust
wasmi-labs/wasmi
crates/wasmi/src/module/global.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/global.rs
Apache-2.0
pub fn into_name_and_type(self) -> (ImportName, ExternTypeIdx) { (self.name, self.kind) }
Splits the [`Import`] into its raw parts. # Note This allows to reuse some allocations in certain cases.
into_name_and_type
rust
wasmi-labs/wasmi
crates/wasmi/src/module/import.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/import.rs
Apache-2.0
pub fn constant<T>(value: T) -> Self where T: Into<Val>, { Self::Const(ConstOp { value: value.into().into(), }) }
Creates a new constant operator for the given `value`.
constant
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn global(global_index: u32) -> Self { Self::Global(GlobalOp { global_index }) }
Creates a new global operator with the given index.
global
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn funcref(function_index: u32) -> Self { Self::FuncRef(FuncRefOp { function_index }) }
Creates a new global operator with the given index.
funcref
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn expr<T>(expr: T) -> Self where T: Fn(&dyn EvalContext) -> Option<UntypedVal> + Send + Sync + 'static, { Self::Expr(ExprOp { expr: Box::new(expr), }) }
Creates a new expression operator for the given `expr`.
expr
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn new(expr: wasmparser::ConstExpr<'_>) -> Self { /// A buffer required for translation of Wasm const expressions. type TranslationBuffer = SmallVec<[Op; 3]>; /// Convenience function to create the various expression operators. fn expr_op<Lhs, Rhs, T>(stack: &mut TranslationBuffer, expr: fn(Lhs, Rhs) -> T) where Lhs: From<UntypedVal> + 'static, Rhs: From<UntypedVal> + 'static, T: 'static, UntypedVal: From<T>, { let rhs = stack .pop() .expect("must have rhs operator on the stack due to Wasm validation"); let lhs = stack .pop() .expect("must have lhs operator on the stack due to Wasm validation"); let op = match (lhs, rhs) { (Op::Const(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::Const(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::Const(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::Const(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), }; stack.push(op); } let mut reader = expr.get_operators_reader(); let mut stack = TranslationBuffer::new(); loop { let op = reader.read().unwrap_or_else(|error| { panic!("unexpectedly encountered invalid const expression operator: {error}") }); match op { wasmparser::Operator::I32Const { value } => { stack.push(Op::constant(value)); } wasmparser::Operator::I64Const { value } => { stack.push(Op::constant(value)); } wasmparser::Operator::F32Const { value } => { stack.push(Op::constant(F32::from_bits(value.bits()))); } wasmparser::Operator::F64Const { value } => { stack.push(Op::constant(F64::from_bits(value.bits()))); } #[cfg(feature = "simd")] wasmparser::Operator::V128Const { value } => { stack.push(Op::constant(V128::from(value.i128() as u128))); } wasmparser::Operator::GlobalGet { global_index } => { stack.push(Op::global(global_index)); } wasmparser::Operator::RefNull { hty } => { let value = match hty { wasmparser::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func, } => Val::from(FuncRef::null()), wasmparser::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern, } => Val::from(ExternRef::null()), invalid => { panic!("encountered invalid heap type for `ref.null`: {invalid:?}") } }; stack.push(Op::constant(value)); } wasmparser::Operator::RefFunc { function_index } => { stack.push(Op::funcref(function_index)); } wasmparser::Operator::I32Add => expr_op(&mut stack, wasm::i32_add), wasmparser::Operator::I32Sub => expr_op(&mut stack, wasm::i32_sub), wasmparser::Operator::I32Mul => expr_op(&mut stack, wasm::i32_mul), wasmparser::Operator::I64Add => expr_op(&mut stack, wasm::i64_add), wasmparser::Operator::I64Sub => expr_op(&mut stack, wasm::i64_sub), wasmparser::Operator::I64Mul => expr_op(&mut stack, wasm::i64_mul), wasmparser::Operator::End => break, op => panic!("encountered invalid Wasm const expression operator: {op:?}"), }; } reader .ensure_end() .expect("due to Wasm validation this is guaranteed to succeed"); let op = stack .pop() .expect("due to Wasm validation must have one operator on the stack"); assert!( stack.is_empty(), "due to Wasm validation operator stack must be empty now" ); Self { op } }
Creates a new [`ConstExpr`] from the given Wasm [`ConstExpr`]. # Note The constructor assumes that Wasm validation already succeeded on the input Wasm [`ConstExpr`].
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
fn expr_op<Lhs, Rhs, T>(stack: &mut TranslationBuffer, expr: fn(Lhs, Rhs) -> T) where Lhs: From<UntypedVal> + 'static, Rhs: From<UntypedVal> + 'static, T: 'static, UntypedVal: From<T>, { let rhs = stack .pop() .expect("must have rhs operator on the stack due to Wasm validation"); let lhs = stack .pop() .expect("must have lhs operator on the stack due to Wasm validation"); let op = match (lhs, rhs) { (Op::Const(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::Const(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::Const(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::Const(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::Global(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::FuncRef(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::Const(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::Global(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::FuncRef(rhs)) => def_expr!(lhs, rhs, expr), (Op::Expr(lhs), Op::Expr(rhs)) => def_expr!(lhs, rhs, expr), }; stack.push(op); }
Convenience function to create the various expression operators.
expr_op
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn new_funcref(function_index: u32) -> Self { Self { op: Op::FuncRef(FuncRefOp { function_index }), } }
Create a new `ref.func x` [`ConstExpr`]. # Note Required for setting up table elements.
new_funcref
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn funcref(&self) -> Option<FuncIdx> { if let Op::FuncRef(op) = &self.op { return Some(FuncIdx::from(op.function_index)); } None }
Returns `Some(index)` if the [`ConstExpr`] is a `funcref(index)`. Otherwise returns `None`.
funcref
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn eval_with_context<G, F>(&self, global_get: G, func_get: F) -> Option<UntypedVal> where G: Fn(u32) -> Val, F: Fn(u32) -> FuncRef, { /// Context that wraps closures representing partial evaluation contexts. struct WrappedEvalContext<G, F> { /// Wrapped context for global variables. global_get: G, /// Wrapped context for functions. func_get: F, } impl<G, F> EvalContext for WrappedEvalContext<G, F> where G: Fn(u32) -> Val, F: Fn(u32) -> FuncRef, { fn get_global(&self, index: u32) -> Option<Val> { Some((self.global_get)(index)) } fn get_func(&self, index: u32) -> Option<FuncRef> { Some((self.func_get)(index)) } } self.eval(&WrappedEvalContext::<G, F> { global_get, func_get, }) }
Evaluates the [`ConstExpr`] given a context for globals and functions. Returns `None` if a non-const expression operand is encountered or the provided globals and functions context returns `None`. # Note This is useful for evaluation of [`ConstExpr`] during bytecode execution.
eval_with_context
rust
wasmi-labs/wasmi
crates/wasmi/src/module/init_expr.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/init_expr.rs
Apache-2.0
pub fn get_func_type(&self, func_type_idx: FuncTypeIdx) -> &DedupFuncType { &self.inner.func_types[func_type_idx.into_u32() as usize] }
Returns the [`FuncType`] at the given index.
get_func_type
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_type_of_func(&self, func_idx: FuncIdx) -> &DedupFuncType { &self.inner.funcs[func_idx.into_u32() as usize] }
Returns the [`FuncType`] of the indexed function.
get_type_of_func
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_type_of_global(&self, global_idx: GlobalIdx) -> &GlobalType { &self.inner.globals[global_idx.into_u32() as usize] }
Returns the [`GlobalType`] of the indexed global variable.
get_type_of_global
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_type_of_memory(&self, memory_idx: MemoryIdx) -> &MemoryType { &self.inner.memories[memory_idx.into_u32() as usize] }
Returns the [`MemoryType`] of the indexed Wasm memory.
get_type_of_memory
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_type_of_table(&self, table_idx: TableIdx) -> &TableType { &self.inner.tables[table_idx.into_u32() as usize] }
Returns the [`TableType`] of the indexed Wasm table.
get_type_of_table
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_engine_func(&self, func_idx: FuncIdx) -> Option<EngineFunc> { let index = func_idx.into_u32(); let len_imported = self.inner.imports.len_funcs() as u32; let index = index.checked_sub(len_imported)?; // Note: It is a bug if this index access is out of bounds // therefore we panic here instead of using `get`. Some(self.inner.engine_funcs.get_or_panic(index)) }
Returns the [`EngineFunc`] for the given [`FuncIdx`]. Returns `None` if [`FuncIdx`] refers to an imported function.
get_engine_func
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_func_index(&self, func: EngineFunc) -> Option<FuncIdx> { let position = self.inner.engine_funcs.position(func)?; let len_imports = self.inner.imports.len_funcs as u32; Some(FuncIdx::from(position + len_imports)) }
Returns the [`FuncIdx`] for the given [`EngineFunc`].
get_func_index
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_global(&self, global_idx: GlobalIdx) -> (&GlobalType, Option<&ConstExpr>) { let index = global_idx.into_u32() as usize; let len_imports = self.inner.imports.len_globals(); let global_type = self.get_type_of_global(global_idx); if index < len_imports { // The index refers to an imported global without init value. (global_type, None) } else { // The index refers to an internal global with init value. let init_expr = &self.inner.globals_init[index - len_imports]; (global_type, Some(init_expr)) } }
Returns the global variable type and optional initial value.
get_global
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn new(engine: &Engine, wasm: impl AsRef<[u8]>) -> Result<Self, Error> { let wasm = wasm.as_ref(); #[cfg(feature = "wat")] let wasm = &wat::parse_bytes(wasm)?[..]; ModuleParser::new(engine).parse_buffered(wasm) }
Creates a new Wasm [`Module`] from the given Wasm bytecode buffer. # Note - This parses, validates and translates the buffered Wasm bytecode. - The `wasm` may be encoded as WebAssembly binary (`.wasm`) or as WebAssembly text format (`.wat`). # Errors - If the Wasm bytecode is malformed or fails to validate. - If the Wasm bytecode violates restrictions set in the [`Config`] used by the `engine`. - If Wasmi cannot translate the Wasm bytecode. [`Config`]: crate::Config
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub unsafe fn new_unchecked(engine: &Engine, wasm: &[u8]) -> Result<Self, Error> { let parser = ModuleParser::new(engine); unsafe { parser.parse_buffered_unchecked(wasm) } }
Creates a new Wasm [`Module`] from the given Wasm bytecode buffer. # Note This parses and translates the buffered Wasm bytecode. # Safety - This does _not_ validate the Wasm bytecode. - It is the caller's responsibility that the Wasm bytecode is valid. - It is the caller's responsibility that the Wasm bytecode adheres to the restrictions set by the used [`Config`] of the `engine`. - Violating the above rules is undefined behavior. # Errors - If the Wasm bytecode is malformed or contains invalid sections. - If the Wasm bytecode fails to be compiled by Wasmi. [`Config`]: crate::Config
new_unchecked
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn validate(engine: &Engine, wasm: &[u8]) -> Result<(), Error> { let mut validator = Validator::new_with_features(engine.config().wasm_features()); for payload in Parser::new(0).parse_all(wasm) { let payload = payload?; if let ValidPayload::Func(func_to_validate, func_body) = validator.payload(&payload)? { func_to_validate .into_validator(FuncValidatorAllocations::default()) .validate(&func_body)?; } } Ok(()) }
Validates `wasm` as a WebAssembly binary given the configuration (via [`Config`]) in `engine`. This function performs Wasm validation of the binary input WebAssembly module and returns either `Ok`` or `Err`` depending on the results of the validation. The [`Config`] of the `engine` is used for Wasm validation which indicates which WebAssembly features are valid and invalid for the validation. # Note - The input `wasm` must be in binary form, the text format is not accepted by this function. - This will only validate the `wasm` but not try to translate it. Therefore `Module::new` might still fail if translation of the Wasm binary input fails to translate via the Wasmi [`Engine`]. - Validation automatically happens as part of [`Module::new`]. # Errors If Wasm validation for `wasm` fails for the given [`Config`] provided via `engine`. [`Config`]: crate::Config
validate
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn imports(&self) -> ModuleImportsIter { let header = self.module_header(); let len_imported_funcs = header.imports.len_funcs; let len_imported_globals = header.imports.len_globals; ModuleImportsIter { engine: self.engine(), names: header.imports.items.iter(), funcs: header.funcs[..len_imported_funcs].iter(), tables: header.tables.iter(), memories: header.memories.iter(), globals: header.globals[..len_imported_globals].iter(), } }
Returns an iterator over the imports of the [`Module`].
imports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub(crate) fn internal_funcs(&self) -> InternalFuncsIter { let header = self.module_header(); let len_imported = header.imports.len_funcs; // We skip the first `len_imported` elements in `funcs` // since they refer to imported and not internally defined // functions. let funcs = &header.funcs[len_imported..]; let engine_funcs = header.engine_funcs.iter(); assert_eq!(funcs.len(), engine_funcs.len()); InternalFuncsIter { iter: funcs.iter().zip(engine_funcs), } }
Returns an iterator over the internally defined [`Func`]. [`Func`]: [`crate::Func`]
internal_funcs
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
fn internal_memories(&self) -> SliceIter<MemoryType> { let header = self.module_header(); let len_imported = header.imports.len_memories; // We skip the first `len_imported` elements in `memories` // since they refer to imported and not internally defined // linear memories. let memories = &header.memories[len_imported..]; memories.iter() }
Returns an iterator over the [`MemoryType`] of internal linear memories.
internal_memories
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
fn internal_tables(&self) -> SliceIter<TableType> { let header = self.module_header(); let len_imported = header.imports.len_tables; // We skip the first `len_imported` elements in `memories` // since they refer to imported and not internally defined // linear memories. let tables = &header.tables[len_imported..]; tables.iter() }
Returns an iterator over the [`TableType`] of internal tables.
internal_tables
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
fn internal_globals(&self) -> InternalGlobalsIter { let header = self.module_header(); let len_imported = header.imports.len_globals; // We skip the first `len_imported` elements in `globals` // since they refer to imported and not internally defined // global variables. let globals = header.globals[len_imported..].iter(); let global_inits = header.globals_init.iter(); InternalGlobalsIter { iter: globals.zip(global_inits), } }
Returns an iterator over the internally defined [`Global`].
internal_globals
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn get_export(&self, name: &str) -> Option<ExternType> { let idx = self.module_header().exports.get(name).copied()?; let ty = self.get_extern_type(idx); Some(ty) }
Looks up an export in this [`Module`] by its `name`. Returns `None` if no export with the name was found. # Note This function will return the type of an export with the given `name`.
get_export
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
fn get_extern_type(&self, idx: ExternIdx) -> ExternType { let header = self.module_header(); match idx { ExternIdx::Func(index) => { let dedup = &header.funcs[index.into_u32() as usize]; let func_type = self.engine().resolve_func_type(dedup, Clone::clone); ExternType::Func(func_type) } ExternIdx::Table(index) => { let table_type = header.tables[index.into_u32() as usize]; ExternType::Table(table_type) } ExternIdx::Memory(index) => { let memory_type = header.memories[index.into_u32() as usize]; ExternType::Memory(memory_type) } ExternIdx::Global(index) => { let global_type = header.globals[index.into_u32() as usize]; ExternType::Global(global_type) } } }
Returns the [`ExternType`] for a given [`ExternIdx`]. # Note This function assumes that the given [`ExternType`] is valid.
get_extern_type
rust
wasmi-labs/wasmi
crates/wasmi/src/module/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/mod.rs
Apache-2.0
pub fn new(engine: &Engine) -> Self { let mut parser = WasmParser::new(0); parser.set_features(engine.config().wasm_features()); Self { engine: engine.clone(), validator: None, parser, engine_funcs: 0, eof: false, } }
Creates a new [`ModuleParser`] for the given [`Engine`].
new
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_end(&mut self, offset: usize) -> Result<(), Error> { if let Some(validator) = &mut self.validator { // This only checks if the number of code section entries and data segments match // their expected numbers thus we must avoid this check in header-only mode because // otherwise we will receive errors for unmatched data section entries. validator.end(offset)?; } Ok(()) }
Processes the end of the Wasm binary.
process_end
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_types( &mut self, section: TypeSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(validator) = &mut self.validator { validator.type_section(&section)?; } let limits = self.engine.config().get_enforced_limits(); let func_types = section.into_iter().map(|result| { let ty = result?.into_types().next().unwrap(); let func_ty = ty.unwrap_func(); if let Some(limit) = limits.max_params { if func_ty.params().len() > limit { return Err(Error::from(EnforcedLimitsError::TooManyParameters { limit, })); } } if let Some(limit) = limits.max_results { if func_ty.results().len() > limit { return Err(Error::from(EnforcedLimitsError::TooManyResults { limit })); } } Ok(FuncType::from_wasmparser(func_ty)) }); header.push_func_types(func_types)?; Ok(()) }
Processes the Wasm type section. # Note This extracts all function types into the [`Module`] under construction. # Errors If an unsupported function type is encountered.
process_types
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_imports( &mut self, section: ImportSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(validator) = &mut self.validator { validator.import_section(&section)?; } let imports = section .into_iter() .map(|import| import.map(Import::from).map_err(Error::from)); header.push_imports(imports)?; Ok(()) }
Processes the Wasm import section. # Note This extracts all imports into the [`Module`] under construction. # Errors - If an import fails to validate. - If an unsupported import declaration is encountered.
process_imports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_functions( &mut self, section: FunctionSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(limit) = self.engine.config().get_enforced_limits().max_functions { if section.count() > limit { return Err(Error::from(EnforcedLimitsError::TooManyFunctions { limit })); } } if let Some(validator) = &mut self.validator { validator.function_section(&section)?; } let funcs = section .into_iter() .map(|func| func.map(FuncTypeIdx::from).map_err(Error::from)); header.push_funcs(funcs)?; Ok(()) }
Process module function declarations. # Note This extracts all function declarations into the [`Module`] under construction. # Errors If a function declaration fails to validate.
process_functions
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_tables( &mut self, section: TableSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(limit) = self.engine.config().get_enforced_limits().max_tables { if section.count() > limit { return Err(Error::from(EnforcedLimitsError::TooManyTables { limit })); } } if let Some(validator) = &mut self.validator { validator.table_section(&section)?; } let tables = section.into_iter().map(|table| match table { Ok(table) => { assert!(matches!(table.init, wasmparser::TableInit::RefNull)); Ok(TableType::from_wasmparser(table.ty)) } Err(err) => Err(err.into()), }); header.push_tables(tables)?; Ok(()) }
Process module table declarations. # Note This extracts all table declarations into the [`Module`] under construction. # Errors If a table declaration fails to validate.
process_tables
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_memories( &mut self, section: MemorySectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(limit) = self.engine.config().get_enforced_limits().max_memories { if section.count() > limit { return Err(Error::from(EnforcedLimitsError::TooManyMemories { limit })); } } if let Some(validator) = &mut self.validator { validator.memory_section(&section)?; } let memories = section .into_iter() .map(|memory| memory.map(MemoryType::from_wasmparser).map_err(Error::from)); header.push_memories(memories)?; Ok(()) }
Process module linear memory declarations. # Note This extracts all linear memory declarations into the [`Module`] under construction. # Errors If a linear memory declaration fails to validate.
process_memories
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_globals( &mut self, section: GlobalSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(limit) = self.engine.config().get_enforced_limits().max_globals { if section.count() > limit { return Err(Error::from(EnforcedLimitsError::TooManyGlobals { limit })); } } if let Some(validator) = &mut self.validator { validator.global_section(&section)?; } let globals = section .into_iter() .map(|global| global.map(Global::from).map_err(Error::from)); header.push_globals(globals)?; Ok(()) }
Process module global variable declarations. # Note This extracts all global variable declarations into the [`Module`] under construction. # Errors If a global variable declaration fails to validate.
process_globals
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_exports( &mut self, section: ExportSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(validator) = &mut self.validator { validator.export_section(&section)?; } let exports = section.into_iter().map(|export| { let export = export?; let field: Box<str> = export.name.into(); let idx = ExternIdx::new(export.kind, export.index)?; Ok((field, idx)) }); header.push_exports(exports)?; Ok(()) }
Process module export declarations. # Note This extracts all export declarations into the [`Module`] under construction. # Errors If an export declaration fails to validate.
process_exports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_start( &mut self, func: u32, range: Range<usize>, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(validator) = &mut self.validator { validator.start_section(func, &range)?; } header.set_start(FuncIdx::from(func)); Ok(()) }
Process module start section. # Note This sets the start function for the [`Module`] under construction. # Errors If the start function declaration fails to validate.
process_start
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_element( &mut self, section: ElementSectionReader, header: &mut ModuleHeaderBuilder, ) -> Result<(), Error> { if let Some(limit) = self .engine .config() .get_enforced_limits() .max_element_segments { if section.count() > limit { return Err(Error::from(EnforcedLimitsError::TooManyElementSegments { limit, })); } } if let Some(validator) = &mut self.validator { validator.element_section(&section)?; } let segments = section .into_iter() .map(|segment| segment.map(ElementSegment::from).map_err(Error::from)); header.push_element_segments(segments)?; Ok(()) }
Process module table element segments. # Note This extracts all table element segments into the [`Module`] under construction. # Errors If any of the table element segments fail to validate.
process_element
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_data_count(&mut self, count: u32, range: Range<usize>) -> Result<(), Error> { if let Some(limit) = self.engine.config().get_enforced_limits().max_data_segments { if count > limit { return Err(Error::from(EnforcedLimitsError::TooManyDataSegments { limit, })); } } if let Some(validator) = &mut self.validator { validator.data_count_section(count, &range)?; } Ok(()) }
Process module data count section. # Note This is part of the bulk memory operations Wasm proposal and not yet supported by Wasmi.
process_data_count
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_data( &mut self, section: DataSectionReader, builder: &mut ModuleBuilder, ) -> Result<(), Error> { if let Some(limit) = self.engine.config().get_enforced_limits().max_data_segments { if section.count() > limit { return Err(Error::from(EnforcedLimitsError::TooManyDataSegments { limit, })); } } if let Some(validator) = &mut self.validator { // Note: data section does not belong to the Wasm module header. // // Also benchmarks show that validation of the data section can be very costly. validator.data_section(&section)?; } builder.reserve_data_segments(section.count() as usize); for segment in section { builder.push_data_segment(segment?)?; } Ok(()) }
Process module linear memory data segments. # Note This extracts all table elements into the [`Module`] under construction. # Errors If any of the table elements fail to validate.
process_data
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_code_start( &mut self, count: u32, range: Range<usize>, size: u32, ) -> Result<(), Error> { let enforced_limits = self.engine.config().get_enforced_limits(); if let Some(limit) = enforced_limits.max_functions { if count > limit { return Err(Error::from(EnforcedLimitsError::TooManyFunctions { limit })); } } if let Some(limit) = enforced_limits.min_avg_bytes_per_function { if size >= limit.req_funcs_bytes { let limit = limit.min_avg_bytes_per_function; let avg = size / count; if avg < limit { return Err(Error::from(EnforcedLimitsError::MinAvgBytesPerFunction { limit, avg, })); } } } if let Some(validator) = &mut self.validator { validator.code_section_start(count, &range)?; } Ok(()) }
Process module code section start. # Note This currently does not do a lot but it might become important in the future if we add parallel translation of function bodies to prepare for the translation. # Errors If the code start section fails to validate.
process_code_start
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn next_func(&mut self, header: &ModuleHeader) -> (FuncIdx, EngineFunc) { let index = self.engine_funcs; let engine_func = header.inner.engine_funcs.get_or_panic(index); self.engine_funcs += 1; // We have to adjust the initial func reference to the first // internal function before we process any of the internal functions. let len_func_imports = u32::try_from(header.inner.imports.len_funcs()) .unwrap_or_else(|_| panic!("too many imported functions")); let func_idx = FuncIdx::from(index + len_func_imports); (func_idx, engine_func) }
Returns the next `FuncIdx` for processing of its function body.
next_func
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_code_entry( &mut self, func_body: FunctionBody, bytes: &[u8], header: &ModuleHeader, ) -> Result<(), Error> { let (func, engine_func) = self.next_func(header); let module = header.clone(); let offset = func_body.get_binary_reader().original_position(); let func_to_validate = match &mut self.validator { Some(validator) => Some(validator.code_section_entry(&func_body)?), None => None, }; self.engine .translate_func(func, engine_func, offset, bytes, module, func_to_validate)?; Ok(()) }
Process a single module code section entry. # Note This contains the local variables and Wasm instructions of a single function body. This procedure is translating the Wasm bytecode into Wasmi bytecode. # Errors If the function body fails to validate.
process_code_entry
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
fn process_invalid_payload(&mut self, payload: Payload<'_>) -> Result<(), Error> { if let Some(validator) = &mut self.validator { if let Err(error) = validator.payload(&payload) { return Err(Error::from(error)); } } panic!("encountered unsupported, unexpected or malformed Wasm payload: {payload:?}") }
Process an unexpected, unsupported or malformed Wasm module section payload.
process_invalid_payload
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser.rs
Apache-2.0
pub(crate) fn instantiate<I>( &self, mut context: impl AsContextMut, externals: I, ) -> Result<InstancePre, Error> where I: IntoIterator<Item = Extern, IntoIter: ExactSizeIterator>, { let mut context = context.as_context_mut().store; if !context.can_create_more_instances(1) { return Err(Error::from(InstantiationError::TooManyInstances)); } let handle = context.as_context_mut().store.inner.alloc_instance(); let mut builder = InstanceEntity::build(self); self.extract_imports(&context, &mut builder, externals)?; self.extract_functions(&mut context, &mut builder, handle); self.extract_tables(&mut context, &mut builder)?; self.extract_memories(&mut context, &mut builder)?; self.extract_globals(&mut context, &mut builder); self.extract_exports(&mut builder); self.extract_start_fn(&mut builder); self.initialize_table_elements(&mut context, &mut builder)?; self.initialize_memory_data(&mut context, &mut builder)?; // At this point the module instantiation is nearly done. // The only thing that is missing is to run the `start` function. Ok(InstancePre::new(handle, builder)) }
Instantiates a new [`Instance`] from the given compiled [`Module`]. Uses the given `context` to store the instance data to. The given `externals` are joined with the imports in the same order in which they occurred. # Note This is a very low-level API. For a more high-level API users should use the corresponding instantiation methods provided by the [`Linker`]. # Errors If the given `externals` do not satisfy the required imports, e.g. if an externally provided [`Func`] has a different function signature than required by the module import. [`Linker`]: struct.Linker.html [`Func`]: [`crate::Func`]
instantiate
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_imports<I>( &self, store: impl AsContext, builder: &mut InstanceEntityBuilder, externals: I, ) -> Result<(), InstantiationError> where I: IntoIterator<Item = Extern, IntoIter: ExactSizeIterator>, { let imports = self.imports(); let externals = externals.into_iter(); if imports.len() != externals.len() { return Err(InstantiationError::InvalidNumberOfImports { required: imports.len(), given: externals.len(), }); } for (import, external) in imports.zip(externals) { match (import.ty(), external) { (ExternType::Func(expected_signature), Extern::Func(func)) => { let actual_signature = func.ty(&store); if &actual_signature != expected_signature { return Err(InstantiationError::FuncTypeMismatch { actual: actual_signature, expected: expected_signature.clone(), }); } builder.push_func(func); } (ExternType::Table(required), Extern::Table(table)) => { let imported = table.dynamic_ty(&store); if !imported.is_subtype_of(required) { return Err(InstantiationError::TableTypeMismatch { expected: *required, actual: imported, }); } builder.push_table(table); } (ExternType::Memory(required), Extern::Memory(memory)) => { let imported = memory.dynamic_ty(&store); if !imported.is_subtype_of(required) { return Err(InstantiationError::MemoryTypeMismatch { expected: *required, actual: imported, }); } builder.push_memory(memory); } (ExternType::Global(required), Extern::Global(global)) => { let imported = global.ty(&store); let required = *required; if imported != required { return Err(InstantiationError::GlobalTypeMismatch { expected: required, actual: imported, }); } builder.push_global(global); } (expected_import, actual_extern_val) => { return Err(InstantiationError::ImportsExternalsMismatch { expected: expected_import.clone(), actual: actual_extern_val, }); } } } Ok(()) }
Extract the Wasm imports from the module and zips them with the given external values. This also stores imported references into the [`Instance`] under construction. # Errors - If too few or too many external values are given for the required module imports. - If the zipped import and given external have mismatching types, e.g. on index `i` the module requires a function import but on index `i` the externals provide a global variable external value. - If the externally provided [`Table`], [`Memory`], [`Func`] or [`Global`] has a type mismatch with the expected module import type. [`Func`]: [`crate::Func`]
extract_imports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_functions( &self, mut context: impl AsContextMut, builder: &mut InstanceEntityBuilder, handle: Instance, ) { for (func_type, func_body) in self.internal_funcs() { let wasm_func = WasmFuncEntity::new(func_type, func_body, handle); let func = context .as_context_mut() .store .inner .alloc_func(wasm_func.into()); builder.push_func(func); } }
Extracts the Wasm functions from the module and stores them into the [`Store`]. This also stores [`Func`] references into the [`Instance`] under construction. [`Store`]: struct.Store.html [`Func`]: [`crate::Func`]
extract_functions
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_tables( &self, mut context: impl AsContextMut, builder: &mut InstanceEntityBuilder, ) -> Result<(), InstantiationError> { let ctx = context.as_context_mut().store; if !ctx.can_create_more_tables(self.len_tables()) { return Err(InstantiationError::TooManyTables); } for table_type in self.internal_tables().copied() { let init = Val::default(table_type.element()); let table = Table::new(context.as_context_mut(), table_type, init).map_err(|error| { let error = match error.kind() { ErrorKind::Table(error) => *error, error => panic!("unexpected error: {error}"), }; InstantiationError::FailedToInstantiateTable(error) })?; builder.push_table(table); } Ok(()) }
Extracts the Wasm tables from the module and stores them into the [`Store`]. This also stores [`Table`] references into the [`Instance`] under construction. [`Store`]: struct.Store.html
extract_tables
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_memories( &self, mut context: impl AsContextMut, builder: &mut InstanceEntityBuilder, ) -> Result<(), InstantiationError> { let ctx = context.as_context_mut().store; if !ctx.can_create_more_memories(self.len_memories()) { return Err(InstantiationError::TooManyMemories); } for memory_type in self.internal_memories().copied() { let memory = Memory::new(context.as_context_mut(), memory_type).map_err(|error| { let error = match error.kind() { ErrorKind::Memory(error) => *error, error => panic!("unexpected error: {error}"), }; InstantiationError::FailedToInstantiateMemory(error) })?; builder.push_memory(memory); } Ok(()) }
Extracts the Wasm linear memories from the module and stores them into the [`Store`]. This also stores [`Memory`] references into the [`Instance`] under construction. [`Store`]: struct.Store.html
extract_memories
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_globals(&self, mut context: impl AsContextMut, builder: &mut InstanceEntityBuilder) { for (global_type, global_init) in self.internal_globals() { let value_type = global_type.content(); let init_value = Self::eval_init_expr(context.as_context_mut(), builder, global_init); let mutability = global_type.mutability(); let global = Global::new( context.as_context_mut(), init_value.with_type(value_type), mutability, ); builder.push_global(global); } }
Extracts the Wasm global variables from the module and stores them into the [`Store`]. This also stores [`Global`] references into the [`Instance`] under construction. [`Store`]: struct.Store.html
extract_globals
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn eval_init_expr( context: impl AsContext, builder: &InstanceEntityBuilder, init_expr: &ConstExpr, ) -> UntypedVal { init_expr .eval_with_context( |global_index| builder.get_global(global_index).get(&context), |func_index| FuncRef::new(builder.get_func(func_index)), ) .expect("must evaluate to proper value") }
Evaluates the given initializer expression using the partially constructed [`Instance`].
eval_init_expr
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_exports(&self, builder: &mut InstanceEntityBuilder) { for (field, idx) in &self.module_header().exports { let external = match idx { export::ExternIdx::Func(func_index) => { let func_index = func_index.into_u32(); let func = builder.get_func(func_index); Extern::Func(func) } export::ExternIdx::Table(table_index) => { let table_index = table_index.into_u32(); let table = builder.get_table(table_index); Extern::Table(table) } export::ExternIdx::Memory(memory_index) => { let memory_index = memory_index.into_u32(); let memory = builder.get_memory(memory_index); Extern::Memory(memory) } export::ExternIdx::Global(global_index) => { let global_index = global_index.into_u32(); let global = builder.get_global(global_index); Extern::Global(global) } }; builder.push_export(field, external); } }
Extracts the Wasm exports from the module and registers them into the [`Instance`].
extract_exports
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn extract_start_fn(&self, builder: &mut InstanceEntityBuilder) { if let Some(start_fn) = self.module_header().start { builder.set_start(start_fn) } }
Extracts the optional start function for the build instance.
extract_start_fn
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn initialize_table_elements( &self, mut context: impl AsContextMut, builder: &mut InstanceEntityBuilder, ) -> Result<(), Error> { for segment in &self.module_header().element_segments[..] { let get_global = |index| builder.get_global(index); let get_func = |index| builder.get_func(index); let element = ElementSegment::new(context.as_context_mut(), segment, get_func, get_global); if let ElementSegmentKind::Active(active) = segment.kind() { let dst_index = u64::from(Self::eval_init_expr( context.as_context(), builder, active.offset(), )); let table = builder.get_table(active.table_index().into_u32()); // Note: This checks not only that the elements in the element segments properly // fit into the table at the given offset but also that the element segment // consists of at least 1 element member. let len_table = table.size(&context); let len_items = element.size(&context); dst_index .checked_add(u64::from(len_items)) .filter(|&max_index| max_index <= len_table) .ok_or(InstantiationError::ElementSegmentDoesNotFit { table, table_index: dst_index, len: len_items, })?; let (table, elem) = context .as_context_mut() .store .inner .resolve_table_and_element_mut(&table, &element); table.init(elem.as_ref(), dst_index, 0, len_items, None)?; // Now drop the active element segment as commanded by the Wasm spec. elem.drop_items(); } builder.push_element_segment(element); } Ok(()) }
Initializes the [`Instance`] tables with the Wasm element segments of the [`Module`].
initialize_table_elements
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
fn initialize_memory_data( &self, mut context: impl AsContextMut, builder: &mut InstanceEntityBuilder, ) -> Result<(), Error> { for segment in &self.inner.data_segments { let segment = match segment { InitDataSegment::Active { memory_index, offset, bytes, } => { let memory = builder.get_memory(memory_index.into_u32()); let offset = Self::eval_init_expr(context.as_context(), builder, offset); let offset = match usize::try_from(u64::from(offset)) { Ok(offset) => offset, Err(_) => return Err(Error::from(MemoryError::OutOfBoundsAccess)), }; memory.write(context.as_context_mut(), offset, bytes)?; DataSegment::new_active(context.as_context_mut()) } InitDataSegment::Passive { bytes } => { DataSegment::new_passive(context.as_context_mut(), bytes) } }; builder.push_data_segment(segment); } Ok(()) }
Initializes the [`Instance`] linear memories with the Wasm data segments of the [`Module`].
initialize_memory_data
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/mod.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/mod.rs
Apache-2.0
pub fn start(self, mut context: impl AsContextMut) -> Result<Instance, Error> { let opt_start_index = self.start_fn(); context .as_context_mut() .store .inner .initialize_instance(self.handle, self.builder.finish()); if let Some(start_index) = opt_start_index { let start_func = self .handle .get_func_by_index(&mut context, start_index) .unwrap_or_else(|| { panic!("encountered invalid start function after validation: {start_index}") }); start_func.call(context.as_context_mut(), &[], &mut [])? } Ok(self.handle) }
Runs the `start` function of the [`Instance`] and returns its handle. # Note This finishes the instantiation procedure. # Errors If executing the `start` function traps. # Panics If the `start` function is invalid albeit successful validation.
start
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/pre.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/pre.rs
Apache-2.0
pub fn ensure_no_start( self, mut context: impl AsContextMut, ) -> Result<Instance, InstantiationError> { if let Some(index) = self.start_fn() { return Err(InstantiationError::UnexpectedStartFn { index }); } context .as_context_mut() .store .inner .initialize_instance(self.handle, self.builder.finish()); Ok(self.handle) }
Finishes instantiation ensuring that no `start` function exists. # Errors If a `start` function exists that needs to be called for conformant module instantiation.
ensure_no_start
rust
wasmi-labs/wasmi
crates/wasmi/src/module/instantiate/pre.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/instantiate/pre.rs
Apache-2.0
pub fn parse_buffered(mut self, buffer: &[u8]) -> Result<Module, Error> { let features = self.engine.config().wasm_features(); self.validator = Some(Validator::new_with_features(features)); // SAFETY: we just pre-populated the Wasm module parser with a validator // thus calling this method is safe. unsafe { self.parse_buffered_impl(buffer) } }
Starts parsing and validating the Wasm bytecode stream. Returns the compiled and validated Wasm [`Module`] upon success. # Errors If the Wasm bytecode stream fails to validate.
parse_buffered
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
pub unsafe fn parse_buffered_unchecked(self, buffer: &[u8]) -> Result<Module, Error> { unsafe { self.parse_buffered_impl(buffer) } }
Starts parsing and validating the Wasm bytecode stream. Returns the compiled and validated Wasm [`Module`] upon success. # Safety The caller is responsible to make sure that the provided `stream` yields valid WebAssembly bytecode. # Errors If the Wasm bytecode stream fails to validate.
parse_buffered_unchecked
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
unsafe fn parse_buffered_impl(mut self, mut buffer: &[u8]) -> Result<Module, Error> { let mut custom_sections = CustomSectionsBuilder::default(); let header = Self::parse_buffered_header(&mut self, &mut buffer, &mut custom_sections)?; let builder = Self::parse_buffered_code(&mut self, &mut buffer, header, custom_sections)?; let module = Self::parse_buffered_data(&mut self, &mut buffer, builder)?; Ok(module) }
Starts parsing and validating the Wasm bytecode stream. Returns the compiled and validated Wasm [`Module`] upon success. # Safety The caller is responsible to either 1) Populate the [`ModuleParser`] with a [`Validator`] prior to calling this method, OR; 2) Make sure that the provided `stream` yields valid WebAssembly bytecode. Otherwise this method has undefined behavior. # Errors If the Wasm bytecode stream fails to validate.
parse_buffered_impl
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
fn next_payload<'a>(&mut self, buffer: &mut &'a [u8]) -> Result<(usize, Payload<'a>), Error> { match self.parser.parse(&buffer[..], true)? { Chunk::Parsed { consumed, payload } => Ok((consumed, payload)), Chunk::NeedMoreData(_hint) => { // This is not possible since `eof` is always true. unreachable!() } } }
Fetch next Wasm module payload and adust the `buffer`. # Errors If the parsed Wasm is malformed.
next_payload
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
fn consume_buffer<'a>(consumed: usize, buffer: &mut &'a [u8]) -> &'a [u8] { let (consumed, remaining) = buffer.split_at(consumed); *buffer = remaining; consumed }
Consumes the parts of the buffer that have been processed.
consume_buffer
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
fn parse_buffered_header( &mut self, buffer: &mut &[u8], custom_sections: &mut CustomSectionsBuilder, ) -> Result<ModuleHeader, Error> { let mut header = ModuleHeaderBuilder::new(&self.engine); loop { let (consumed, payload) = self.next_payload(buffer)?; match payload { Payload::Version { num, encoding, range, } => self.process_version(num, encoding, range), Payload::TypeSection(section) => self.process_types(section, &mut header), Payload::ImportSection(section) => self.process_imports(section, &mut header), Payload::FunctionSection(section) => self.process_functions(section, &mut header), Payload::TableSection(section) => self.process_tables(section, &mut header), Payload::MemorySection(section) => self.process_memories(section, &mut header), Payload::GlobalSection(section) => self.process_globals(section, &mut header), Payload::ExportSection(section) => self.process_exports(section, &mut header), Payload::StartSection { func, range } => { self.process_start(func, range, &mut header) } Payload::ElementSection(section) => self.process_element(section, &mut header), Payload::DataCountSection { count, range } => self.process_data_count(count, range), Payload::CodeSectionStart { count, range, size } => { self.process_code_start(count, range, size)?; Self::consume_buffer(consumed, buffer); break; } Payload::DataSection(_) => break, Payload::End(_) => break, Payload::CustomSection(reader) => { self.process_custom_section(custom_sections, reader) } unexpected => self.process_invalid_payload(unexpected), }?; Self::consume_buffer(consumed, buffer); } Ok(header.finish()) }
Parse the Wasm module header. - The Wasm module header is the set of all sections that appear before the Wasm code section. - We separate parsing of the Wasm module header since the information of the Wasm module header is required for translating the Wasm code section. # Errors If the Wasm bytecode stream fails to parse or validate.
parse_buffered_header
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
fn parse_buffered_code( &mut self, buffer: &mut &[u8], header: ModuleHeader, custom_sections: CustomSectionsBuilder, ) -> Result<ModuleBuilder, Error> { loop { let (consumed, payload) = self.next_payload(buffer)?; match payload { Payload::CodeSectionEntry(func_body) => { // Note: Unfortunately the `wasmparser` crate is missing an API // to return the byte slice for the respective code section // entry payload. Please remove this work around as soon as // such an API becomes available. Self::consume_buffer(consumed, buffer); let bytes = func_body.as_bytes(); self.process_code_entry(func_body, bytes, &header)?; } _ => break, } } Ok(ModuleBuilder::new(header, custom_sections)) }
Parse the Wasm code section entries. We separate parsing of the Wasm code section since most of a Wasm module is made up of code section entries which we can parse and validate more efficiently by serving them with a specialized routine. # Errors If the Wasm bytecode stream fails to parse or validate.
parse_buffered_code
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
fn parse_buffered_data( &mut self, buffer: &mut &[u8], mut builder: ModuleBuilder, ) -> Result<Module, Error> { loop { let (consumed, payload) = self.next_payload(buffer)?; match payload { Payload::DataSection(section) => { self.process_data(section, &mut builder)?; } Payload::End(offset) => { self.process_end(offset)?; break; } Payload::CustomSection(reader) => { self.process_custom_section(&mut builder.custom_sections, reader)?; } invalid => self.process_invalid_payload(invalid)?, } Self::consume_buffer(consumed, buffer); } Ok(builder.finish(&self.engine)) }
Parse the Wasm data section and finalize parsing. We separate parsing of the Wasm data section since it is the only Wasm section that comes after the Wasm code section that we have to separate out for technical reasons. # Errors If the Wasm bytecode stream fails to parse or validate.
parse_buffered_data
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/buffered.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/buffered.rs
Apache-2.0
pub fn parse_streaming(mut self, stream: impl Read) -> Result<Module, Error> { let features = self.engine.config().wasm_features(); self.validator = Some(Validator::new_with_features(features)); // SAFETY: we just pre-populated the Wasm module parser with a validator // thus calling this method is safe. unsafe { self.parse_streaming_impl(stream) } }
Parses and validates the Wasm bytecode `stream`. Returns the compiled and validated Wasm [`Module`] upon success. # Errors If the Wasm bytecode stream fails to validate.
parse_streaming
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/streaming.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/streaming.rs
Apache-2.0
pub unsafe fn parse_streaming_unchecked(self, stream: impl Read) -> Result<Module, Error> { unsafe { self.parse_streaming_impl(stream) } }
Parses the Wasm bytecode `stream` without Wasm validation. Returns the compiled and validated Wasm [`Module`] upon success. # Safety The caller is responsible to make sure that the provided `stream` yields valid WebAssembly bytecode. # Errors If the Wasm bytecode stream fails to validate.
parse_streaming_unchecked
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/streaming.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/streaming.rs
Apache-2.0
unsafe fn parse_streaming_impl(mut self, mut stream: impl Read) -> Result<Module, Error> { let mut custom_sections = CustomSectionsBuilder::default(); let mut buffer = ParseBuffer::default(); let header = Self::parse_streaming_header( &mut self, &mut stream, &mut buffer, &mut custom_sections, )?; let builder = Self::parse_streaming_code( &mut self, &mut stream, &mut buffer, header, custom_sections, )?; let module = Self::parse_streaming_data(&mut self, &mut stream, &mut buffer, builder)?; Ok(module) }
Starts parsing and validating the Wasm bytecode stream. Returns the compiled and validated Wasm [`Module`] upon success. # Safety The caller is responsible to either 1) Populate the [`ModuleParser`] with a [`Validator`] prior to calling this method, OR; 2) Make sure that the provided `stream` yields valid WebAssembly bytecode. Otherwise this method has undefined behavior. # Errors If the Wasm bytecode stream fails to validate.
parse_streaming_impl
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/streaming.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/streaming.rs
Apache-2.0
fn parse_streaming_header( &mut self, stream: &mut impl Read, buffer: &mut ParseBuffer, custom_sections: &mut CustomSectionsBuilder, ) -> Result<ModuleHeader, Error> { let mut header = ModuleHeaderBuilder::new(&self.engine); loop { match self.parser.parse(&buffer[..], self.eof)? { Chunk::NeedMoreData(hint) => { self.eof = ParseBuffer::pull_bytes(buffer, hint, stream)?; if self.eof { break; } } Chunk::Parsed { consumed, payload } => { match payload { Payload::Version { num, encoding, range, } => self.process_version(num, encoding, range), Payload::TypeSection(section) => self.process_types(section, &mut header), Payload::ImportSection(section) => { self.process_imports(section, &mut header) } Payload::FunctionSection(section) => { self.process_functions(section, &mut header) } Payload::TableSection(section) => self.process_tables(section, &mut header), Payload::MemorySection(section) => { self.process_memories(section, &mut header) } Payload::GlobalSection(section) => { self.process_globals(section, &mut header) } Payload::ExportSection(section) => { self.process_exports(section, &mut header) } Payload::StartSection { func, range } => { self.process_start(func, range, &mut header) } Payload::ElementSection(section) => { self.process_element(section, &mut header) } Payload::DataCountSection { count, range } => { self.process_data_count(count, range) } Payload::CodeSectionStart { count, range, size } => { self.process_code_start(count, range, size)?; ParseBuffer::consume(buffer, consumed); break; } Payload::DataSection(_) => break, Payload::End(_) => break, Payload::CustomSection(reader) => { self.process_custom_section(custom_sections, reader) } unexpected => self.process_invalid_payload(unexpected), }?; // Cut away the parts from the intermediate buffer that have already been parsed. ParseBuffer::consume(buffer, consumed); } } } Ok(header.finish()) }
Parse the Wasm module header. - The Wasm module header is the set of all sections that appear before the Wasm code section. - We separate parsing of the Wasm module header since the information of the Wasm module header is required for translating the Wasm code section. # Errors If the Wasm bytecode stream fails to parse or validate.
parse_streaming_header
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/streaming.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/streaming.rs
Apache-2.0
fn parse_streaming_code( &mut self, stream: &mut impl Read, buffer: &mut ParseBuffer, header: ModuleHeader, custom_sections: CustomSectionsBuilder, ) -> Result<ModuleBuilder, Error> { loop { match self.parser.parse(&buffer[..], self.eof)? { Chunk::NeedMoreData(hint) => { self.eof = ParseBuffer::pull_bytes(buffer, hint, stream)?; } Chunk::Parsed { consumed, payload } => { match payload { Payload::CodeSectionEntry(func_body) => { // Note: Unfortunately the `wasmparser` crate is missing an API // to return the byte slice for the respective code section // entry payload. Please remove this work around as soon as // such an API becomes available. let bytes = func_body.as_bytes(); self.process_code_entry(func_body, bytes, &header)?; } _ => break, } // Cut away the parts from the intermediate buffer that have already been parsed. ParseBuffer::consume(buffer, consumed); } } } Ok(ModuleBuilder::new(header, custom_sections)) }
Parse the Wasm code section entries. We separate parsing of the Wasm code section since most of a Wasm module is made up of code section entries which we can parse and validate more efficiently by serving them with a specialized routine. # Errors If the Wasm bytecode stream fails to parse or validate.
parse_streaming_code
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/streaming.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/streaming.rs
Apache-2.0
fn parse_streaming_data( &mut self, stream: &mut impl Read, buffer: &mut ParseBuffer, mut builder: ModuleBuilder, ) -> Result<Module, Error> { loop { match self.parser.parse(&buffer[..], self.eof)? { Chunk::NeedMoreData(hint) => { self.eof = ParseBuffer::pull_bytes(buffer, hint, stream)?; } Chunk::Parsed { consumed, payload } => { match payload { Payload::DataSection(section) => { self.process_data(section, &mut builder)?; } Payload::End(offset) => { self.process_end(offset)?; ParseBuffer::consume(buffer, consumed); break; } Payload::CustomSection(reader) => { self.process_custom_section(&mut builder.custom_sections, reader)? } invalid => self.process_invalid_payload(invalid)?, } // Cut away the parts from the intermediate buffer that have already been parsed. ParseBuffer::consume(buffer, consumed); } } } Ok(builder.finish(&self.engine)) }
Parse the Wasm data section and finalize parsing. We separate parsing of the Wasm data section since it is the only Wasm section that comes after the Wasm code section that we have to separate out for technical reasons. # Errors If the Wasm bytecode stream fails to parse or validate.
parse_streaming_data
rust
wasmi-labs/wasmi
crates/wasmi/src/module/parser/streaming.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/module/parser/streaming.rs
Apache-2.0
pub fn new(engine: &Engine) -> Self { let config = engine.config(); let fuel_enabled = config.get_consume_fuel(); let fuel_costs = config.fuel_costs().clone(); let fuel = Fuel::new(fuel_enabled, fuel_costs); StoreInner { engine: engine.clone(), store_idx: StoreIdx::new(), funcs: Arena::new(), memories: Arena::new(), tables: Arena::new(), globals: Arena::new(), instances: Arena::new(), datas: Arena::new(), elems: Arena::new(), extern_objects: Arena::new(), fuel, } }
Creates a new [`StoreInner`] for the given [`Engine`].
new
rust
wasmi-labs/wasmi
crates/wasmi/src/store/inner.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/inner.rs
Apache-2.0
pub fn fuel_mut(&mut self) -> &mut Fuel { &mut self.fuel }
Returns an exclusive reference to the [`Fuel`] counters.
fuel_mut
rust
wasmi-labs/wasmi
crates/wasmi/src/store/inner.rs
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/inner.rs
Apache-2.0