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 |
|---|---|---|---|---|---|---|---|
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
|
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
|
pub(super) fn wrap_stored<Idx>(&self, entity_idx: Idx) -> Stored<Idx> {
Stored::new(self.store_idx, entity_idx)
}
|
Wraps an entity `Idx` (index type) as a [`Stored<Idx>`] type.
# Note
[`Stored<Idx>`] associates an `Idx` type with the internal store index.
This way wrapped indices cannot be misused with incorrect [`StoreInner`] instances.
|
wrap_stored
|
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(super) fn unwrap_stored<Idx>(&self, stored: &Stored<Idx>) -> Idx
where
Idx: ArenaIndex + Debug,
{
stored.entity_index(self.store_idx).unwrap_or_else(|| {
panic!(
"entity reference ({:?}) does not belong to store {:?}",
stored, self.store_idx,
)
})
}
|
Unwraps the given [`Stored<Idx>`] reference and returns the `Idx`.
# Panics
If the [`Stored<Idx>`] does not originate from this [`StoreInner`].
|
unwrap_stored
|
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 alloc_global(&mut self, global: CoreGlobal) -> Global {
let global = self.globals.alloc(global);
Global::from_inner(self.wrap_stored(global))
}
|
Allocates a new [`CoreGlobal`] and returns a [`Global`] reference to it.
|
alloc_global
|
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 alloc_table(&mut self, table: CoreTable) -> Table {
let table = self.tables.alloc(table);
Table::from_inner(self.wrap_stored(table))
}
|
Allocates a new [`CoreTable`] and returns a [`Table`] reference to it.
|
alloc_table
|
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 alloc_memory(&mut self, memory: CoreMemory) -> Memory {
let memory = self.memories.alloc(memory);
Memory::from_inner(self.wrap_stored(memory))
}
|
Allocates a new [`CoreMemory`] and returns a [`Memory`] reference to it.
|
alloc_memory
|
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 alloc_data_segment(&mut self, segment: DataSegmentEntity) -> DataSegment {
let segment = self.datas.alloc(segment);
DataSegment::from_inner(self.wrap_stored(segment))
}
|
Allocates a new [`DataSegmentEntity`] and returns a [`DataSegment`] reference to it.
|
alloc_data_segment
|
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 alloc_element_segment(&mut self, segment: CoreElementSegment) -> ElementSegment {
let segment = self.elems.alloc(segment);
ElementSegment::from_inner(self.wrap_stored(segment))
}
|
Allocates a new [`CoreElementSegment`] and returns a [`ElementSegment`] reference to it.
|
alloc_element_segment
|
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 alloc_extern_object(&mut self, object: ExternObjectEntity) -> ExternObject {
let object = self.extern_objects.alloc(object);
ExternObject::from_inner(self.wrap_stored(object))
}
|
Allocates a new [`ExternObjectEntity`] and returns a [`ExternObject`] reference to it.
|
alloc_extern_object
|
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 alloc_instance(&mut self) -> Instance {
let instance = self.instances.alloc(InstanceEntity::uninitialized());
Instance::from_inner(self.wrap_stored(instance))
}
|
Allocates a new uninitialized [`InstanceEntity`] and returns an [`Instance`] reference to it.
# Note
- This will create an uninitialized dummy [`InstanceEntity`] as a place holder
for the returned [`Instance`]. Using this uninitialized [`Instance`] will result
in a runtime panic.
- The returned [`Instance`] must later be initialized via the [`StoreInner::initialize_instance`]
method. Afterwards the [`Instance`] may be used.
|
alloc_instance
|
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 initialize_instance(&mut self, instance: Instance, init: InstanceEntity) {
assert!(
init.is_initialized(),
"encountered an uninitialized new instance entity: {init:?}",
);
let idx = self.unwrap_stored(instance.as_inner());
let uninit = self
.instances
.get_mut(idx)
.unwrap_or_else(|| panic!("missing entity for the given instance: {instance:?}"));
assert!(
!uninit.is_initialized(),
"encountered an already initialized instance: {uninit:?}",
);
*uninit = init;
}
|
Initializes the [`Instance`] using the given [`InstanceEntity`].
# Note
After this operation the [`Instance`] is initialized and can be used.
# Panics
- If the [`Instance`] does not belong to the [`StoreInner`].
- If the [`Instance`] is unknown to the [`StoreInner`].
- If the [`Instance`] has already been initialized.
- If the given [`InstanceEntity`] is itself not initialized, yet.
|
initialize_instance
|
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
|
fn resolve<'a, Idx, Entity>(
&self,
idx: &Stored<Idx>,
entities: &'a Arena<Idx, Entity>,
) -> &'a Entity
where
Idx: ArenaIndex + Debug,
{
let idx = self.unwrap_stored(idx);
entities
.get(idx)
.unwrap_or_else(|| panic!("failed to resolve stored entity: {idx:?}"))
}
|
Returns a shared reference to the entity indexed by the given `idx`.
# Panics
- If the indexed entity does not originate from this [`StoreInner`].
- If the entity index cannot be resolved to its entity.
|
resolve
|
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
|
fn resolve_mut<Idx, Entity>(idx: Idx, entities: &mut Arena<Idx, Entity>) -> &mut Entity
where
Idx: ArenaIndex + Debug,
{
entities
.get_mut(idx)
.unwrap_or_else(|| panic!("failed to resolve stored entity: {idx:?}"))
}
|
Returns an exclusive reference to the entity indexed by the given `idx`.
# Note
Due to borrow checking issues this method takes an already unwrapped
`Idx` unlike the [`StoreInner::resolve`] method.
# Panics
- If the entity index cannot be resolved to its entity.
|
resolve_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
|
pub fn resolve_func_type(&self, func_type: &DedupFuncType) -> FuncType {
self.resolve_func_type_with(func_type, FuncType::clone)
}
|
Returns the [`FuncType`] associated to the given [`DedupFuncType`].
# Panics
- If the [`DedupFuncType`] does not originate from this [`StoreInner`].
- If the [`DedupFuncType`] cannot be resolved to its entity.
|
resolve_func_type
|
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 resolve_func_type_with<R>(
&self,
func_type: &DedupFuncType,
f: impl FnOnce(&FuncType) -> R,
) -> R {
self.engine.resolve_func_type(func_type, f)
}
|
Calls `f` on the [`FuncType`] associated to the given [`DedupFuncType`] and returns the result.
# Panics
- If the [`DedupFuncType`] does not originate from this [`StoreInner`].
- If the [`DedupFuncType`] cannot be resolved to its entity.
|
resolve_func_type_with
|
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 resolve_global(&self, global: &Global) -> &CoreGlobal {
self.resolve(global.as_inner(), &self.globals)
}
|
Returns a shared reference to the [`CoreGlobal`] associated to the given [`Global`].
# Panics
- If the [`Global`] does not originate from this [`StoreInner`].
- If the [`Global`] cannot be resolved to its entity.
|
resolve_global
|
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 resolve_global_mut(&mut self, global: &Global) -> &mut CoreGlobal {
let idx = self.unwrap_stored(global.as_inner());
Self::resolve_mut(idx, &mut self.globals)
}
|
Returns an exclusive reference to the [`CoreGlobal`] associated to the given [`Global`].
# Panics
- If the [`Global`] does not originate from this [`StoreInner`].
- If the [`Global`] cannot be resolved to its entity.
|
resolve_global_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
|
pub fn resolve_table(&self, table: &Table) -> &CoreTable {
self.resolve(table.as_inner(), &self.tables)
}
|
Returns a shared reference to the [`CoreTable`] associated to the given [`Table`].
# Panics
- If the [`Table`] does not originate from this [`StoreInner`].
- If the [`Table`] cannot be resolved to its entity.
|
resolve_table
|
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 resolve_table_mut(&mut self, table: &Table) -> &mut CoreTable {
let idx = self.unwrap_stored(table.as_inner());
Self::resolve_mut(idx, &mut self.tables)
}
|
Returns an exclusive reference to the [`CoreTable`] associated to the given [`Table`].
# Panics
- If the [`Table`] does not originate from this [`StoreInner`].
- If the [`Table`] cannot be resolved to its entity.
|
resolve_table_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
|
pub fn resolve_table_and_element_mut(
&mut self,
table: &Table,
elem: &ElementSegment,
) -> (&mut CoreTable, &mut CoreElementSegment) {
let table_idx = self.unwrap_stored(table.as_inner());
let elem_idx = self.unwrap_stored(elem.as_inner());
let table = Self::resolve_mut(table_idx, &mut self.tables);
let elem = Self::resolve_mut(elem_idx, &mut self.elems);
(table, elem)
}
|
Returns an exclusive reference to the [`CoreTable`] and [`CoreElementSegment`] associated to `table` and `elem`.
# Panics
- If the [`Table`] does not originate from this [`StoreInner`].
- If the [`Table`] cannot be resolved to its entity.
- If the [`ElementSegment`] does not originate from this [`StoreInner`].
- If the [`ElementSegment`] cannot be resolved to its entity.
|
resolve_table_and_element_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
|
pub fn resolve_table_and_fuel_mut(&mut self, table: &Table) -> (&mut CoreTable, &mut Fuel) {
let idx = self.unwrap_stored(table.as_inner());
let table = Self::resolve_mut(idx, &mut self.tables);
let fuel = &mut self.fuel;
(table, fuel)
}
|
Returns both
- an exclusive reference to the [`CoreTable`] associated to the given [`Table`]
- an exclusive reference to the [`Fuel`] of the [`StoreInner`].
# Panics
- If the [`Table`] does not originate from this [`StoreInner`].
- If the [`Table`] cannot be resolved to its entity.
|
resolve_table_and_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
|
pub fn resolve_table_init_params(
&mut self,
table: &Table,
segment: &ElementSegment,
) -> (&mut CoreTable, &CoreElementSegment, &mut Fuel) {
let mem_idx = self.unwrap_stored(table.as_inner());
let elem_idx = segment.as_inner();
let elem = self.resolve(elem_idx, &self.elems);
let mem = Self::resolve_mut(mem_idx, &mut self.tables);
let fuel = &mut self.fuel;
(mem, elem, fuel)
}
|
Returns the following data:
- A shared reference to the [`InstanceEntity`] associated to the given [`Instance`].
- An exclusive reference to the [`CoreTable`] associated to the given [`Table`].
- A shared reference to the [`CoreElementSegment`] associated to the given [`ElementSegment`].
- An exclusive reference to the [`Fuel`] of the [`StoreInner`].
# Note
This method exists to properly handle use cases where
otherwise the Rust borrow-checker would not accept.
# Panics
- If the [`Instance`] does not originate from this [`StoreInner`].
- If the [`Instance`] cannot be resolved to its entity.
- If the [`Table`] does not originate from this [`StoreInner`].
- If the [`Table`] cannot be resolved to its entity.
- If the [`ElementSegment`] does not originate from this [`StoreInner`].
- If the [`ElementSegment`] cannot be resolved to its entity.
|
resolve_table_init_params
|
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 resolve_element_segment(&self, segment: &ElementSegment) -> &CoreElementSegment {
self.resolve(segment.as_inner(), &self.elems)
}
|
Returns a shared reference to the [`CoreElementSegment`] associated to the given [`ElementSegment`].
# Panics
- If the [`ElementSegment`] does not originate from this [`StoreInner`].
- If the [`ElementSegment`] cannot be resolved to its entity.
|
resolve_element_segment
|
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 resolve_element_segment_mut(
&mut self,
segment: &ElementSegment,
) -> &mut CoreElementSegment {
let idx = self.unwrap_stored(segment.as_inner());
Self::resolve_mut(idx, &mut self.elems)
}
|
Returns an exclusive reference to the [`CoreElementSegment`] associated to the given [`ElementSegment`].
# Panics
- If the [`ElementSegment`] does not originate from this [`StoreInner`].
- If the [`ElementSegment`] cannot be resolved to its entity.
|
resolve_element_segment_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
|
pub fn resolve_memory<'a>(&'a self, memory: &Memory) -> &'a CoreMemory {
self.resolve(memory.as_inner(), &self.memories)
}
|
Returns a shared reference to the [`CoreMemory`] associated to the given [`Memory`].
# Panics
- If the [`Memory`] does not originate from this [`StoreInner`].
- If the [`Memory`] cannot be resolved to its entity.
|
resolve_memory
|
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 resolve_memory_mut<'a>(&'a mut self, memory: &Memory) -> &'a mut CoreMemory {
let idx = self.unwrap_stored(memory.as_inner());
Self::resolve_mut(idx, &mut self.memories)
}
|
Returns an exclusive reference to the [`CoreMemory`] associated to the given [`Memory`].
# Panics
- If the [`Memory`] does not originate from this [`StoreInner`].
- If the [`Memory`] cannot be resolved to its entity.
|
resolve_memory_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
|
pub fn resolve_memory_init_params(
&mut self,
memory: &Memory,
segment: &DataSegment,
) -> (&mut CoreMemory, &DataSegmentEntity, &mut Fuel) {
let mem_idx = self.unwrap_stored(memory.as_inner());
let data_idx = segment.as_inner();
let data = self.resolve(data_idx, &self.datas);
let mem = Self::resolve_mut(mem_idx, &mut self.memories);
let fuel = &mut self.fuel;
(mem, data, fuel)
}
|
Returns the following data:
- An exclusive reference to the [`CoreMemory`] associated to the given [`Memory`].
- A shared reference to the [`DataSegmentEntity`] associated to the given [`DataSegment`].
- An exclusive reference to the [`Fuel`] of the [`StoreInner`].
# Note
This method exists to properly handle use cases where
otherwise the Rust borrow-checker would not accept.
# Panics
- If the [`Memory`] does not originate from this [`StoreInner`].
- If the [`Memory`] cannot be resolved to its entity.
- If the [`DataSegment`] does not originate from this [`StoreInner`].
- If the [`DataSegment`] cannot be resolved to its entity.
|
resolve_memory_init_params
|
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 resolve_memory_pair_and_fuel(
&mut self,
fst: &Memory,
snd: &Memory,
) -> (&mut CoreMemory, &mut CoreMemory, &mut Fuel) {
let fst = self.unwrap_stored(fst.as_inner());
let snd = self.unwrap_stored(snd.as_inner());
let (fst, snd) = self.memories.get_pair_mut(fst, snd).unwrap_or_else(|| {
panic!("failed to resolve stored pair of entities: {fst:?} and {snd:?}")
});
let fuel = &mut self.fuel;
(fst, snd, fuel)
}
|
Returns an exclusive pair of references to the [`CoreMemory`] associated to the given [`Memory`]s.
# Panics
- If the [`Memory`] does not originate from this [`StoreInner`].
- If the [`Memory`] cannot be resolved to its entity.
|
resolve_memory_pair_and_fuel
|
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 resolve_data_segment_mut(&mut self, segment: &DataSegment) -> &mut DataSegmentEntity {
let idx = self.unwrap_stored(segment.as_inner());
Self::resolve_mut(idx, &mut self.datas)
}
|
Returns an exclusive reference to the [`DataSegmentEntity`] associated to the given [`DataSegment`].
# Panics
- If the [`DataSegment`] does not originate from this [`StoreInner`].
- If the [`DataSegment`] cannot be resolved to its entity.
|
resolve_data_segment_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
|
pub fn resolve_instance(&self, instance: &Instance) -> &InstanceEntity {
self.resolve(instance.as_inner(), &self.instances)
}
|
Returns a shared reference to the [`InstanceEntity`] associated to the given [`Instance`].
# Panics
- If the [`Instance`] does not originate from this [`StoreInner`].
- If the [`Instance`] cannot be resolved to its entity.
|
resolve_instance
|
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 resolve_external_object(&self, object: &ExternObject) -> &ExternObjectEntity {
self.resolve(object.as_inner(), &self.extern_objects)
}
|
Returns a shared reference to the [`ExternObjectEntity`] associated to the given [`ExternObject`].
# Panics
- If the [`ExternObject`] does not originate from this [`StoreInner`].
- If the [`ExternObject`] cannot be resolved to its entity.
|
resolve_external_object
|
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 alloc_func(&mut self, func: FuncEntity) -> Func {
let idx = self.funcs.alloc(func);
Func::from_inner(self.wrap_stored(idx))
}
|
Allocates a new Wasm or host [`FuncEntity`] and returns a [`Func`] reference to it.
|
alloc_func
|
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 resolve_func(&self, func: &Func) -> &FuncEntity {
let entity_index = self.unwrap_stored(func.as_inner());
self.funcs.get(entity_index).unwrap_or_else(|| {
panic!("failed to resolve stored Wasm or host function: {entity_index:?}")
})
}
|
Returns a shared reference to the associated entity of the Wasm or host function.
# Panics
- If the [`Func`] does not originate from this [`StoreInner`].
- If the [`Func`] cannot be resolved to its entity.
|
resolve_func
|
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 data_mut(&mut self) -> &mut T {
&mut self.typed.data
}
|
Returns an exclusive reference to the user provided data owned by this [`Store`].
|
data_mut
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
fn call_host_func(
&mut self,
func: &HostFuncEntity,
instance: Option<&Instance>,
params_results: FuncInOut,
) -> Result<(), Error> {
let trampoline = self.resolve_trampoline(func.trampoline()).clone();
trampoline.call(self, instance, params_results)?;
Ok(())
}
|
Calls the given [`HostFuncEntity`] with the `params` and `results` on `instance`.
# Errors
If the called host function returned an error.
|
call_host_func
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
pub(crate) fn can_create_more_instances(&mut self, additional: usize) -> bool {
let (inner, mut limiter) = self.store_inner_and_resource_limiter_ref();
if let Some(limiter) = limiter.as_resource_limiter() {
if inner.len_instances().saturating_add(additional) > limiter.instances() {
return false;
}
}
true
}
|
Returns `true` if it is possible to create `additional` more instances in the [`Store`].
|
can_create_more_instances
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
pub(crate) fn can_create_more_memories(&mut self, additional: usize) -> bool {
let (inner, mut limiter) = self.store_inner_and_resource_limiter_ref();
if let Some(limiter) = limiter.as_resource_limiter() {
if inner.len_memories().saturating_add(additional) > limiter.memories() {
return false;
}
}
true
}
|
Returns `true` if it is possible to create `additional` more linear memories in the [`Store`].
|
can_create_more_memories
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
pub(crate) fn can_create_more_tables(&mut self, additional: usize) -> bool {
let (inner, mut limiter) = self.store_inner_and_resource_limiter_ref();
if let Some(limiter) = limiter.as_resource_limiter() {
if inner.len_tables().saturating_add(additional) > limiter.tables() {
return false;
}
}
true
}
|
Returns `true` if it is possible to create `additional` more tables in the [`Store`].
|
can_create_more_tables
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
pub(super) fn alloc_trampoline(&mut self, func: TrampolineEntity<T>) -> Trampoline {
let idx = self.typed.trampolines.alloc(func);
Trampoline::from_inner(self.inner.wrap_stored(idx))
}
|
Allocates a new [`TrampolineEntity`] and returns a [`Trampoline`] reference to it.
|
alloc_trampoline
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
pub(super) fn resolve_memory_and_state_mut(
&mut self,
memory: &Memory,
) -> (&mut CoreMemory, &mut T) {
(self.inner.resolve_memory_mut(memory), &mut self.typed.data)
}
|
Returns an exclusive reference to the [`CoreMemory`] associated to the given [`Memory`]
and an exclusive reference to the user provided host state.
# Note
This method exists to properly handle use cases where
otherwise the Rust borrow-checker would not accept.
# Panics
- If the [`Memory`] does not originate from this [`Store`].
- If the [`Memory`] cannot be resolved to its entity.
|
resolve_memory_and_state_mut
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
fn resolve_trampoline(&self, func: &Trampoline) -> &TrampolineEntity<T> {
let entity_index = self.inner.unwrap_stored(func.as_inner());
self.typed
.trampolines
.get(entity_index)
.unwrap_or_else(|| panic!("failed to resolve stored host function: {entity_index:?}"))
}
|
Returns a shared reference to the associated entity of the host function trampoline.
# Panics
- If the [`Trampoline`] does not originate from this [`Store`].
- If the [`Trampoline`] cannot be resolved to its entity.
|
resolve_trampoline
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
pub fn call_hook(
&mut self,
hook: impl FnMut(&mut T, CallHook) -> Result<(), Error> + Send + Sync + 'static,
) {
self.typed.call_hook = Some(CallHookWrapper(Box::new(hook)));
}
|
Sets a callback function that is executed whenever a WebAssembly
function is called from the host or a host function is called from
WebAssembly, or these functions return.
The function is passed a `&mut T` to the underlying store, and a
[`CallHook`]. [`CallHook`] can be used to find out what kind of function
is being called or returned from.
The callback can either return `Ok(())` or an `Err` with an
[`Error`]. If an error is returned, it is returned to the host
caller. If there are nested calls, only the most recent host caller
receives the error and it is not propagated further automatically. The
hook may be invoked again as new functions are called and returned from.
|
call_hook
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
fn new(data: T) -> Self {
Self {
trampolines: Arena::new(),
data: Box::new(data),
limiter: None,
call_hook: None,
}
}
|
Creates a new [`TypedStoreInner`] from the given data of type `T`.
|
new
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/mod.rs
|
Apache-2.0
|
fn restore_or_panic<T>(&mut self) -> &mut Store<T> {
let Ok(store) = self.restore() else {
panic!(
"failed to convert `PrunedStore` back into `Store<{}>`",
type_name::<T>(),
);
};
store
}
|
Restores `self` to a proper [`Store<T>`] if possible.
# Panics
If the `T` of the resulting [`Store<T>`] does not match the given `T`.
|
restore_or_panic
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/store/pruned.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/store/pruned.rs
|
Apache-2.0
|
pub fn new(
mut ctx: impl AsContextMut,
elem: &module::ElementSegment,
get_func: impl Fn(u32) -> Func,
get_global: impl Fn(u32) -> Global,
) -> Self {
let get_func = |index| get_func(index).into();
let get_global = |index| get_global(index).get(&ctx);
let items: Box<[UntypedVal]> = match elem.kind() {
module::ElementSegmentKind::Passive | module::ElementSegmentKind::Active(_) => {
elem
.items()
.iter()
.map(|const_expr| {
const_expr.eval_with_context(get_global, get_func).unwrap_or_else(|| {
panic!("unexpected failed initialization of constant expression: {const_expr:?}")
})
}).collect()
}
module::ElementSegmentKind::Declared => Box::from([]),
};
let entity = CoreElementSegment::new(elem.ty(), items);
ctx.as_context_mut()
.store
.inner
.alloc_element_segment(entity)
}
|
Allocates a new [`ElementSegment`] on the store.
# Errors
If more than [`u32::MAX`] much linear memory is allocated.
|
new
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/table/element.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/table/element.rs
|
Apache-2.0
|
pub fn new(mut ctx: impl AsContextMut, ty: TableType, init: Val) -> Result<Self, Error> {
let (inner, mut resource_limiter) = ctx
.as_context_mut()
.store
.store_inner_and_resource_limiter_ref();
let entity = CoreTable::new(ty.core, init.into(), &mut resource_limiter)?;
let table = inner.alloc_table(entity);
Ok(table)
}
|
Creates a new table to the store.
# Errors
If `init` does not match the [`TableType`] element type.
|
new
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/table/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/table/mod.rs
|
Apache-2.0
|
pub(crate) fn dynamic_ty(&self, ctx: impl AsContext) -> TableType {
let core = ctx
.as_context()
.store
.inner
.resolve_table(self)
.dynamic_ty();
TableType { core }
}
|
Returns the dynamic [`TableType`] of the [`Table`].
# Note
This respects the current size of the [`Table`] as
its minimum size and is useful for import subtyping checks.
# Panics
Panics if `ctx` does not own this [`Table`].
|
dynamic_ty
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/table/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/table/mod.rs
|
Apache-2.0
|
pub fn get(&self, ctx: impl AsContext, index: u64) -> Option<Val> {
ctx.as_context()
.store
.inner
.resolve_table(self)
.get(index)
.map(Val::from)
}
|
Returns the [`Table`] element value at `index`.
Returns `None` if `index` is out of bounds.
# Panics
Panics if `ctx` does not own this [`Table`].
|
get
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/table/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/table/mod.rs
|
Apache-2.0
|
pub fn set(
&self,
mut ctx: impl AsContextMut,
index: u64,
value: Val,
) -> Result<(), TableError> {
ctx.as_context_mut()
.store
.inner
.resolve_table_mut(self)
.set(index, value.into())
}
|
Sets the [`Val`] of this [`Table`] at `index`.
# Errors
- If `index` is out of bounds.
- If `value` does not match the [`Table`] element type.
# Panics
Panics if `ctx` does not own this [`Table`].
|
set
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/table/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/table/mod.rs
|
Apache-2.0
|
pub fn copy(
mut store: impl AsContextMut,
dst_table: &Table,
dst_index: u64,
src_table: &Table,
src_index: u64,
len: u64,
) -> Result<(), TableError> {
if Self::eq(dst_table, src_table) {
// The `dst_table` and `src_table` are the same table
// therefore we have to copy within the same table.
let table = store
.as_context_mut()
.store
.inner
.resolve_table_mut(dst_table);
table
.copy_within(dst_index, src_index, len, None)
.map_err(|_| TableError::CopyOutOfBounds)
} else {
// The `dst_table` and `src_table` are different entities
// therefore we have to copy from one table to the other.
let (dst_table, src_table, _fuel) = store
.as_context_mut()
.store
.inner
.resolve_table_pair_and_fuel(dst_table, src_table);
CoreTable::copy(dst_table, dst_index, src_table, src_index, len, None)
.map_err(|_| TableError::CopyOutOfBounds)
}
}
|
Copy `len` elements from `src_table[src_index..]` into
`dst_table[dst_index..]`.
# Errors
Returns an error if the range is out of bounds of either the source or
destination tables.
# Panics
Panics if `store` does not own either `dst_table` or `src_table`.
|
copy
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/src/table/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/src/table/mod.rs
|
Apache-2.0
|
fn execute_wasm_fn_a(
mut store: &mut Store<CallHookTestState>,
linker: &mut Linker<CallHookTestState>,
) -> Result<(), Error> {
let wasm = r#"
(module
(import "env" "host_fn_a" (func $host_fn_a))
(import "env" "host_fn_b" (func $host_fn_b))
(func (export "wasm_fn_a")
(call $host_fn_a)
)
(func (export "wasm_fn_b")
(call $host_fn_b)
)
)
"#;
let module = Module::new(store.engine(), wasm).unwrap();
let instance = linker
.instantiate(&mut store, &module)
.unwrap()
.start(store.as_context_mut())
.unwrap();
let wasm_fn = instance
.get_export(store.as_context(), "wasm_fn_a")
.and_then(Extern::into_func)
.unwrap()
.typed::<(), ()>(&store)
.unwrap();
wasm_fn.call(store.as_context_mut(), ())
}
|
Prepares the test WAT and executes it. The wat defines two functions,
`wasm_fn_a` and `wasm_fn_b` and two imports, `host_fn_a` and `host_fn_b`.
`wasm_fn_a` calls `host_fn_a`, and `wasm_fn_b` calls `host_fn_b`.
None of the functions accept any arguments or return any value.
|
execute_wasm_fn_a
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/call_hook.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/call_hook.rs
|
Apache-2.0
|
fn test_setup() -> (Store<()>, Linker<()>) {
let mut config = Config::default();
config.consume_fuel(true);
config.compilation_mode(wasmi::CompilationMode::Eager);
let engine = Engine::new(&config);
let store = Store::new(&engine, ());
let linker = Linker::new(&engine);
(store, linker)
}
|
Setup [`Engine`] and [`Store`] for fuel metering.
|
test_setup
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/fuel_consumption.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/fuel_consumption.rs
|
Apache-2.0
|
fn default_test_setup(wasm: &[u8]) -> (Store<()>, Func) {
let (mut store, linker) = test_setup();
let module = create_module(&store, wasm);
let instance = linker
.instantiate(&mut store, &module)
.unwrap()
.start(&mut store)
.unwrap();
let func = instance.get_func(&store, "test").unwrap();
(store, func)
}
|
Setup [`Store`] and [`Instance`] for fuel metering.
|
default_test_setup
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/fuel_consumption.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/fuel_consumption.rs
|
Apache-2.0
|
fn assert_success(call_result: Result<i32, Error>) {
assert!(call_result.is_ok());
assert_eq!(call_result.unwrap(), -1);
}
|
Asserts that the call was successful.
# Note
We just check if the call succeeded, not if the results are correct.
That is to be determined by another kind of test.
|
assert_success
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/fuel_consumption.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/fuel_consumption.rs
|
Apache-2.0
|
fn test_module() -> &'static str {
r#"
(module
(memory 1 1)
(func (export "test") (result i32)
(memory.grow (i32.const 1))
)
)"#
}
|
The test module exporting a function as `"test"`.
# Note
The module's `memory` has one pages minimum and one page maximum
and thus cannot grow. Therefore the `memory.grow` operation in
the `test` function will fail and only consume a small amount of
fuel in lazy mode but will still consume a large amount in eager
mode.
|
test_module
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/fuel_consumption.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/fuel_consumption.rs
|
Apache-2.0
|
fn assert_out_of_fuel<T>(call_result: Result<T, Error>)
where
T: Debug,
{
assert!(matches!(
call_result.unwrap_err().as_trap_code(),
Some(TrapCode::OutOfFuel)
));
}
|
Asserts that the call trapped with [`TrapCode::OutOfFuel`].
|
assert_out_of_fuel
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/fuel_metering.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/fuel_metering.rs
|
Apache-2.0
|
fn ascending_tuple() -> I32x16 {
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
}
|
Returns a `(i32, ...)` tuple with 16 elements that have ascending values.
This is required as input or output of many of the following tests.
|
ascending_tuple
|
rust
|
wasmi-labs/wasmi
|
crates/wasmi/tests/integration/func.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wasmi/tests/integration/func.rs
|
Apache-2.0
|
pub fn new(config: RunnerConfig) -> Self {
let engine = Engine::new(&config.config);
let mut linker = Linker::new(&engine);
linker.allow_shadowing(true);
let mut store = Store::new(&engine, ());
_ = store.set_fuel(0);
WastRunner {
config,
linker,
store,
modules: HashMap::new(),
current: None,
params: Vec::new(),
results: Vec::new(),
}
}
|
Creates a new [`WastRunner`] with the given [`RunnerConfig`].
|
new
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
pub fn register_spectest(&mut self) -> Result<(), wasmi::Error> {
let Self { store, .. } = self;
let default_memory = Memory::new(&mut *store, MemoryType::new(1, Some(2)))?;
let default_table = Table::new(
&mut *store,
TableType::new(ValType::FuncRef, 10, Some(20)),
Val::default(ValType::FuncRef),
)?;
let table64 = Table::new(
&mut *store,
TableType::new64(ValType::FuncRef, 0, None),
Val::default(ValType::FuncRef),
)?;
let global_i32 = Global::new(&mut *store, Val::I32(666), Mutability::Const);
let global_i64 = Global::new(&mut *store, Val::I64(666), Mutability::Const);
let global_f32 = Global::new(
&mut *store,
Val::F32(F32::from_bits(0x4426_a666)),
Mutability::Const,
);
let global_f64 = Global::new(
&mut *store,
Val::F64(F64::from_bits(0x4084_d4cc_cccc_cccd)),
Mutability::Const,
);
self.linker.define("spectest", "memory", default_memory)?;
self.linker.define("spectest", "table", default_table)?;
self.linker.define("spectest", "table64", table64)?;
self.linker.define("spectest", "global_i32", global_i32)?;
self.linker.define("spectest", "global_i64", global_i64)?;
self.linker.define("spectest", "global_f32", global_f32)?;
self.linker.define("spectest", "global_f64", global_f64)?;
self.linker.func_wrap("spectest", "print", || {
println!("print");
})?;
self.linker
.func_wrap("spectest", "print_i32", |value: i32| {
println!("print: {value}");
})?;
self.linker
.func_wrap("spectest", "print_i64", |value: i64| {
println!("print: {value}");
})?;
self.linker
.func_wrap("spectest", "print_f32", |value: F32| {
println!("print: {value:?}");
})?;
self.linker
.func_wrap("spectest", "print_f64", |value: F64| {
println!("print: {value:?}");
})?;
self.linker
.func_wrap("spectest", "print_i32_f32", |v0: i32, v1: F32| {
println!("print: {v0:?} {v1:?}");
})?;
self.linker
.func_wrap("spectest", "print_f64_f64", |v0: F64, v1: F64| {
println!("print: {v0:?} {v1:?}");
})?;
Ok(())
}
|
Sets up the Wasm spec testsuite module for `self`.
|
register_spectest
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn value(&mut self, value: &WastArgCore) -> Option<Val> {
use wasmi::{ExternRef, FuncRef};
use wast::core::{AbstractHeapType, HeapType};
Some(match value {
WastArgCore::I32(arg) => Val::I32(*arg),
WastArgCore::I64(arg) => Val::I64(*arg),
WastArgCore::F32(arg) => Val::F32(F32::from_bits(arg.bits)),
WastArgCore::F64(arg) => Val::F64(F64::from_bits(arg.bits)),
WastArgCore::V128(arg) => {
let v128: V128 = u128::from_le_bytes(arg.to_le_bytes()).into();
Val::V128(v128)
}
WastArgCore::RefNull(HeapType::Abstract {
ty: AbstractHeapType::Func,
..
}) => Val::FuncRef(FuncRef::null()),
WastArgCore::RefNull(HeapType::Abstract {
ty: AbstractHeapType::Extern,
..
}) => Val::ExternRef(ExternRef::null()),
WastArgCore::RefExtern(value) => {
Val::ExternRef(ExternRef::new(&mut self.store, *value))
}
_ => return None,
})
}
|
Converts the [`WastArgCore`][`wast::core::WastArgCore`] into a [`wasmi::Val`] if possible.
|
value
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
pub fn process_directives(&mut self, filename: &str, wast: &str) -> Result<()> {
let enhance_error = |mut err: wast::Error| {
err.set_path(filename.as_ref());
err.set_text(wast);
err
};
let mut lexer = Lexer::new(wast);
lexer.allow_confusing_unicode(true);
let buffer = ParseBuffer::new_with_lexer(lexer).map_err(enhance_error)?;
let directives = wast::parser::parse::<wast::Wast>(&buffer)
.map_err(enhance_error)?
.directives;
for directive in directives {
let span = directive.span();
self.process_directive(directive)
.map_err(|err| match err.downcast::<wast::Error>() {
Ok(err) => enhance_error(err).into(),
Err(err) => err,
})
.with_context(|| {
let (line, col) = span.linecol_in(wast);
format!("failed directive on {}:{}:{}", filename, line + 1, col)
})?;
}
Ok(())
}
|
Processes the directives of the given `wast` source by `self`.
|
process_directives
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn process_directive(&mut self, directive: WastDirective) -> Result<()> {
match directive {
#[rustfmt::skip]
WastDirective::Module(
| module @ QuoteWat::Wat(wast::Wat::Module(_))
| module @ QuoteWat::QuoteModule { .. },
) => {
let (name, module) = self.module_definition(module)?;
self.module(name, &module)?;
}
#[rustfmt::skip]
WastDirective::ModuleDefinition(
| module @ QuoteWat::Wat(wast::Wat::Module(_))
| module @ QuoteWat::QuoteModule { .. },
) => {
let (name, module) = self.module_definition(module)?;
if let Some(name) = name {
self.modules.insert(name.into(), module);
}
}
WastDirective::ModuleInstance {
span: _,
instance,
module,
} => {
let Some(module) = module.and_then(|n| self.modules.get(n.name())).cloned() else {
bail!("missing module named {module:?}")
};
self.module(instance.map(|n| n.name()), &module)?;
}
WastDirective::Register { name, module, .. } => {
self.register(name, module)?;
}
WastDirective::Invoke(wast_invoke) => {
self.invoke(wast_invoke)?;
}
#[rustfmt::skip]
WastDirective::AssertInvalid {
module:
| module @ QuoteWat::Wat(wast::Wat::Module(_))
| module @ QuoteWat::QuoteModule { .. },
message,
..
} => {
if self.module_definition(module).is_ok() {
bail!("module succeeded to compile and validate but should have failed with: {message}");
}
},
WastDirective::AssertMalformed {
module: module @ QuoteWat::Wat(wast::Wat::Module(_)),
message,
span: _,
} => {
if self.module_definition(module).is_ok() {
bail!("module succeeded to compile and validate but should have failed with: {message}");
}
}
WastDirective::AssertMalformed {
module: QuoteWat::QuoteModule { .. },
..
} => {}
WastDirective::AssertUnlinkable {
module: module @ Wat::Module(_),
message,
..
} => {
let (name, module) = self.module_definition(QuoteWat::Wat(module))?;
if self.module(name, &module).is_ok() {
bail!("module succeeded to link but should have failed with: {message}")
}
}
WastDirective::AssertTrap { exec, message, .. } => {
match self.execute_wast_execute(exec) {
Ok(_) => {
bail!(
"expected to trap with message '{message}' but succeeded with: {:?}",
&self.results[..],
)
}
Err(error) => {
self.assert_trap(error, message)?;
}
}
}
WastDirective::AssertReturn {
exec,
results: expected,
..
} => {
self.execute_wast_execute(exec)?;
self.assert_results(&expected)?;
}
WastDirective::AssertExhaustion { call, message, .. } => match self.invoke(call) {
Ok(_) => {
bail!(
"expected to fail due to resource exhaustion '{message}' but succeeded with: {:?}",
&self.results[..],
)
}
Err(error) => {
self.assert_trap(error, message)?;
}
},
unsupported => bail!("encountered unsupported Wast directive: {unsupported:?}"),
};
Ok(())
}
|
Processes the given `.wast` directive by `self`.
|
process_directive
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn module(&mut self, name: Option<&str>, module: &Module) -> Result<()> {
let instance = match self.instantiate_module(module) {
Ok(instance) => instance,
Err(error) => bail!("failed to instantiate module: {error}"),
};
if let Some(name) = name {
self.linker.instance(&mut self.store, name, instance)?;
}
self.current = Some(instance);
Ok(())
}
|
Instantiates `module` and makes its exports available under `name` if any.
Also sets the `current` instance to the `module` instance.
|
module
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn register(&mut self, as_name: &str, name: Option<Id>) -> Result<()> {
match name {
Some(name) => {
let name = name.name();
self.linker.alias_module(name, as_name)?;
}
None => {
let Some(current) = self.current else {
bail!("no previous instance")
};
self.linker.instance(&mut self.store, as_name, current)?;
}
}
Ok(())
}
|
Registers the given [`Instance`] with the given `name` and sets it as the last instance.
|
register
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn assert_results(&self, expected: &[WastRet]) -> Result<()> {
anyhow::ensure!(
self.results.len() == expected.len(),
"number of returned values and expected values do not match: #expected = {}, #returned = {}",
expected.len(),
self.results.len(),
);
for (result, expected) in self.results.iter().zip(expected) {
self.assert_result(result, expected)?;
}
Ok(())
}
|
Asserts that `results` match the `expected` values.
|
assert_results
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn assert_result(&self, result: &Val, expected: &WastRet) -> Result<()> {
let WastRet::Core(expected) = expected else {
bail!("encountered unsupported Wast result: {expected:?}")
};
self.assert_result_core(result, expected)
}
|
Asserts that `result` match the `expected` value.
|
assert_result
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn instantiate_module(&mut self, module: &wasmi::Module) -> Result<Instance> {
let previous_fuel = self.store.get_fuel().ok();
_ = self.store.set_fuel(1_000);
let instance_pre = self.linker.instantiate(&mut self.store, module)?;
let instance = instance_pre.start(&mut self.store)?;
if let Some(fuel) = previous_fuel {
_ = self.store.set_fuel(fuel);
}
Ok(instance)
}
|
Instantiates and starts the `module` while preserving fuel.
|
instantiate_module
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn get_export(&self, module_name: Option<Id>, name: &str) -> Result<Extern> {
let export = match module_name {
Some(module_name) => self.linker.get(&self.store, module_name.name(), name),
None => {
let Some(current) = self.current else {
bail!("missing previous instance to get export at: {module_name:?}::{name}")
};
current.get_export(&self.store, name)
}
};
match export {
Some(export) => Ok(export),
None => bail!("missing export at {module_name:?}::{name}"),
}
}
|
Queries the export named `name` for the instance named `module_name`.
# Errors
- If there is no instance to query exports from.
- If there is no such export available.
|
get_export
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn get_global(&self, module_name: Option<Id>, global_name: &str) -> Result<Val> {
let export = self.get_export(module_name, global_name)?;
let Some(global) = export.into_global() else {
bail!("missing global export at {module_name:?}::{global_name}")
};
let value = global.get(&self.store);
Ok(value)
}
|
Returns the current value of the [`Global`] identifier by the given `module_name` and `global_name`.
# Errors
- If no module instances can be found.
- If no global variable identifier with `global_name` can be found.
|
get_global
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn assert_trap(&self, error: anyhow::Error, message: &str) -> Result<()> {
let Some(error) = error.downcast_ref::<wasmi::Error>() else {
bail!(
"encountered unexpected error: \n\t\
found: '{error}'\n\t\
expected: trap with message '{message}'",
)
};
if !error.to_string().contains(message) {
bail!(
"the directive trapped as expected but with an unexpected message\n\
expected: {message},\n\
encountered: {error}",
)
}
Ok(())
}
|
Asserts that the `error` is a trap with the expected `message`.
# Panics
- If the `error` is not a trap.
- If the trap message of the `error` is not as expected.
|
assert_trap
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn invoke(&mut self, invoke: wast::WastInvoke) -> Result<()> {
let export = self.get_export(invoke.module, invoke.name)?;
let Some(func) = export.into_func() else {
bail!(
"missing function export at {:?}::{}",
invoke.module,
invoke.name
)
};
self.fill_params(&invoke.args)?;
self.prepare_results(&func);
self.call_func(&func)?;
Ok(())
}
|
Invokes the [`Func`] identified by `func_name` in [`Instance`] identified by `module_name`.
If no [`Instance`] under `module_name` is found then invoke [`Func`] on the last instantiated [`Instance`].
# Note
Returns the results of the function invocation.
# Errors
- If no module instances can be found.
- If no function identified with `func_name` can be found.
- If function invocation returned an error.
[`Func`]: wasmi::Func
|
invoke
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn fill_params(&mut self, args: &[WastArg]) -> Result<()> {
self.params.clear();
for arg in args {
#[allow(unreachable_patterns)] // TODO: remove once `wast v220` is used
let arg = match arg {
WastArg::Core(arg) => arg,
_ => {
bail!("encountered unsupported Wast argument: {arg:?}")
}
};
let Some(val) = self.value(arg) else {
bail!("encountered unsupported WastArgCore argument: {arg:?}")
};
self.params.push(val);
}
Ok(())
}
|
Fills the `params` buffer with `args`.
|
fill_params
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn prepare_results(&mut self, func: &wasmi::Func) {
let len_results = func.ty(&self.store).results().len();
self.results.clear();
self.results.resize(len_results, Val::I32(0));
}
|
Prepares the results buffer for a call to `func`.
|
prepare_results
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn f32_matches(actual: &F32, expected: &NanPattern<wast::token::F32>) -> bool {
match expected {
NanPattern::CanonicalNan | NanPattern::ArithmeticNan => actual.to_float().is_nan(),
NanPattern::Value(expected) => actual.to_bits() == expected.bits,
}
}
|
Returns `true` if `actual` matches `expected`.
|
f32_matches
|
rust
|
wasmi-labs/wasmi
|
crates/wast/src/lib.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/src/lib.rs
|
Apache-2.0
|
fn process_wast(path: &'static str, wast: &'static str, config: RunnerConfig) {
let mut runner = WastRunner::new(config);
if let Err(error) = runner.register_spectest() {
panic!("{path}: failed to setup Wasm spectest module: {error}");
}
if let Err(error) = runner.process_directives(path, wast) {
panic!("{error:#}")
}
}
|
Runs the Wasm test spec identified by the given name.
|
process_wast
|
rust
|
wasmi-labs/wasmi
|
crates/wast/tests/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/tests/mod.rs
|
Apache-2.0
|
fn mvp_config() -> Config {
let mut config = Config::default();
config
.wasm_mutable_global(false)
.wasm_saturating_float_to_int(false)
.wasm_sign_extension(false)
.wasm_multi_value(false)
.wasm_multi_memory(false)
.wasm_simd(false)
.wasm_memory64(false);
config
}
|
Create a [`Config`] for the Wasm MVP feature set.
|
mvp_config
|
rust
|
wasmi-labs/wasmi
|
crates/wast/tests/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/tests/mod.rs
|
Apache-2.0
|
fn test_config(consume_fuel: bool, parsing_mode: ParsingMode) -> RunnerConfig {
let mut config = mvp_config();
// We have to enable the `mutable-global` Wasm proposal because
// it seems that the entire Wasm spec test suite is already built
// on the basis of its semantics.
config
.wasm_mutable_global(true)
.wasm_saturating_float_to_int(true)
.wasm_sign_extension(true)
.wasm_multi_value(true)
.wasm_multi_memory(false)
.wasm_bulk_memory(true)
.wasm_reference_types(true)
.wasm_tail_call(true)
.wasm_extended_const(true)
.wasm_wide_arithmetic(true)
.wasm_simd(true)
.consume_fuel(consume_fuel)
.compilation_mode(CompilationMode::Eager);
RunnerConfig {
config,
parsing_mode,
}
}
|
Create a [`Config`] with all Wasm feature supported by Wasmi enabled.
# Note
The Wasm MVP has no Wasm proposals enabled.
|
test_config
|
rust
|
wasmi-labs/wasmi
|
crates/wast/tests/mod.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/crates/wast/tests/mod.rs
|
Apache-2.0
|
pub fn setup(input: FuzzInput<'a>) -> Option<Self> {
let wasm = input.module.wasm().into_bytes();
let wasmi_oracle = WasmiOracle::setup(&wasm[..])?;
let chosen_oracle = input.chosen_oracle.setup(&wasm[..])?;
Some(Self {
wasm,
wasmi_oracle,
chosen_oracle,
u: input.u,
})
}
|
Sets up the oracles for the differential fuzzing if possible.
|
setup
|
rust
|
wasmi-labs/wasmi
|
fuzz/fuzz_targets/differential.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/fuzz/fuzz_targets/differential.rs
|
Apache-2.0
|
fn init_params(&mut self, dst: &mut Vec<FuzzVal>, src: &[ValType]) {
dst.clear();
dst.extend(
src.iter()
.copied()
.map(FuzzValType::from)
.map(|ty| FuzzVal::with_type(ty, &mut self.u)),
);
}
|
Fill [`FuzzVal`]s of type `src` into `dst` using `u` for initialization.
Clears `dst` before the operation.
|
init_params
|
rust
|
wasmi-labs/wasmi
|
fuzz/fuzz_targets/differential.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/fuzz/fuzz_targets/differential.rs
|
Apache-2.0
|
fn assert_results_match(
&self,
func_name: &str,
params: &[FuzzVal],
wasmi_results: &[FuzzVal],
oracle_results: &[FuzzVal],
) {
if wasmi_results == oracle_results {
return;
}
let wasmi_name = self.wasmi_oracle.name();
let oracle_name = self.chosen_oracle.name();
let crash_input = self.generate_crash_inputs();
panic!(
"\
function call returned different values:\n\
\tfunc: {func_name}\n\
\tparams: {params:?}\n\
\t{wasmi_name}: {wasmi_results:?}\n\
\t{oracle_name}: {oracle_results:?}\n\
\tcrash-report: 0x{crash_input}\n\
"
)
}
|
Asserts that the call results is equal for both oracles.
|
assert_results_match
|
rust
|
wasmi-labs/wasmi
|
fuzz/fuzz_targets/differential.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/fuzz/fuzz_targets/differential.rs
|
Apache-2.0
|
fn assert_globals_match(&mut self, exports: &ModuleExports) {
for name in exports.globals() {
let wasmi_val = self.wasmi_oracle.get_global(name);
let oracle_val = self.chosen_oracle.get_global(name);
if wasmi_val == oracle_val {
continue;
}
let wasmi_name = self.wasmi_oracle.name();
let oracle_name = self.chosen_oracle.name();
let crash_input = self.generate_crash_inputs();
panic!(
"\
encountered unequal globals:\n\
\tglobal: {name}\n\
\t{wasmi_name}: {wasmi_val:?}\n\
\t{oracle_name}: {oracle_val:?}\n\
\tcrash-report: 0x{crash_input}\n\
"
)
}
}
|
Asserts that the global variable state is equal in both oracles.
|
assert_globals_match
|
rust
|
wasmi-labs/wasmi
|
fuzz/fuzz_targets/differential.rs
|
https://github.com/wasmi-labs/wasmi/blob/master/fuzz/fuzz_targets/differential.rs
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.