Debian Codegraph @

third_party/rust/wasmparser/benches/benchmark.rs

raw
1 use anyhow::Result;
2 use criterion::{criterion_group, criterion_main, Criterion};
3 use once_cell::unsync::Lazy;
4 use std::fs;
5 use std::path::Path;
6 use std::path::PathBuf;
7 use wasmparser::{DataKind, ElementKind, Parser, Payload, Validator, VisitOperator, WasmFeatures};
8
9 /// A benchmark input.
10 pub struct BenchmarkInput {
11 /// The path to the benchmark file important for handling errors.
12 pub path: PathBuf,
13 /// The encoded Wasm module that is run by the benchmark.
14 pub wasm: Vec<u8>,
15 }
16
17 impl BenchmarkInput {
18 /// Creates a new benchmark input.
19 pub fn new(test_path: PathBuf, encoded_wasm: Vec<u8>) -> Self {
20 Self {
21 path: test_path,
22 wasm: encoded_wasm,
23 }
24 }
25 }
26
27 /// Returns a vector of all found benchmark input files under the given directory.
28 ///
29 /// Benchmark input files can be `.wat` or `.wast` formatted files.
30 /// For `.wast` files we pull out all the module directives and run them in the benchmarks.
31 fn collect_test_files(path: &Path, list: &mut Vec<BenchmarkInput>) -> Result<()> {
32 for entry in path.read_dir()? {
33 let entry = entry?;
34 let path = entry.path();
35 if path.is_dir() {
36 collect_test_files(&path, list)?;
37 continue;
38 }
39 match path.extension().and_then(|ext| ext.to_str()) {
40 Some("wasm") => {
41 let wasm = fs::read(&path)?;
42 list.push(BenchmarkInput::new(path, wasm));
43 }
44 Some("wat") | Some("txt") => {
45 if let Ok(wasm) = wat::parse_file(&path) {
46 list.push(BenchmarkInput::new(path, wasm));
47 }
48 }
49 Some("wast") => {
50 let contents = fs::read_to_string(&path)?;
51 let buf = match wast::parser::ParseBuffer::new(&contents) {
52 Ok(buf) => buf,
53 Err(_) => continue,
54 };
55 let wast: wast::Wast<'_> = match wast::parser::parse(&buf) {
56 Ok(wast) => wast,
57 Err(_) => continue,
58 };
59 for directive in wast.directives {
60 match directive {
61 wast::WastDirective::Module(mut module)
62 | wast::WastDirective::ModuleDefinition(mut module) => {
63 let wasm = module.encode()?;
64 list.push(BenchmarkInput::new(path.clone(), wasm));
65 }
66 _ => continue,
67 }
68 }
69 }
70 _ => (),
71 }
72 }
73 Ok(())
74 }
75
76 /// Reads the input given the Wasm parser or validator.
77 ///
78 /// The `path` specifies which benchmark input file we are currently operating on
79 /// so that we can report better errors in case of failures.
80 fn read_all_wasm(wasm: &[u8]) -> Result<()> {
81 use Payload::*;
82 for item in Parser::new(0).parse_all(wasm) {
83 match item? {
84 TypeSection(s) => {
85 for item in s {
86 item?;
87 }
88 }
89 ImportSection(s) => {
90 for item in s {
91 item?;
92 }
93 }
94 FunctionSection(s) => {
95 for item in s {
96 item?;
97 }
98 }
99 TableSection(s) => {
100 for item in s {
101 item?;
102 }
103 }
104 MemorySection(s) => {
105 for item in s {
106 item?;
107 }
108 }
109 TagSection(s) => {
110 for item in s {
111 item?;
112 }
113 }
114 GlobalSection(s) => {
115 for item in s {
116 for op in item?.init_expr.get_operators_reader() {
117 op?;
118 }
119 }
120 }
121 ExportSection(s) => {
122 for item in s {
123 item?;
124 }
125 }
126 ElementSection(s) => {
127 for item in s {
128 let item = item?;
129 if let ElementKind::Active { offset_expr, .. } = item.kind {
130 for op in offset_expr.get_operators_reader() {
131 op?;
132 }
133 }
134 match item.items {
135 wasmparser::ElementItems::Functions(r) => {
136 for op in r {
137 op?;
138 }
139 }
140 wasmparser::ElementItems::Expressions(_, r) => {
141 for op in r {
142 op?;
143 }
144 }
145 }
146 }
147 }
148 DataSection(s) => {
149 for item in s {
150 let item = item?;
151 if let DataKind::Active { offset_expr, .. } = item.kind {
152 for op in offset_expr.get_operators_reader() {
153 op?;
154 }
155 }
156 }
157 }
158 CodeSectionEntry(body) => {
159 let mut reader = body.get_binary_reader();
160 for _ in 0..reader.read_var_u32()? {
161 reader.read_var_u32()?;
162 reader.read::<wasmparser::ValType>()?;
163 }
164 while !reader.eof() {
165 reader.visit_operator(&mut NopVisit)?;
166 }
167 }
168
169 // Component sections
170 ModuleSection { .. } => {}
171 InstanceSection(s) => {
172 for item in s {
173 item?;
174 }
175 }
176 CoreTypeSection(s) => {
177 for item in s {
178 item?;
179 }
180 }
181 ComponentSection { .. } => {}
182 ComponentInstanceSection(s) => {
183 for item in s {
184 item?;
185 }
186 }
187 ComponentAliasSection(s) => {
188 for item in s {
189 item?;
190 }
191 }
192 ComponentTypeSection(s) => {
193 for item in s {
194 item?;
195 }
196 }
197 ComponentCanonicalSection(s) => {
198 for item in s {
199 item?;
200 }
201 }
202 ComponentStartSection { .. } => {}
203 ComponentImportSection(s) => {
204 for item in s {
205 item?;
206 }
207 }
208 ComponentExportSection(s) => {
209 for item in s {
210 item?;
211 }
212 }
213
214 Version { .. }
215 | StartSection { .. }
216 | DataCountSection { .. }
217 | UnknownSection { .. }
218 | CustomSection { .. }
219 | CodeSectionStart { .. }
220 | End(_) => {}
221
222 other => {
223 // NB: if you hit this panic if you'd be so kind as to grep
224 // through other locations in the code base that need to be
225 // updated as well. As of the time of this writing the locations
226 // might be:
227 //
228 // * src/bin/wasm-tools/objdump.rs
229 // * src/bin/wasm-tools/dump.rs
230 // * crates/wasm-encoder/src/reencode.rs
231 // * crates/wasm-encoder/src/reencode/component.rs
232 // * crates/wasmprinter/src/lib.rs
233 // * crates/wit-component/src/gc.rs
234 //
235 // This is required due to the `#[non_exhaustive]` nature of
236 // the `Payload` enum.
237 panic!("a new match statement should be added above for this case: {other:?}")
238 }
239 }
240 }
241 Ok(())
242 }
243
244 /// Returns the default benchmark inputs that are proper `wasmparser` benchmark
245 /// test inputs.
246 fn collect_benchmark_inputs() -> Vec<BenchmarkInput> {
247 let mut ret = Vec::new();
248 collect_test_files("../../tests".as_ref(), &mut ret).unwrap();
249 // Sort to ideally get more deterministic perf that ignores filesystems
250 ret.sort_by_key(|p| p.path.clone());
251 ret
252 }
253
254 fn skip_validation(test: &Path) -> bool {
255 let broken = [
256 "gc/gc-rec-sub.wat",
257 "proposals/gc/type-equivalence.wast",
258 "proposals/gc/type-subtyping.wast",
259 ];
260
261 let test_path = test.to_str().unwrap().replace("\\", "/"); // for windows paths
262 if broken.iter().any(|x| test_path.contains(x)) {
263 return true;
264 }
265
266 false
267 }
268
269 fn define_benchmarks(c: &mut Criterion) {
270 let _ = env_logger::try_init();
271
272 fn validator() -> Validator {
273 Validator::new_with_features(WasmFeatures::all())
274 }
275
276 let test_inputs = once_cell::unsync::Lazy::new(collect_benchmark_inputs);
277
278 let parse_inputs = once_cell::unsync::Lazy::new(|| {
279 let mut list = Vec::new();
280 for input in test_inputs.iter() {
281 if read_all_wasm(&input.wasm).is_ok() {
282 list.push(&input.wasm);
283 }
284 }
285 list
286 });
287 c.bench_function("parse/tests", |b| {
288 Lazy::force(&parse_inputs);
289 b.iter(|| {
290 for wasm in parse_inputs.iter() {
291 read_all_wasm(wasm).unwrap();
292 }
293 })
294 });
295
296 let validate_inputs = once_cell::unsync::Lazy::new(|| {
297 let mut list = Vec::new();
298 for input in test_inputs.iter() {
299 if skip_validation(&input.path) {
300 continue;
301 }
302 log::debug!("Validating {}", input.path.display());
303 if validator().validate_all(&input.wasm).is_ok() {
304 list.push(&input.wasm);
305 }
306 }
307 list
308 });
309 c.bench_function("validate/tests", |b| {
310 Lazy::force(&validate_inputs);
311 b.iter(|| {
312 for wasm in validate_inputs.iter() {
313 validator().validate_all(wasm).unwrap();
314 }
315 })
316 });
317
318 for file in std::fs::read_dir("benches").unwrap() {
319 let file = file.unwrap();
320 let path = file.path();
321 if path.extension().and_then(|s| s.to_str()) != Some("wasm") {
322 continue;
323 }
324 let name = path.file_stem().unwrap().to_str().unwrap();
325 let wasm = Lazy::new(|| std::fs::read(&path).unwrap());
326 c.bench_function(&format!("validate/{name}"), |b| {
327 Lazy::force(&wasm);
328 b.iter(|| {
329 validator().validate_all(&wasm).unwrap();
330 })
331 });
332 c.bench_function(&format!("parse/{name}"), |b| {
333 Lazy::force(&wasm);
334 b.iter(|| {
335 read_all_wasm(&wasm).unwrap();
336 })
337 });
338 }
339 }
340
341 criterion_group!(benchmark, define_benchmarks);
342 criterion_main!(benchmark);
343
344 struct NopVisit;
345
346 macro_rules! define_visit_operator {
347 ($(@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {
348 $(
349 fn $visit(&mut self $($(,$arg: $argty)*)?) {
350 define_visit_operator!(@visit $op $( $($arg)* )?);
351 }
352 )*
353 };
354
355 (@visit BrTable $table:ident) => {
356 for target in $table.targets() {
357 target.unwrap();
358 }
359 };
360 (@visit $($rest:tt)*) => {}
361 }
362
363 #[allow(unused_variables)]
364 impl<'a> VisitOperator<'a> for NopVisit {
365 type Output = ();
366
367 wasmparser::for_each_operator!(define_visit_operator);
368 }