Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 52eda3e

Browse files
feat: uninitialized elems
Signed-off-by: Henry Gressmann <[email protected]>
1 parent 3e71f86 commit 52eda3e

File tree

7 files changed

+71
-68
lines changed

7 files changed

+71
-68
lines changed

crates/parser/src/conversion.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
use alloc::{boxed::Box, format, string::ToString, vec::Vec};
22
use log::debug;
3-
use tinywasm_types::{
4-
BlockArgs, ConstInstruction, ElementItem, Export, ExternalKind, FuncType, Global, GlobalType, Import, ImportKind,
5-
Instruction, MemArg, MemoryArch, MemoryType, TableType, ValType,
6-
};
3+
use tinywasm_types::*;
74
use wasmparser::{FuncValidator, OperatorsReader, ValidatorResources};
85

96
use crate::{module::CodeSection, Result};
@@ -210,8 +207,8 @@ pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> ValType {
210207
}
211208
}
212209

213-
pub(crate) fn convert_memarg(memarg: wasmparser::MemArg) -> MemArg {
214-
MemArg { offset: memarg.offset, align: memarg.align, align_max: memarg.max_align, mem_addr: memarg.memory }
210+
pub(crate) fn convert_memarg(memarg: wasmparser::MemArg) -> MemoryArg {
211+
MemoryArg { offset: memarg.offset, align: memarg.align, align_max: memarg.max_align, mem_addr: memarg.memory }
215212
}
216213

217214
pub(crate) fn process_const_operators(ops: OperatorsReader) -> Result<ConstInstruction> {

crates/tinywasm/src/imports.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -215,13 +215,13 @@ pub(crate) enum ResolvedExtern<S, V> {
215215
pub(crate) struct ResolvedImports {
216216
pub(crate) globals: Vec<GlobalAddr>,
217217
pub(crate) tables: Vec<TableAddr>,
218-
pub(crate) mems: Vec<MemAddr>,
218+
pub(crate) memories: Vec<MemAddr>,
219219
pub(crate) funcs: Vec<FuncAddr>,
220220
}
221221

222222
impl ResolvedImports {
223223
pub(crate) fn new() -> Self {
224-
Self { globals: Vec::new(), tables: Vec::new(), mems: Vec::new(), funcs: Vec::new() }
224+
Self { globals: Vec::new(), tables: Vec::new(), memories: Vec::new(), funcs: Vec::new() }
225225
}
226226
}
227227

@@ -318,7 +318,7 @@ impl Imports {
318318
match &kind {
319319
ExternalKind::Global => imports.globals.push(addr),
320320
ExternalKind::Table => imports.tables.push(addr),
321-
ExternalKind::Memory => imports.mems.push(addr),
321+
ExternalKind::Memory => imports.memories.push(addr),
322322
ExternalKind::Func => imports.funcs.push(addr),
323323
}
324324
}
@@ -338,7 +338,7 @@ impl Imports {
338338
match val {
339339
ExternVal::Global(g) => imports.globals.push(g),
340340
ExternVal::Table(t) => imports.tables.push(t),
341-
ExternVal::Mem(m) => imports.mems.push(m),
341+
ExternVal::Mem(m) => imports.memories.push(m),
342342
ExternVal::Func(f) => imports.funcs.push(f),
343343
}
344344
}

crates/tinywasm/src/instance.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,10 @@ impl ModuleInstance {
6666
addrs.globals.extend(store.init_globals(data.globals.into(), idx)?);
6767
addrs.funcs.extend(store.init_funcs(data.funcs.into(), idx)?);
6868
addrs.tables.extend(store.init_tables(data.table_types.into(), idx)?);
69-
addrs.mems.extend(store.init_mems(data.memory_types.into(), idx)?);
69+
addrs.memories.extend(store.init_memories(data.memory_types.into(), idx)?);
7070

71-
let elem_addrs = store.init_elems(&addrs.tables, data.elements.into(), idx)?;
72-
let data_addrs = store.init_datas(&addrs.mems, data.data.into(), idx)?;
71+
let elem_addrs = store.init_elements(&addrs.tables, data.elements.into(), idx)?;
72+
let data_addrs = store.init_datas(&addrs.memories, data.data.into(), idx)?;
7373

7474
let instance = ModuleInstanceInner {
7575
store_id: store.id(),
@@ -78,7 +78,7 @@ impl ModuleInstance {
7878
types: data.func_types,
7979
func_addrs: addrs.funcs.into_boxed_slice(),
8080
table_addrs: addrs.tables.into_boxed_slice(),
81-
mem_addrs: addrs.mems.into_boxed_slice(),
81+
mem_addrs: addrs.memories.into_boxed_slice(),
8282
global_addrs: addrs.globals.into_boxed_slice(),
8383
elem_addrs,
8484
data_addrs: data_addrs,

crates/tinywasm/src/store.rs

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,9 @@ impl Default for Store {
8686
pub(crate) struct StoreData {
8787
pub(crate) funcs: Vec<Rc<FunctionInstance>>,
8888
pub(crate) tables: Vec<Rc<RefCell<TableInstance>>>,
89-
pub(crate) mems: Vec<Rc<RefCell<MemoryInstance>>>,
89+
pub(crate) memories: Vec<Rc<RefCell<MemoryInstance>>>,
9090
pub(crate) globals: Vec<Rc<RefCell<GlobalInstance>>>,
91-
pub(crate) elems: Vec<ElemInstance>,
91+
pub(crate) elements: Vec<ElementInstance>,
9292
pub(crate) datas: Vec<DataInstance>,
9393
}
9494

@@ -142,15 +142,15 @@ impl Store {
142142
}
143143

144144
/// Add memories to the store, returning their addresses in the store
145-
pub(crate) fn init_mems(&mut self, mems: Vec<MemoryType>, idx: ModuleInstanceAddr) -> Result<Vec<MemAddr>> {
146-
let mem_count = self.data.mems.len();
145+
pub(crate) fn init_memories(&mut self, memories: Vec<MemoryType>, idx: ModuleInstanceAddr) -> Result<Vec<MemAddr>> {
146+
let mem_count = self.data.memories.len();
147147
let mut mem_addrs = Vec::with_capacity(mem_count);
148-
for (i, mem) in mems.into_iter().enumerate() {
148+
for (i, mem) in memories.into_iter().enumerate() {
149149
if let MemoryArch::I64 = mem.arch {
150150
return Err(Error::UnsupportedFeature("64-bit memories".to_string()));
151151
}
152152
log::info!("adding memory: {:?}", mem);
153-
self.data.mems.push(Rc::new(RefCell::new(MemoryInstance::new(mem, idx))));
153+
self.data.memories.push(Rc::new(RefCell::new(MemoryInstance::new(mem, idx))));
154154

155155
mem_addrs.push((i + mem_count) as MemAddr);
156156
}
@@ -175,16 +175,16 @@ impl Store {
175175

176176
/// Add elements to the store, returning their addresses in the store
177177
/// Should be called after the tables have been added
178-
pub(crate) fn init_elems(
178+
pub(crate) fn init_elements(
179179
&mut self,
180180
table_addrs: &[TableAddr],
181-
elems: Vec<Element>,
181+
elements: Vec<Element>,
182182
idx: ModuleInstanceAddr,
183183
) -> Result<Box<[Addr]>> {
184-
let elem_count = self.data.elems.len();
184+
let elem_count = self.data.elements.len();
185185
let mut elem_addrs = Vec::with_capacity(elem_count);
186-
for (i, elem) in elems.into_iter().enumerate() {
187-
let init = elem
186+
for (i, element) in elements.into_iter().enumerate() {
187+
let init = element
188188
.items
189189
.iter()
190190
.map(|item| {
@@ -194,7 +194,7 @@ impl Store {
194194
})
195195
.collect::<Result<Vec<_>>>()?;
196196

197-
let items = match elem.kind {
197+
let items = match element.kind {
198198
// doesn't need to be initialized, can be initialized lazily using the `table.init` instruction
199199
ElementKind::Passive => Some(init),
200200

@@ -228,7 +228,7 @@ impl Store {
228228
}
229229
};
230230

231-
self.data.elems.push(ElemInstance::new(elem.kind, idx, items));
231+
self.data.elements.push(ElementInstance::new(element.kind, idx, items));
232232
elem_addrs.push((i + elem_count) as Addr);
233233
}
234234

@@ -262,7 +262,7 @@ impl Store {
262262
let offset = self.eval_i32_const(&offset)?;
263263

264264
let mem =
265-
self.data.mems.get_mut(mem_addr as usize).ok_or_else(|| {
265+
self.data.memories.get_mut(mem_addr as usize).ok_or_else(|| {
266266
Error::Other(format!("memory {} not found for data segment {}", mem_addr, i))
267267
})?;
268268

@@ -296,8 +296,8 @@ impl Store {
296296
if let MemoryArch::I64 = mem.arch {
297297
return Err(Error::UnsupportedFeature("64-bit memories".to_string()));
298298
}
299-
self.data.mems.push(Rc::new(RefCell::new(MemoryInstance::new(mem, idx))));
300-
Ok(self.data.mems.len() as MemAddr - 1)
299+
self.data.memories.push(Rc::new(RefCell::new(MemoryInstance::new(mem, idx))));
300+
Ok(self.data.memories.len() as MemAddr - 1)
301301
}
302302

303303
pub(crate) fn add_func(&mut self, func: Function, type_idx: TypeAddr, idx: ModuleInstanceAddr) -> Result<FuncAddr> {
@@ -348,7 +348,7 @@ impl Store {
348348

349349
/// Get the memory at the actual index in the store
350350
pub(crate) fn get_mem(&self, addr: usize) -> Result<&Rc<RefCell<MemoryInstance>>> {
351-
self.data.mems.get(addr).ok_or_else(|| Error::Other(format!("memory {} not found", addr)))
351+
self.data.memories.get(addr).ok_or_else(|| Error::Other(format!("memory {} not found", addr)))
352352
}
353353

354354
/// Get the table at the actual index in the store
@@ -357,8 +357,8 @@ impl Store {
357357
}
358358

359359
/// Get the element at the actual index in the store
360-
pub(crate) fn get_elem(&self, addr: usize) -> Result<&ElemInstance> {
361-
self.data.elems.get(addr).ok_or_else(|| Error::Other(format!("element {} not found", addr)))
360+
pub(crate) fn get_elem(&self, addr: usize) -> Result<&ElementInstance> {
361+
self.data.elements.get(addr).ok_or_else(|| Error::Other(format!("element {} not found", addr)))
362362
}
363363

364364
/// Get the global at the actual index in the store
@@ -413,25 +413,29 @@ impl FunctionInstance {
413413
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#table-instances>
414414
#[derive(Debug)]
415415
pub(crate) struct TableInstance {
416-
pub(crate) elements: Vec<Addr>,
416+
pub(crate) elements: Vec<Option<Addr>>,
417417
pub(crate) _kind: TableType,
418418
pub(crate) _owner: ModuleInstanceAddr, // index into store.module_instances
419419
}
420420

421421
impl TableInstance {
422422
pub(crate) fn new(kind: TableType, owner: ModuleInstanceAddr) -> Self {
423-
Self { elements: vec![0; kind.size_initial as usize], _kind: kind, _owner: owner }
423+
Self { elements: vec![None; kind.size_initial as usize], _kind: kind, _owner: owner }
424424
}
425425

426426
pub(crate) fn get(&self, addr: usize) -> Result<Addr> {
427-
self.elements.get(addr).copied().ok_or_else(|| Trap::UndefinedElement { index: addr }.into())
427+
self.elements
428+
.get(addr)
429+
.copied()
430+
.ok_or_else(|| Error::Trap(Trap::UndefinedElement { index: addr }))
431+
.map(|elem| elem.ok_or_else(|| Trap::UninitializedElement { index: addr }.into()))?
428432
}
429433

430434
pub(crate) fn set(&mut self, addr: usize, value: Addr) -> Result<()> {
431435
if addr >= self.elements.len() {
432436
return Err(Error::Other(format!("table element {} not found", addr)));
433437
}
434-
self.elements[addr] = value;
438+
self.elements[addr] = Some(value);
435439
Ok(())
436440
}
437441

@@ -440,6 +444,8 @@ impl TableInstance {
440444
}
441445

442446
pub(crate) fn init(&mut self, offset: i32, init: &[Addr]) -> Result<()> {
447+
let init = init.iter().map(|item| Some(*item)).collect::<Vec<_>>();
448+
443449
let offset = offset as usize;
444450
let end = offset.checked_add(init.len()).ok_or_else(|| {
445451
Error::Trap(crate::Trap::TableOutOfBounds { offset, len: init.len(), max: self.elements.len() })
@@ -449,7 +455,7 @@ impl TableInstance {
449455
return Err(crate::Trap::TableOutOfBounds { offset, len: init.len(), max: self.elements.len() }.into());
450456
}
451457

452-
self.elements[offset..end].copy_from_slice(init);
458+
self.elements[offset..end].copy_from_slice(&init);
453459
Ok(())
454460
}
455461
}
@@ -573,13 +579,13 @@ impl GlobalInstance {
573579
///
574580
/// See <https://webassembly.github.io/spec/core/exec/runtime.html#element-instances>
575581
#[derive(Debug)]
576-
pub(crate) struct ElemInstance {
582+
pub(crate) struct ElementInstance {
577583
pub(crate) kind: ElementKind,
578584
pub(crate) items: Option<Vec<u32>>, // none is the element was dropped
579585
_owner: ModuleInstanceAddr, // index into store.module_instances
580586
}
581587

582-
impl ElemInstance {
588+
impl ElementInstance {
583589
pub(crate) fn new(kind: ElementKind, owner: ModuleInstanceAddr, items: Option<Vec<u32>>) -> Self {
584590
Self { kind, _owner: owner, items }
585591
}

0 commit comments

Comments
 (0)