Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return generalized side table from validation #720

Merged
merged 8 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions crates/interpreter/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub struct Module<'m> {
types: Vec<FuncType<'m>>,
// TODO(dev/fast-interp): Flatten it to 1D array when making it persistent in
// flash.
side_tables: &'m [Vec<BranchTableEntry>],
side_table: &'m [SideTableEntry],
}

impl<'m> Import<'m> {
Expand All @@ -56,7 +56,7 @@ impl<'m> Module<'m> {
let side_tables = validate(binary)?;
zhouwfang marked this conversation as resolved.
Show resolved Hide resolved
let mut module = unsafe { Self::new_unchecked(binary) };
// TODO(dev/fast-interp): We should take a buffer as argument to write to.
module.side_tables = Box::leak(Box::new(side_tables));
module.side_table = Box::leak(Box::new(side_tables));
Ok(module)
}

Expand Down Expand Up @@ -191,7 +191,7 @@ impl<'m> Module<'m> {
let size = parser.parse_u32().into_ok() as usize;
let parser = parser.split_at(size).into_ok();
if i == x as usize {
return (parser, &self.side_tables[i]);
return (parser, &self.side_table[i].metadata_entry.branch_table);
}
}
unreachable!()
Expand Down
17 changes: 17 additions & 0 deletions crates/interpreter/src/side_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use alloc::vec::Vec;
use core::ops::Range;

use crate::error::*;
use crate::module::Parser;

Expand Down Expand Up @@ -98,3 +101,17 @@ impl BranchTableEntry {
BranchTableEntry([0; 3])
}
}

#[derive(Default, Debug)]
pub struct SideTableEntry {
#[allow(dead_code)]
pub type_idx: usize,
pub metadata_entry: MetadataEntry,
}

#[derive(Default, Debug)]
pub struct MetadataEntry {
#[allow(dead_code)]
pub parser_range: Range<usize>,
pub branch_table: Vec<BranchTableEntry>,
}
65 changes: 36 additions & 29 deletions crates/interpreter/src/valid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use alloc::collections::BTreeSet;
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::ops::Range;

use crate::error::*;
use crate::side_table::*;
Expand All @@ -25,7 +26,7 @@ use crate::util::*;
use crate::*;

/// Checks whether a WASM module in binary format is valid.
pub fn validate(binary: &[u8]) -> Result<Vec<Vec<BranchTableEntry>>, Error> {
pub fn validate(binary: &[u8]) -> Result<Vec<SideTableEntry>, Error> {
Context::default().check_module(&mut Parser::new(binary))
}

Expand All @@ -44,9 +45,7 @@ struct Context<'m> {
}

