Skip to content

Commit 799ccf7

Browse files
authored
Add a wasm-validate example program (bytecodealliance#202)
Shows off how to to use `validate` and makes it pretty nifty to install from crates.io if you want.
1 parent ac6df05 commit 799ccf7

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ exclude = ["fuzz/**/*", "tests/**/*", "testsuite/**/*"]
1212
edition = "2018"
1313

1414
[dev-dependencies]
15+
anyhow = "1.0"
1516
criterion = "0.3"
17+
getopts = "0.2"
1618
wast = "7.0.0"
1719

1820
[badges]

examples/wasm-validate.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
use anyhow::{Context, Result};
2+
use std::env;
3+
4+
fn main() -> Result<()> {
5+
// Use the `getopts` crate to parse the `-o` option as well as `-h`
6+
let program = env::args().nth(0).unwrap();
7+
let mut opts = getopts::Options::new();
8+
opts.optflag(
9+
"",
10+
"enable-reference-types",
11+
"Enable wasm reference types feature",
12+
);
13+
opts.optflag("", "enable-threads", "Enable wasm threads feature");
14+
opts.optflag("", "enable-simd", "Enable wasm simd feature");
15+
opts.optflag(
16+
"",
17+
"enable-bulk-memory",
18+
"Enable wasm bulk memory operations feature",
19+
);
20+
opts.optflag("", "enable-multi-value", "Enable wasm multi-value feature");
21+
#[cfg(feature = "deterministic")]
22+
opts.optflag(
23+
"",
24+
"deterministic-only",
25+
"Require only deterministic instructions",
26+
);
27+
opts.optflag("h", "help", "print this help menu");
28+
let matches = opts.parse(env::args_os().skip(1))?;
29+
if matches.opt_present("h") {
30+
return Ok(print_usage(&program, opts));
31+
}
32+
let input = match matches.free.len() {
33+
0 => {
34+
print_usage(&program, opts);
35+
std::process::exit(1);
36+
}
37+
1 => &matches.free[0],
38+
_ => anyhow::bail!("more than one input file specified on command line"),
39+
};
40+
41+
let config = wasmparser::ValidatingParserConfig {
42+
operator_config: wasmparser::OperatorValidatorConfig {
43+
enable_threads: matches.opt_present("enable-threads"),
44+
enable_reference_types: matches.opt_present("enable-reference-types"),
45+
enable_simd: matches.opt_present("enable-simd"),
46+
enable_bulk_memory: matches.opt_present("enable-bulk-memory"),
47+
enable_multi_value: matches.opt_present("enable-multi-value"),
48+
#[cfg(feature = "deterministic")]
49+
deterministic_only: matches.opt_present("deterministic-only"),
50+
},
51+
};
52+
let wasm = std::fs::read(input).context(format!("failed to read input: {}", input))?;
53+
wasmparser::validate(&wasm, Some(config)).unwrap();
54+
55+
Ok(())
56+
}
57+
58+
fn print_usage(program: &str, opts: getopts::Options) {
59+
let brief = format!("Usage: {} FILE [options]", program);
60+
print!("{}", opts.usage(&brief));
61+
}

0 commit comments

Comments
 (0)