Skip to content

Commit

Permalink
Add a -d flag to wasm-tools strip (#791)
Browse files Browse the repository at this point in the history
No real reason for doing this but when I was thinking about this while
ago I figured it would be easy to strip only some sections vs others as
opposed to only an all-or-nothing toggle.
  • Loading branch information
alexcrichton committed Oct 4, 2022
1 parent 90b0163 commit 0bdc240
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ wasmparser-dump = { workspace = true, optional = true }

# Dependencies of `strip`
wasm-encoder = { workspace = true, optional = true }
regex = { version = "1.6.0", optional = true }

# Dependencies of `compose`
wasm-compose = { workspace = true, optional = true, features = ['cli'] }
Expand Down Expand Up @@ -116,5 +117,5 @@ shrink = ['wasm-shrink', 'is_executable']
mutate = ['wasm-mutate']
dump = ['wasmparser-dump']
objdump = ['wasmparser']
strip = ['wasm-encoder', 'wasmparser']
strip = ['wasm-encoder', 'wasmparser', 'regex']
compose = ['wasm-compose']
36 changes: 28 additions & 8 deletions src/bin/wasm-tools/strip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@ pub struct Opts {
#[clap(flatten)]
io: wasm_tools::InputOutput,

/// Strip all custom sections, including the `name` section
/// Remove all custom sections, regardless of name.
#[clap(long, short)]
all: bool,

/// Remove custom sections matching the specified regex.
#[clap(long, short, value_name = "REGEX")]
delete: Vec<String>,

/// Output the text format of WebAssembly instead of the binary format.
#[clap(short = 't', long)]
wat: bool,
Expand All @@ -25,6 +29,22 @@ pub struct Opts {
impl Opts {
pub fn run(&self) -> Result<()> {
let input = self.io.parse_input_wasm()?;
let to_delete = regex::RegexSet::new(self.delete.iter())?;

let strip_custom_section = |name: &str| {
// If explicitly specified, strip everything.
if self.all {
return true;
}

// If any section was called out by name only delete those sections.
if !to_delete.is_empty() {
return to_delete.is_match(name);
}

// Finally default strip everything but the `name` section.
name != "name"
};

let mut module = wasm_encoder::Module::new();

Expand Down Expand Up @@ -75,15 +95,15 @@ impl Opts {
| ComponentImportSection(_)
| ComponentExportSection(_) => unimplemented!("component model"),

CustomSection(c) if c.name() == "name" && !self.all => {
module.section(&RawSection {
id: SectionId::Custom as u8,
data: &input[c.range()],
});
CustomSection(c) => {
if !strip_custom_section(c.name()) {
module.section(&RawSection {
id: SectionId::Custom as u8,
data: &input[c.range()],
});
}
}

CustomSection(_) => {}

UnknownSection {
id,
contents,
Expand Down

0 comments on commit 0bdc240

Please sign in to comment.