impl<'m> Context<'m> {
fn check_module(
&mut self, parser: &mut Parser<'m>,
) -> MResult<Vec<Vec<BranchTableEntry>>, Check> {
fn check_module(&mut self, parser: &mut Parser<'m>) -> MResult<Vec<SideTableEntry>, Check> {
check(parser.parse_bytes(8)? == b"\0asm\x01\0\0\0")?;
if let Some(mut parser) = self.check_section(parser, SectionId::Type)? {
let n = parser.parse_vec()?;
Expand Down Expand Up @@ -129,13 +128,23 @@ impl<'m> Context<'m> {
let mut side_tables = vec![];
if let Some(mut parser) = self.check_section(parser, SectionId::Code)? {
check(self.funcs.len() == imported_funcs + parser.parse_vec()?)?;
let mut offset = 0;
for x in imported_funcs .. self.funcs.len() {
let size = parser.parse_u32()? as usize;
offset += size_of::<u32>();
zhouwfang marked this conversation as resolved.
Show resolved Hide resolved
let mut parser = parser.split_at(size)?;
let t = self.functype(x as FuncIdx).unwrap();
let t = self.functype(x as FuncIdx)?;
zhouwfang marked this conversation as resolved.
Show resolved Hide resolved
let mut locals = t.params.to_vec();
parser.parse_locals(&mut locals)?;
side_tables.push(Expr::check_body(self, &mut parser, &refs, locals, t.results)?);
let branch_table = Expr::check_body(self, &mut parser, &refs, locals, t.results)?;
side_tables.push(SideTableEntry {
type_idx: self.funcs[x] as usize,
metadata_entry: MetadataEntry {
parser_range: Range { start: offset, end: offset + size },
branch_table,
},
});
offset += size;
check(parser.is_empty())?;
}
check(parser.is_empty())?;
Expand Down Expand Up @@ -409,34 +418,32 @@ struct Expr<'a, 'm> {
is_body: bool,
locals: Vec<ValType>,
labels: Vec<Label<'m>>,
side_table: SideTable,
branch_table: BranchTable,
}

#[derive(Default)]
struct SideTable {
entries: Vec<BranchTableEntry>,
}
struct BranchTable(Vec<BranchTableEntry>);

impl SideTable {
impl BranchTable {
fn save(&self) -> usize {
self.entries.len()
self.0.len()
}

fn branch(&mut self) {
self.entries.push(BranchTableEntry::invalid());
self.0.push(BranchTableEntry::invalid());
}

fn stitch(&mut self, source: SideTableBranch, target: SideTableBranch) -> CheckResult {
let delta_ip = Self::delta(source, target, |x| x.parser.as_ptr() as isize)?;
let delta_stp = Self::delta(source, target, |x| x.side_table as isize)?;
let delta_stp = Self::delta(source, target, |x| x.branch_table as isize)?;
let val_cnt = u32::try_from(target.result).map_err(|_| {
#[cfg(feature = "debug")]
eprintln!("side-table val_cnt overflow {0}", target.result);
unsupported(if_debug!(Unsupported::SideTable))
})?;
let pop_cnt = Self::pop_cnt(source, target)?;
debug_assert!(self.entries[source.side_table].is_invalid());
self.entries[source.side_table] =
debug_assert!(self.0[source.branch_table].is_invalid());
self.0[source.branch_table] =
BranchTableEntry::new(BranchTableEntryView { delta_ip, delta_stp, val_cnt, pop_cnt })?;
Ok(())
}
Expand Down Expand Up @@ -476,16 +483,16 @@ impl SideTable {
})
}

fn persist(self) -> MResult<Vec<BranchTableEntry>, Check> {
ia0 marked this conversation as resolved.
Show resolved Hide resolved
debug_assert!(self.entries.iter().all(|x| !x.is_invalid()));
Ok(self.entries)
fn check(self) -> MResult<Vec<BranchTableEntry>, Check> {
debug_assert!(self.0.iter().all(|x| !x.is_invalid()));
Ok(self.0)
}
}

#[derive(Debug, Copy, Clone)]
struct SideTableBranch<'m> {
parser: &'m [u8],
side_table: usize,
branch_table: usize,
stack: usize,
result: usize, // unused (zero) for source branches
}
Expand Down Expand Up @@ -524,7 +531,7 @@ impl<'a, 'm> Expr<'a, 'm> {
is_body: false,
locals: vec![],
labels: vec![Label::default()],
side_table: SideTable::default(),
branch_table: BranchTable::default(),
}
}

Expand All @@ -547,7 +554,7 @@ impl<'a, 'm> Expr<'a, 'm> {
expr.locals = locals;
expr.label().type_.results = results;
expr.check()?;
expr.side_table.persist()
expr.branch_table.check()
}

fn check(&mut self) -> CheckResult {
Expand Down Expand Up @@ -602,8 +609,8 @@ impl<'a, 'm> Expr<'a, 'm> {
LabelKind::If(source) => {
let result = self.label().type_.results.len();
let mut target = self.branch_target(result);
target.side_table += 1;
self.side_table.stitch(source, target)?
target.branch_table += 1;
self.branch_table.stitch(source, target)?
}
_ => Err(invalid())?,
}
Expand Down Expand Up @@ -858,14 +865,14 @@ impl<'a, 'm> Expr<'a, 'm> {
let results_len = self.label().type_.results.len();
let mut target = self.branch_target(results_len);
for source in core::mem::take(&mut self.label().branches) {
self.side_table.stitch(source, target)?;
self.branch_table.stitch(source, target)?;
}
let label = self.label();
if let LabelKind::If(source) = label.kind {
check(label.type_.params == label.type_.results)?;
// SAFETY: This function is only called after parsing an End instruction.
target.parser = offset_front(target.parser, -1);
self.side_table.stitch(source, target)?;
self.branch_table.stitch(source, target)?;
}
let results = self.label().type_.results;
self.pops(results)?;
Expand All @@ -888,7 +895,7 @@ impl<'a, 'm> Expr<'a, 'm> {
label.type_.results
}
LabelKind::Loop(target) => {
self.side_table.stitch(source, target)?;
self.branch_table.stitch(source, target)?;
label.type_.params
}
})
Expand All @@ -897,7 +904,7 @@ impl<'a, 'm> Expr<'a, 'm> {
fn branch_source(&mut self) -> SideTableBranch<'m> {
let mut branch = self.branch();
branch.stack += self.stack().len();
self.side_table.branch();
self.branch_table.branch();
branch
}

Expand All @@ -911,7 +918,7 @@ impl<'a, 'm> Expr<'a, 'm> {
fn branch(&self) -> SideTableBranch<'m> {
SideTableBranch {
parser: self.parser.save(),
side_table: self.side_table.save(),
branch_table: self.branch_table.save(),
stack: self.immutable_label().prev_stack,
result: 0,
}
Expand Down
Loading