From 478ddaae277f213518e1b130c4443f8267f464ea Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Fri, 15 Apr 2022 09:59:59 -0700 Subject: [PATCH] Use std::ops::Range instead of a custom type This commit removes `wasmparser::Range` and instead uses `std::ops::Range` instead. This is inspired by review on bytecodealliance/wasmtime#4005 where it's more convenience to have all the libstd methods available. --- crates/wasm-mutate/src/info.rs | 7 +-- .../wasm-mutate/src/mutators/codemotion/ir.rs | 17 +++--- .../mutators/codemotion/ir/parse_context.rs | 19 +++---- crates/wasm-mutate/src/mutators/peephole.rs | 3 +- .../wasm-mutate/src/mutators/peephole/dfg.rs | 11 ++-- .../src/mutators/peephole/eggsy/encoder.rs | 4 +- crates/wasmparser/src/binary_reader.rs | 33 ++---------- crates/wasmparser/src/lib.rs | 2 +- crates/wasmparser/src/parser.rs | 54 ++++++++----------- crates/wasmparser/src/readers.rs | 5 +- .../src/readers/component/aliases.rs | 7 ++- .../src/readers/component/exports.rs | 5 +- .../src/readers/component/functions.rs | 7 ++- .../src/readers/component/imports.rs | 7 ++- .../src/readers/component/instances.rs | 5 +- .../wasmparser/src/readers/component/start.rs | 5 +- .../wasmparser/src/readers/component/types.rs | 5 +- crates/wasmparser/src/readers/core/code.rs | 12 ++--- crates/wasmparser/src/readers/core/custom.rs | 9 ++-- crates/wasmparser/src/readers/core/data.rs | 13 ++--- .../wasmparser/src/readers/core/elements.rs | 9 ++-- crates/wasmparser/src/readers/core/exports.rs | 7 ++- .../wasmparser/src/readers/core/functions.rs | 7 ++- crates/wasmparser/src/readers/core/globals.rs | 5 +- crates/wasmparser/src/readers/core/imports.rs | 5 +- crates/wasmparser/src/readers/core/linking.rs | 7 ++- .../wasmparser/src/readers/core/memories.rs | 5 +- crates/wasmparser/src/readers/core/names.rs | 11 ++-- .../wasmparser/src/readers/core/producers.rs | 7 ++- crates/wasmparser/src/readers/core/relocs.rs | 7 ++- crates/wasmparser/src/readers/core/tables.rs | 6 +-- crates/wasmparser/src/readers/core/tags.rs | 6 +-- crates/wasmparser/src/readers/core/types.rs | 7 ++- crates/wasmparser/src/validator.rs | 19 +++---- src/bin/wasm-tools/objdump.rs | 10 ++-- 35 files changed, 158 insertions(+), 190 deletions(-) diff --git a/crates/wasm-mutate/src/info.rs b/crates/wasm-mutate/src/info.rs index 669810cde9..50e7d12cd6 100644 --- a/crates/wasm-mutate/src/info.rs +++ b/crates/wasm-mutate/src/info.rs @@ -4,6 +4,7 @@ use crate::{ }; use std::collections::HashSet; use std::convert::TryFrom; +use std::ops::Range; use wasm_encoder::{RawSection, SectionId}; use wasmparser::{Chunk, Parser, Payload, SectionReader}; @@ -79,7 +80,7 @@ impl<'a> ModuleInfo<'a> { size: _, } => { info.code = Some(info.raw_sections.len()); - info.section(SectionId::Code.into(), range, input_wasm); + info.section(SectionId::Code.into(), range.clone(), input_wasm); parser.skip_section(); // update slice, bypass the section wasm = &input_wasm[range.end..]; @@ -249,10 +250,10 @@ impl<'a> ModuleInfo<'a> { } /// Registers a new raw_section in the ModuleInfo - pub fn section(&mut self, id: u8, range: wasmparser::Range, full_wasm: &'a [u8]) { + pub fn section(&mut self, id: u8, range: Range, full_wasm: &'a [u8]) { self.raw_sections.push(RawSection { id, - data: &full_wasm[range.start..range.end], + data: &full_wasm[range], }); } diff --git a/crates/wasm-mutate/src/mutators/codemotion/ir.rs b/crates/wasm-mutate/src/mutators/codemotion/ir.rs index 6f3ba4a831..9e6522b5bf 100644 --- a/crates/wasm-mutate/src/mutators/codemotion/ir.rs +++ b/crates/wasm-mutate/src/mutators/codemotion/ir.rs @@ -3,8 +3,9 @@ use crate::{ module::map_block_type, mutators::{codemotion::ir::parse_context::ParseContext, OperatorAndByteOffset}, }; +use std::ops::Range; use wasm_encoder::{Function, Instruction}; -use wasmparser::{BlockType, Operator, Range}; +use wasmparser::{BlockType, Operator}; use self::parse_context::{Ast, Node, State}; @@ -169,7 +170,7 @@ pub trait AstWriter { &self, _ast: &Ast, _nodeidx: usize, - range: Range, + range: Range, newfunc: &mut Function, operators: &Vec, input_wasm: &'a [u8], @@ -192,7 +193,7 @@ pub trait AstWriter { &self, ast: &Ast, nodeidx: usize, - range: Range, + range: Range, newfunc: &mut Function, operators: &Vec, input_wasm: &'a [u8], @@ -232,7 +233,7 @@ pub trait AstWriter { )?; } Node::Code { range } => { - self.write_code(ast, nodeidx, *range, newfunc, operators, input_wasm)?; + self.write_code(ast, nodeidx, range.clone(), newfunc, operators, input_wasm)?; } Node::Loop { body, ty, range: _ } => { self.write_loop(ast, nodeidx, body, newfunc, operators, input_wasm, ty)? @@ -319,7 +320,7 @@ impl AstBuilder { consequent: then_branch, alternative: None, ty: ty.expect("Missing if type"), - range: Range::new(frame_start, idx), + range: frame_start..idx, }); } State::Else => { @@ -337,7 +338,7 @@ impl AstBuilder { consequent: then_branch, alternative: Some(else_branch), ty: ty.expect("Missing if type"), - range: Range::new(if_start, idx), + range: if_start..idx, }); } State::Loop => { @@ -347,7 +348,7 @@ impl AstBuilder { parse_context.push_node_to_current_parsing(Node::Loop { body: children, ty: ty.expect("Missing block type for loop"), - range: Range::new(frame_start, idx), + range: frame_start..idx, }); } State::Block => { @@ -357,7 +358,7 @@ impl AstBuilder { parse_context.push_node_to_current_parsing(Node::Block { body: children, ty: ty.expect("Missing block type for loop"), - range: Range::new(frame_start, idx), + range: frame_start..idx, }); } State::Root => { diff --git a/crates/wasm-mutate/src/mutators/codemotion/ir/parse_context.rs b/crates/wasm-mutate/src/mutators/codemotion/ir/parse_context.rs index 51867d4292..b2febde6e5 100644 --- a/crates/wasm-mutate/src/mutators/codemotion/ir/parse_context.rs +++ b/crates/wasm-mutate/src/mutators/codemotion/ir/parse_context.rs @@ -1,5 +1,6 @@ use crate::{Error, Result}; -use wasmparser::{BlockType, Range}; +use std::ops::Range; +use wasmparser::BlockType; #[derive(Debug, Default)] pub struct Ast { @@ -50,12 +51,12 @@ pub enum Node { alternative: Option>, /// The block type for the branches. ty: BlockType, - range: Range, + range: Range, }, /// Code node Code { /// Range on the instructions stream - range: Range, + range: Range, }, /// Loop Node Loop { @@ -64,7 +65,7 @@ pub enum Node { /// Block type ty: BlockType, /// Range on the instructions stream - range: Range, + range: Range, }, /// Block Node Block { @@ -73,7 +74,7 @@ pub enum Node { /// Block type ty: BlockType, /// Range on the instructions stream - range: Range, + range: Range, }, /// Special node to wrap the root nodes of the Ast Root(Vec), @@ -93,7 +94,7 @@ pub(crate) struct ParseContext { current_parsing: Vec, stack: Vec>, frames: Vec<(State, Option, usize)>, - current_code_range: Range, + current_code_range: Range, nodes: Vec, ifs: Vec, @@ -104,7 +105,7 @@ pub(crate) struct ParseContext { impl Default for ParseContext { fn default() -> Self { ParseContext { - current_code_range: Range::new(0, 0), + current_code_range: 0..0, current_parsing: Vec::new(), stack: Vec::new(), frames: Vec::new(), @@ -185,13 +186,13 @@ impl ParseContext { /// Pushes the current code parsing as a `Node::Code` instance pub fn push_current_code_as_node(&mut self) -> usize { self.push_node_to_current_parsing(Node::Code { - range: self.current_code_range, + range: self.current_code_range.clone(), }) } /// Resets the current code parsing pub fn reset_code_range_at(&mut self, idx: usize) { - self.current_code_range = Range::new(idx, idx); + self.current_code_range = idx..idx; } /// Augmnents current code parsing to include the next instruction diff --git a/crates/wasm-mutate/src/mutators/peephole.rs b/crates/wasm-mutate/src/mutators/peephole.rs index 8eec5a8996..edbcd7466a 100644 --- a/crates/wasm-mutate/src/mutators/peephole.rs +++ b/crates/wasm-mutate/src/mutators/peephole.rs @@ -40,6 +40,7 @@ use crate::{ }; use egg::{Rewrite, Runner}; use rand::{prelude::SmallRng, Rng}; +use std::ops::Range; use std::{borrow::Cow, fmt::Debug}; use wasm_encoder::{CodeSection, Function, GlobalSection, Instruction, Module, ValType}; use wasmparser::{CodeSectionReader, FunctionBody, GlobalSectionReader, LocalsReader}; @@ -467,7 +468,7 @@ pub(crate) trait CodeMutator { operator_index: usize, operators: Vec, funcreader: FunctionBody, - body_range: wasmparser::Range, + body_range: Range, function_data: &[u8], ) -> Result; diff --git a/crates/wasm-mutate/src/mutators/peephole/dfg.rs b/crates/wasm-mutate/src/mutators/peephole/dfg.rs index 1f982eb657..aa5f6bb5a9 100644 --- a/crates/wasm-mutate/src/mutators/peephole/dfg.rs +++ b/crates/wasm-mutate/src/mutators/peephole/dfg.rs @@ -9,7 +9,8 @@ use crate::mutators::OperatorAndByteOffset; use crate::{ModuleInfo, WasmMutate}; use egg::{Id, Language, RecExpr}; use std::collections::HashMap; -use wasmparser::{Operator, Range}; +use std::ops::Range; +use wasmparser::Operator; /// It executes a minimal symbolic evaluation of the stack to detect operands /// location in the code for certain operators @@ -34,7 +35,7 @@ pub struct DFGBuilder { /// function #[derive(Debug)] pub struct BBlock { - pub(crate) range: Range, + pub(crate) range: Range, } /// Node of a DFG extracted from a basic block in the Wasm code @@ -226,10 +227,8 @@ impl<'a> DFGBuilder { operator_index: usize, operators: &[OperatorAndByteOffset], ) -> Option { - let mut range = Range { - start: operator_index, - end: operator_index + 1, // The range is inclusive in the last operator - }; + // The range is inclusive in the last operator + let mut range = operator_index..operator_index + 1; // We only need the basic block upward let mut found = false; loop { diff --git a/crates/wasm-mutate/src/mutators/peephole/eggsy/encoder.rs b/crates/wasm-mutate/src/mutators/peephole/eggsy/encoder.rs index e30ba77eb6..464344391a 100644 --- a/crates/wasm-mutate/src/mutators/peephole/eggsy/encoder.rs +++ b/crates/wasm-mutate/src/mutators/peephole/eggsy/encoder.rs @@ -36,7 +36,7 @@ impl Encoder { egraph: &EG, ) -> crate::Result> { // Copy previous code - let range = basicblock.range; + let range = basicblock.range.clone(); let byterange = (&operators[0].1, &operators[range.start].1); let bytes = &config.info().get_code_section().data[*byterange.0..*byterange.1]; newfunc.raw(bytes.iter().copied()); @@ -60,7 +60,7 @@ impl Encoder { } // Copy remaining function - let range = basicblock.range; + let range = basicblock.range.clone(); let byterange = ( &operators[range.end].1, // In the worst case the next instruction will be and end &operators[operators.len() - 1].1, diff --git a/crates/wasmparser/src/binary_reader.rs b/crates/wasmparser/src/binary_reader.rs index dd39e8cd0e..58f8cfcf14 100644 --- a/crates/wasmparser/src/binary_reader.rs +++ b/crates/wasmparser/src/binary_reader.rs @@ -26,6 +26,7 @@ use crate::{ComponentArg, ComponentArgKind}; use std::convert::TryInto; use std::error::Error; use std::fmt; +use std::ops::Range; use std::str; fn is_name(name: &str, expected: &'static str) -> bool { @@ -38,31 +39,6 @@ fn is_name_prefix(name: &str, prefix: &'static str) -> bool { const WASM_MAGIC_NUMBER: &[u8; 4] = b"\0asm"; -/// Bytecode range in the WebAssembly module. -#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub struct Range { - /// The start bound of the range. - pub start: usize, - /// The end bound of the range. - pub end: usize, -} - -impl Range { - /// Constructs a new instance of `Range`. - /// - /// # Panics - /// If `start` is greater than `end`. - pub fn new(start: usize, end: usize) -> Range { - assert!(start <= end); - Range { start, end } - } - - /// Returns a new slice between `start` and `end - 1` from `data`. - pub fn slice<'a>(&self, data: &'a [u8]) -> &'a [u8] { - &data[self.start..self.end] - } -} - /// A binary reader for WebAssembly modules. #[derive(Debug, Clone)] pub struct BinaryReaderError { @@ -181,11 +157,8 @@ impl<'a> BinaryReader<'a> { } /// Returns a range from the starting offset to the end of the buffer. - pub fn range(&self) -> Range { - Range { - start: self.original_offset, - end: self.original_offset + self.buffer.len(), - } + pub fn range(&self) -> Range { + self.original_offset..self.original_offset + self.buffer.len() } pub(crate) fn remaining_buffer(&self) -> &'a [u8] { diff --git a/crates/wasmparser/src/lib.rs b/crates/wasmparser/src/lib.rs index 67e8d3bc7f..67c28878ee 100644 --- a/crates/wasmparser/src/lib.rs +++ b/crates/wasmparser/src/lib.rs @@ -25,7 +25,7 @@ #![deny(missing_docs)] -pub use crate::binary_reader::{BinaryReader, BinaryReaderError, Range, Result}; +pub use crate::binary_reader::{BinaryReader, BinaryReaderError, Result}; pub use crate::module_resources::*; pub use crate::parser::*; pub use crate::readers::*; diff --git a/crates/wasmparser/src/parser.rs b/crates/wasmparser/src/parser.rs index 73044a197a..fa9c007c62 100644 --- a/crates/wasmparser/src/parser.rs +++ b/crates/wasmparser/src/parser.rs @@ -7,12 +7,13 @@ use crate::{ use crate::{ BinaryReader, BinaryReaderError, CustomSectionReader, DataSectionReader, ElementSectionReader, ExportSectionReader, FunctionBody, FunctionSectionReader, GlobalSectionReader, - ImportSectionReader, MemorySectionReader, Range, Result, TableSectionReader, TagSectionReader, + ImportSectionReader, MemorySectionReader, Result, TableSectionReader, TagSectionReader, TypeSectionReader, }; use std::convert::TryInto; use std::fmt; use std::iter; +use std::ops::Range; pub(crate) const WASM_EXPERIMENTAL_VERSION: u32 = 0xd; pub(crate) const WASM_MODULE_VERSION: u32 = 0x1; @@ -103,7 +104,7 @@ pub enum Payload<'a> { /// The range of bytes that were parsed to consume the header of the /// module or component. Note that this range is relative to the start /// of the byte stream. - range: Range, + range: Range, }, /// A module type section was received and the provided reader can be @@ -136,7 +137,7 @@ pub enum Payload<'a> { func: u32, /// The range of bytes that specify the `func` field, specified in /// offsets relative to the start of the byte stream. - range: Range, + range: Range, }, /// A module element section was received and the provided reader can be /// used to parse the contents of the element section. @@ -147,7 +148,7 @@ pub enum Payload<'a> { count: u32, /// The range of bytes that specify the `count` field, specified in /// offsets relative to the start of the byte stream. - range: Range, + range: Range, }, /// A module data section was received and the provided reader can be /// used to parse the contents of the data section. @@ -179,7 +180,7 @@ pub enum Payload<'a> { parser: Parser, /// The range of bytes that represent the nested module in the /// original byte stream. - range: Range, + range: Range, }, /// A component section from a WebAssembly component was received and the /// provided parser can be used to parse the nested component. @@ -198,7 +199,7 @@ pub enum Payload<'a> { parser: Parser, /// The range of bytes that represent the nested component in the /// original byte stream. - range: Range, + range: Range, }, /// A component instance section was received and the provided reader can be /// used to parse the contents of the instance section. @@ -229,7 +230,7 @@ pub enum Payload<'a> { count: u32, /// The range of bytes that represent this section, specified in /// offsets relative to the start of the byte stream. - range: Range, + range: Range, /// The size, in bytes, of the remaining contents of this section. /// /// This can be used in combination with [`Parser::skip_section`] @@ -263,7 +264,7 @@ pub enum Payload<'a> { contents: &'a [u8], /// The range of bytes, relative to the start of the original data /// stream, that the contents of this section reside in. - range: Range, + range: Range, }, /// The end of the WebAssembly module or component was reached. @@ -490,10 +491,7 @@ impl Parser { Ok(Version { num, encoding: self.encoding, - range: Range { - start, - end: reader.original_position(), - }, + range: start..reader.original_position(), }) } State::SectionStart => { @@ -565,10 +563,7 @@ impl Parser { (Encoding::Module, 10) => { let start = reader.original_position(); let count = delimited(reader, &mut len, |r| r.read_var_u32())?; - let range = Range { - start, - end: reader.original_position() + len as usize, - }; + let range = start..reader.original_position() + len as usize; self.state = State::FunctionBody { remaining: count, len, @@ -620,10 +615,8 @@ impl Parser { )); } - let range = Range { - start: reader.original_position(), - end: reader.original_position() + len as usize, - }; + let range = + reader.original_position()..reader.original_position() + len as usize; self.max_size -= u64::from(len); self.offset += u64::from(len); let mut parser = Parser::new(usize_to_u64(reader.original_position())); @@ -656,10 +649,7 @@ impl Parser { (_, id) => { let offset = reader.original_position(); let contents = reader.read_bytes(len as usize)?; - let range = Range { - start: offset, - end: offset + len as usize, - }; + let range = offset..offset + len as usize; Ok(UnknownSection { id, contents, @@ -787,7 +777,8 @@ impl Parser { /// # Examples /// /// ``` - /// use wasmparser::{Result, Parser, Chunk, Range, SectionReader, Payload::*}; + /// use wasmparser::{Result, Parser, Chunk, SectionReader, Payload::*}; + /// use std::ops::Range; /// /// fn objdump_headers(mut wasm: &[u8]) -> Result<()> { /// let mut parser = Parser::new(0); @@ -819,7 +810,7 @@ impl Parser { /// Ok(()) /// } /// - /// fn print_range(section: &str, range: &Range) { + /// fn print_range(section: &str, range: &Range) { /// println!("{:>40}: {:#010x} - {:#010x}", section, range.start, range.end); /// } /// ``` @@ -869,11 +860,12 @@ fn subreader<'a>(reader: &mut BinaryReader<'a>, len: u32) -> Result(reader: &mut BinaryReader<'a>, len: u32, desc: &str) -> Result<(u32, Range)> { - let range = Range { - start: reader.original_position(), - end: reader.original_position() + len as usize, - }; +fn single_u32<'a>( + reader: &mut BinaryReader<'a>, + len: u32, + desc: &str, +) -> Result<(u32, Range)> { + let range = reader.original_position()..reader.original_position() + len as usize; let mut content = subreader(reader, len)?; // We can't recover from "unexpected eof" here because our entire section is // already resident in memory, so clear the hint for how many more bytes are diff --git a/crates/wasmparser/src/readers.rs b/crates/wasmparser/src/readers.rs index b39fe096bb..32c455630c 100644 --- a/crates/wasmparser/src/readers.rs +++ b/crates/wasmparser/src/readers.rs @@ -13,7 +13,8 @@ * limitations under the License. */ -use crate::{BinaryReaderError, Range, Result}; +use crate::{BinaryReaderError, Result}; +use std::ops::Range; mod component; mod core; @@ -36,7 +37,7 @@ pub trait SectionReader { fn original_position(&self) -> usize; /// Gets the range of the reader. - fn range(&self) -> Range; + fn range(&self) -> Range; /// Ensures the reader is at the end of the section. /// diff --git a/crates/wasmparser/src/readers/component/aliases.rs b/crates/wasmparser/src/readers/component/aliases.rs index dd321968e1..77dcc6b298 100644 --- a/crates/wasmparser/src/readers/component/aliases.rs +++ b/crates/wasmparser/src/readers/component/aliases.rs @@ -1,6 +1,5 @@ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents a kind of alias. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -119,7 +118,7 @@ impl<'a> SectionReader for AliasSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/component/exports.rs b/crates/wasmparser/src/readers/component/exports.rs index 6996dea13d..ca7aede979 100644 --- a/crates/wasmparser/src/readers/component/exports.rs +++ b/crates/wasmparser/src/readers/component/exports.rs @@ -1,7 +1,8 @@ use crate::{ - BinaryReader, ComponentArgKind, Range, Result, SectionIteratorLimited, SectionReader, + BinaryReader, ComponentArgKind, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, }; +use std::ops::Range; /// Represents the kind of export in a WebAssembly component. pub type ComponentExportKind = ComponentArgKind; @@ -73,7 +74,7 @@ impl<'a> SectionReader for ComponentExportSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/component/functions.rs b/crates/wasmparser/src/readers/component/functions.rs index 8b0ffaf8ad..5009acf7e1 100644 --- a/crates/wasmparser/src/readers/component/functions.rs +++ b/crates/wasmparser/src/readers/component/functions.rs @@ -1,6 +1,5 @@ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents options for component functions. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -98,7 +97,7 @@ impl<'a> SectionReader for ComponentFunctionSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/component/imports.rs b/crates/wasmparser/src/readers/component/imports.rs index 6975f0a275..2c8680aafb 100644 --- a/crates/wasmparser/src/readers/component/imports.rs +++ b/crates/wasmparser/src/readers/component/imports.rs @@ -1,6 +1,5 @@ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents an import in a WebAssembly component #[derive(Debug, Copy, Clone)] @@ -68,7 +67,7 @@ impl<'a> SectionReader for ComponentImportSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/component/instances.rs b/crates/wasmparser/src/readers/component/instances.rs index da3a0068c6..5291a1880f 100644 --- a/crates/wasmparser/src/readers/component/instances.rs +++ b/crates/wasmparser/src/readers/component/instances.rs @@ -1,7 +1,8 @@ use crate::{ - BinaryReader, ComponentExport, Export, Range, Result, SectionIteratorLimited, SectionReader, + BinaryReader, ComponentExport, Export, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, }; +use std::ops::Range; /// Represents the kind of argument when instantiating a WebAssembly module. #[derive(Debug, Clone)] @@ -125,7 +126,7 @@ impl<'a> SectionReader for InstanceSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/component/start.rs b/crates/wasmparser/src/readers/component/start.rs index 221bc960aa..743139271c 100644 --- a/crates/wasmparser/src/readers/component/start.rs +++ b/crates/wasmparser/src/readers/component/start.rs @@ -1,4 +1,5 @@ -use crate::{BinaryReader, Range, Result, SectionReader}; +use crate::{BinaryReader, Result, SectionReader}; +use std::ops::Range; /// Represents the start function in a WebAssembly component. #[derive(Debug, Clone)] @@ -57,7 +58,7 @@ impl<'a> SectionReader for ComponentStartSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.0.range() } } diff --git a/crates/wasmparser/src/readers/component/types.rs b/crates/wasmparser/src/readers/component/types.rs index 899c8f007d..a6bb71a7b3 100644 --- a/crates/wasmparser/src/readers/component/types.rs +++ b/crates/wasmparser/src/readers/component/types.rs @@ -1,7 +1,8 @@ use crate::{ - BinaryReader, ComponentImport, Import, Range, Result, SectionIteratorLimited, SectionReader, + BinaryReader, ComponentImport, Import, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, TypeDef, TypeRef, }; +use std::ops::Range; /// Represents a type defined in a WebAssembly component. #[derive(Debug, Clone)] @@ -267,7 +268,7 @@ impl<'a> SectionReader for ComponentTypeSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/code.rs b/crates/wasmparser/src/readers/core/code.rs index 12d6ed95fd..e2fa60442d 100644 --- a/crates/wasmparser/src/readers/core/code.rs +++ b/crates/wasmparser/src/readers/core/code.rs @@ -14,9 +14,10 @@ */ use crate::{ - BinaryReader, BinaryReaderError, OperatorsReader, Range, Result, SectionIteratorLimited, + BinaryReader, BinaryReaderError, OperatorsReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, Type, }; +use std::ops::Range; /// Represents a WebAssembly function body. #[derive(Debug, Clone, Copy)] @@ -88,11 +89,8 @@ impl<'a> FunctionBody<'a> { } /// Gets the range of the function body. - pub fn range(&self) -> Range { - Range { - start: self.offset, - end: self.offset + self.data.len(), - } + pub fn range(&self) -> Range { + self.offset..self.offset + self.data.len() } } @@ -236,7 +234,7 @@ impl<'a> SectionReader for CodeSectionReader<'a> { fn original_position(&self) -> usize { CodeSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/custom.rs b/crates/wasmparser/src/readers/core/custom.rs index b231357ce7..e5ed399256 100644 --- a/crates/wasmparser/src/readers/core/custom.rs +++ b/crates/wasmparser/src/readers/core/custom.rs @@ -1,4 +1,5 @@ -use crate::{BinaryReader, Range, Result}; +use crate::{BinaryReader, Result}; +use std::ops::Range; /// A reader for custom sections of a WebAssembly module. #[derive(Clone)] @@ -7,7 +8,7 @@ pub struct CustomSectionReader<'a> { pub(crate) name: &'a str, pub(crate) data_offset: usize, pub(crate) data: &'a [u8], - pub(crate) range: Range, + pub(crate) range: Range, } impl<'a> CustomSectionReader<'a> { @@ -45,8 +46,8 @@ impl<'a> CustomSectionReader<'a> { /// The range of bytes that specify this whole custom section (including /// both the name of this custom section and its data) specified in /// offsets relative to the start of the byte stream. - pub fn range(&self) -> Range { - self.range + pub fn range(&self) -> Range { + self.range.clone() } } diff --git a/crates/wasmparser/src/readers/core/data.rs b/crates/wasmparser/src/readers/core/data.rs index 566fcdc1f1..2eaaaa514f 100644 --- a/crates/wasmparser/src/readers/core/data.rs +++ b/crates/wasmparser/src/readers/core/data.rs @@ -14,19 +14,20 @@ */ use crate::{ - BinaryReader, BinaryReaderError, InitExpr, Range, Result, SectionIteratorLimited, - SectionReader, SectionWithLimitedItems, + BinaryReader, BinaryReaderError, InitExpr, Result, SectionIteratorLimited, SectionReader, + SectionWithLimitedItems, }; +use std::ops::Range; /// Represents a data segment in a core WebAssembly module. -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Clone)] pub struct Data<'a> { /// The kind of data segment. pub kind: DataKind<'a>, /// The data of the data segment. pub data: &'a [u8], /// The range of the data segment. - pub range: Range, + pub range: Range, } /// The kind of data segment. @@ -150,7 +151,7 @@ impl<'a> DataSectionReader<'a> { self.reader.skip_to(data_end); let segment_end = self.reader.original_position(); - let range = Range::new(segment_start, segment_end); + let range = segment_start..segment_end; Ok(Data { kind, data, range }) } @@ -167,7 +168,7 @@ impl<'a> SectionReader for DataSectionReader<'a> { fn original_position(&self) -> usize { DataSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/elements.rs b/crates/wasmparser/src/readers/core/elements.rs index 81a7319a8c..3da203ac5c 100644 --- a/crates/wasmparser/src/readers/core/elements.rs +++ b/crates/wasmparser/src/readers/core/elements.rs @@ -14,9 +14,10 @@ */ use crate::{ - BinaryReader, BinaryReaderError, ExternalKind, InitExpr, Range, Result, SectionIteratorLimited, + BinaryReader, BinaryReaderError, ExternalKind, InitExpr, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, Type, }; +use std::ops::Range; /// Represents a core WebAssembly element segment. #[derive(Clone)] @@ -28,7 +29,7 @@ pub struct Element<'a> { /// The type of the elements. pub ty: Type, /// The range of the the element segment. - pub range: Range, + pub range: Range, } /// The kind of element segment. @@ -289,7 +290,7 @@ impl<'a> ElementSectionReader<'a> { }; let elem_end = self.reader.original_position(); - let range = Range::new(elem_start, elem_end); + let range = elem_start..elem_end; Ok(Element { kind, @@ -311,7 +312,7 @@ impl<'a> SectionReader for ElementSectionReader<'a> { fn original_position(&self) -> usize { ElementSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/exports.rs b/crates/wasmparser/src/readers/core/exports.rs index 8d5f427fbc..5aa8e7316f 100644 --- a/crates/wasmparser/src/readers/core/exports.rs +++ b/crates/wasmparser/src/readers/core/exports.rs @@ -13,9 +13,8 @@ * limitations under the License. */ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// External types as defined [here]. /// @@ -103,7 +102,7 @@ impl<'a> SectionReader for ExportSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/functions.rs b/crates/wasmparser/src/readers/core/functions.rs index 36c4aaf795..a98b7fa9fe 100644 --- a/crates/wasmparser/src/readers/core/functions.rs +++ b/crates/wasmparser/src/readers/core/functions.rs @@ -13,9 +13,8 @@ * limitations under the License. */ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// A reader for the function section of a WebAssembly module. #[derive(Clone)] @@ -75,7 +74,7 @@ impl<'a> SectionReader for FunctionSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/globals.rs b/crates/wasmparser/src/readers/core/globals.rs index 22cdb4c626..b7d78fb33b 100644 --- a/crates/wasmparser/src/readers/core/globals.rs +++ b/crates/wasmparser/src/readers/core/globals.rs @@ -14,9 +14,10 @@ */ use crate::{ - BinaryReader, GlobalType, InitExpr, Range, Result, SectionIteratorLimited, SectionReader, + BinaryReader, GlobalType, InitExpr, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, }; +use std::ops::Range; /// Represents a core WebAssembly global. #[derive(Debug, Copy, Clone)] @@ -88,7 +89,7 @@ impl<'a> SectionReader for GlobalSectionReader<'a> { fn original_position(&self) -> usize { GlobalSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/imports.rs b/crates/wasmparser/src/readers/core/imports.rs index c60c188288..81df2680d8 100644 --- a/crates/wasmparser/src/readers/core/imports.rs +++ b/crates/wasmparser/src/readers/core/imports.rs @@ -14,9 +14,10 @@ */ use crate::{ - BinaryReader, GlobalType, MemoryType, Range, Result, SectionIteratorLimited, SectionReader, + BinaryReader, GlobalType, MemoryType, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, TableType, TagType, }; +use std::ops::Range; /// Represents a reference to a type definition. #[derive(Debug, Clone, Copy)] @@ -107,7 +108,7 @@ impl<'a> SectionReader for ImportSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/linking.rs b/crates/wasmparser/src/readers/core/linking.rs index 2de7adcb57..a619288dd6 100644 --- a/crates/wasmparser/src/readers/core/linking.rs +++ b/crates/wasmparser/src/readers/core/linking.rs @@ -13,9 +13,8 @@ * limitations under the License. */ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents a linking type. #[derive(Debug, Copy, Clone)] @@ -68,7 +67,7 @@ impl<'a> SectionReader for LinkingSectionReader<'a> { fn original_position(&self) -> usize { LinkingSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/memories.rs b/crates/wasmparser/src/readers/core/memories.rs index 227192f512..23d1cdcac9 100644 --- a/crates/wasmparser/src/readers/core/memories.rs +++ b/crates/wasmparser/src/readers/core/memories.rs @@ -14,9 +14,10 @@ */ use crate::{ - BinaryReader, MemoryType, Range, Result, SectionIteratorLimited, SectionReader, + BinaryReader, MemoryType, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, }; +use std::ops::Range; /// A reader for the memory section of a WebAssembly module. #[derive(Clone)] @@ -71,7 +72,7 @@ impl<'a> SectionReader for MemorySectionReader<'a> { fn original_position(&self) -> usize { MemorySectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/names.rs b/crates/wasmparser/src/readers/core/names.rs index b70c370bf0..6b8f480647 100644 --- a/crates/wasmparser/src/readers/core/names.rs +++ b/crates/wasmparser/src/readers/core/names.rs @@ -13,7 +13,8 @@ * limitations under the License. */ -use crate::{BinaryReader, BinaryReaderError, Range, Result, SectionIterator, SectionReader}; +use crate::{BinaryReader, BinaryReaderError, Result, SectionIterator, SectionReader}; +use std::ops::Range; /// Represents a name for an index from the names section. #[derive(Debug, Copy, Clone)] @@ -228,7 +229,7 @@ impl<'a> IndirectNameMap<'a> { } /// Represents a name read from the names custom section. -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Clone)] pub enum Name<'a> { /// The name is for the module. Module(SingleName<'a>), @@ -258,7 +259,7 @@ pub enum Name<'a> { data: &'a [u8], /// The range of bytes, relative to the start of the original data /// stream, that the contents of this subsection reside in. - range: Range, + range: Range, }, } @@ -322,7 +323,7 @@ impl<'a> NameSectionReader<'a> { NameType::Unknown(ty) => Name::Unknown { ty, data, - range: Range::new(offset, offset + payload_len), + range: offset..offset + payload_len, }, }) } @@ -339,7 +340,7 @@ impl<'a> SectionReader for NameSectionReader<'a> { fn original_position(&self) -> usize { NameSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/producers.rs b/crates/wasmparser/src/readers/core/producers.rs index 53596aac6d..4999aa45be 100644 --- a/crates/wasmparser/src/readers/core/producers.rs +++ b/crates/wasmparser/src/readers/core/producers.rs @@ -13,9 +13,8 @@ * limitations under the License. */ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents a field value in the producers custom section. #[derive(Debug, Copy, Clone)] @@ -191,7 +190,7 @@ impl<'a> SectionReader for ProducersSectionReader<'a> { fn original_position(&self) -> usize { ProducersSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/relocs.rs b/crates/wasmparser/src/readers/core/relocs.rs index 5751abe8d9..29a9e33faf 100644 --- a/crates/wasmparser/src/readers/core/relocs.rs +++ b/crates/wasmparser/src/readers/core/relocs.rs @@ -13,9 +13,8 @@ * limitations under the License. */ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents a relocation type. #[derive(Debug, Copy, Clone)] @@ -178,7 +177,7 @@ impl<'a> SectionReader for RelocSectionReader<'a> { fn original_position(&self) -> usize { RelocSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/tables.rs b/crates/wasmparser/src/readers/core/tables.rs index a42d2f5471..3121b5fe98 100644 --- a/crates/wasmparser/src/readers/core/tables.rs +++ b/crates/wasmparser/src/readers/core/tables.rs @@ -14,9 +14,9 @@ */ use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, - TableType, + BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, TableType, }; +use std::ops::Range; /// A reader for the table section of a WebAssembly module. #[derive(Clone)] @@ -72,7 +72,7 @@ impl<'a> SectionReader for TableSectionReader<'a> { fn original_position(&self) -> usize { TableSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/tags.rs b/crates/wasmparser/src/readers/core/tags.rs index 307fc49611..fd40779791 100644 --- a/crates/wasmparser/src/readers/core/tags.rs +++ b/crates/wasmparser/src/readers/core/tags.rs @@ -14,9 +14,9 @@ */ use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, - TagType, + BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, TagType, }; +use std::ops::Range; /// A reader for the tags section of a WebAssembly module. #[derive(Clone)] @@ -71,7 +71,7 @@ impl<'a> SectionReader for TagSectionReader<'a> { fn original_position(&self) -> usize { TagSectionReader::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/readers/core/types.rs b/crates/wasmparser/src/readers/core/types.rs index d3cf70d2cd..5ffc1adcec 100644 --- a/crates/wasmparser/src/readers/core/types.rs +++ b/crates/wasmparser/src/readers/core/types.rs @@ -13,9 +13,8 @@ * limitations under the License. */ -use crate::{ - BinaryReader, Range, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems, -}; +use crate::{BinaryReader, Result, SectionIteratorLimited, SectionReader, SectionWithLimitedItems}; +use std::ops::Range; /// Represents the types of values in a WebAssembly module. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -186,7 +185,7 @@ impl<'a> SectionReader for TypeSectionReader<'a> { Self::original_position(self) } - fn range(&self) -> Range { + fn range(&self) -> Range { self.reader.range() } } diff --git a/crates/wasmparser/src/validator.rs b/crates/wasmparser/src/validator.rs index 80ae6524e0..f98a35e17f 100644 --- a/crates/wasmparser/src/validator.rs +++ b/crates/wasmparser/src/validator.rs @@ -14,10 +14,11 @@ */ use crate::{ - limits::*, BinaryReaderError, Encoding, FunctionBody, Parser, Payload, Range, Result, - SectionReader, SectionWithLimitedItems, Type, WASM_COMPONENT_VERSION, WASM_MODULE_VERSION, + limits::*, BinaryReaderError, Encoding, FunctionBody, Parser, Payload, Result, SectionReader, + SectionWithLimitedItems, Type, WASM_COMPONENT_VERSION, WASM_MODULE_VERSION, }; use std::mem; +use std::ops::Range; use std::sync::Arc; /// Test whether the given buffer contains a valid WebAssembly module or component, @@ -433,7 +434,7 @@ impl Validator { } /// Validates [`Payload::Version`](crate::Payload). - pub fn version(&mut self, num: u32, encoding: Encoding, range: &Range) -> Result<()> { + pub fn version(&mut self, num: u32, encoding: Encoding, range: &Range) -> Result<()> { match &self.state { State::Unparsed(expected) => { if let Some(expected) = expected { @@ -700,7 +701,7 @@ impl Validator { /// Validates [`Payload::StartSection`](crate::Payload). /// /// This method should only be called when parsing a module. - pub fn start_section(&mut self, func: u32, range: &Range) -> Result<()> { + pub fn start_section(&mut self, func: u32, range: &Range) -> Result<()> { let offset = range.start; self.state.ensure_module_state("start", offset)?; let state = self.module.as_mut().unwrap(); @@ -749,7 +750,7 @@ impl Validator { /// Validates [`Payload::DataCountSection`](crate::Payload). /// /// This method should only be called when parsing a module. - pub fn data_count_section(&mut self, count: u32, range: &Range) -> Result<()> { + pub fn data_count_section(&mut self, count: u32, range: &Range) -> Result<()> { let offset = range.start; self.state.ensure_module_state("data count", offset)?; let state = self.module.as_mut().unwrap(); @@ -769,7 +770,7 @@ impl Validator { /// Validates [`Payload::CodeSectionStart`](crate::Payload). /// /// This method should only be called when parsing a module. - pub fn code_section_start(&mut self, count: u32, range: &Range) -> Result<()> { + pub fn code_section_start(&mut self, count: u32, range: &Range) -> Result<()> { let offset = range.start; self.state.ensure_module_state("code", offset)?; let state = self.module.as_mut().unwrap(); @@ -945,7 +946,7 @@ impl Validator { /// Validates [`Payload::ModuleSection`](crate::Payload). /// /// This method should only be called when parsing a component. - pub fn module_section(&mut self, range: &Range) -> Result<()> { + pub fn module_section(&mut self, range: &Range) -> Result<()> { self.state.ensure_component_state("module", range.start)?; let current = self.components.last_mut().unwrap(); check_max( @@ -967,7 +968,7 @@ impl Validator { /// Validates [`Payload::ComponentSection`](crate::Payload). /// /// This method should only be called when parsing a component. - pub fn component_section(&mut self, range: &Range) -> Result<()> { + pub fn component_section(&mut self, range: &Range) -> Result<()> { self.state .ensure_component_state("component", range.start)?; let current = self.components.last_mut().unwrap(); @@ -1081,7 +1082,7 @@ impl Validator { /// Validates [`Payload::UnknownSection`](crate::Payload). /// /// Currently always returns an error. - pub fn unknown_section(&mut self, id: u8, range: &Range) -> Result<()> { + pub fn unknown_section(&mut self, id: u8, range: &Range) -> Result<()> { Err(BinaryReaderError::new( format!("malformed section id: {}", id), range.start, diff --git a/src/bin/wasm-tools/objdump.rs b/src/bin/wasm-tools/objdump.rs index a98b966221..69514304bf 100644 --- a/src/bin/wasm-tools/objdump.rs +++ b/src/bin/wasm-tools/objdump.rs @@ -1,6 +1,7 @@ use anyhow::Result; +use std::ops::Range; use std::path::PathBuf; -use wasmparser::{CustomSectionReader, Parser, Payload::*}; +use wasmparser::{Parser, Payload::*}; /// Dumps information about sections in a WebAssembly file. /// @@ -47,10 +48,7 @@ impl Opts { AliasSection(_) => todo!("component-model"), CustomSection(c) => printer.section_raw( - wasmparser::Range { - start: c.data_offset(), - end: c.data_offset() + c.data().len(), - }, + c.data_offset()..c.data_offset() + c.data().len(), 1, &format!("custom {:?}", c.name()), ), @@ -98,7 +96,7 @@ impl Printer { self.section_raw(section.range(), section.get_count(), name) } - fn section_raw(&self, range: wasmparser::Range, count: u32, name: &str) { + fn section_raw(&self, range: Range, count: u32, name: &str) { println!( "{:40} | {:#10x} - {:#10x} | {:9} bytes | {} count", format!("{}{}", self.header(), name),