Debian Codegraph @

crates/wasm-mutate/src/mutators/remove_item.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 //! This mutator attempts to remove various kinds of items from a wasm module.
2 //!
3 //! Removing an item from a wasm module is a somewhat tricky process because
4 //! there are many locations where indices are referenced. That means that when
5 //! this mutator is used it will need to renumber all indices in the wasm module
6 //! for references after the item that's removed. Notably this means that this
7 //! mutator largely translates between `wasmparser` structures and
8 //! `wasm_encoder` structures.
9
10 use crate::mutators::{Item, Mutator};
11 use crate::{Error, ReencodeResult};
12 use crate::{ModuleInfo, Result, WasmMutate};
13 use rand::Rng;
14 use std::collections::HashSet;
15 use wasm_encoder::reencode::Reencode;
16 use wasm_encoder::*;
17
18 /// Mutator that removes a random item in a wasm module (function, global,
19 /// table, etc).
20 #[derive(Copy, Clone)]
21 pub struct RemoveItemMutator(pub Item);
22
23 impl Mutator for RemoveItemMutator {
24 fn can_mutate(&self, config: &WasmMutate) -> bool {
25 self.0.can_mutate(config)
26 }
27
28 fn mutate<'a>(
29 &self,
30 config: &'a mut WasmMutate,
31 ) -> Result<Box<dyn Iterator<Item = Result<wasm_encoder::Module>> + 'a>> {
32 let idx = self.0.choose_removal_index(config);
33 log::trace!("attempting to remove {:?} index {}", self.0, idx);
34
35 let result = RemoveItem {
36 info: config.info(),
37 item: self.0,
38 idx,
39 referenced_functions: HashSet::new(),
40 function_reference_action: Funcref::Save,
41 used_index_that_was_removed: false,
42 }
43 .remove();
44 match result {
45 Ok(result) => {
46 log::debug!("removed {:?} index {}", self.0, idx);
47 Ok(Box::new(std::iter::once(Ok(result))))
48 }
49 Err(e) => {
50 log::trace!("failed to remove {:?} index {}: {:?}", self.0, idx, e);
51 Err(e)
52 }
53 }
54 }
55 }
56
57 impl Item {
58 fn can_mutate(&self, config: &WasmMutate) -> bool {
59 // This heuristic is a bit of a lie in that just because an item is
60 // present doesn't mean that it's actually candidate for removal. The
61 // alternative would be to build up some sort of precise liveness set of
62 // all items which is a bit of a pain to do, so instead this mutator is
63 // generally always applicable and then might just frequently return a
64 // "no mutations applicable" error later
65 let info = config.info();
66 match self {
67 Item::Function => info.num_functions() > 0,
68 Item::Table => info.num_tables() > 0,
69 Item::Memory => info.num_memories() > 0,
70 Item::Global => info.num_globals() > 0,
71 Item::Tag => info.num_tags() > 0,
72 Item::Type => info.num_types() > 0,
73
74 // Note that data/elements can lead to traps and side-effectful
75 // initialization of imported tables/memories, so these are only
76 // considered for removal if we're not preserving semantics.
77 Item::Data => !config.preserve_semantics && info.num_data() > 0,
78 Item::Element => !config.preserve_semantics && info.num_elements() > 0,
79 }
80 }
81
82 fn choose_removal_index(&self, config: &mut WasmMutate) -> u32 {
83 let info = config.info();
84 let max = match self {
85 Item::Function => info.num_functions(),
86 Item::Table => info.num_tables(),
87 Item::Memory => info.num_memories(),
88 Item::Global => info.num_globals(),
89 Item::Tag => info.num_tags(),
90 Item::Type => info.num_types(),
91 Item::Data => info.num_data(),
92 Item::Element => info.num_elements(),
93 };
94 config.rng().random_range(0..max)
95 }
96 }
97
98 struct RemoveItem<'a> {
99 info: &'a ModuleInfo<'a>,
100 item: Item,
101 idx: u32,
102 function_reference_action: Funcref,
103 referenced_functions: HashSet<u32>,
104 used_index_that_was_removed: bool,
105 }
106
107 enum Funcref {
108 /// References to functions are saved in `referenced_functions`.
109 Save,
110 /// References to functions are ignored for validity.
111 Skip,
112 /// References to functions are required to be in `.referenced_functions`
113 /// and if they're not then an error happens.
114 RequireReferenced,
115 }
116
117 impl RemoveItem<'_> {
118 fn remove(&mut self) -> Result<Module> {
119 // This is the main workhorse loop of the module translation. This will
120 // iterate over the original wasm sections, raw, and create the new
121 // module section-by-section. Sections are rewritten on-the-fly.
122 let mut module = Module::new();
123 self.parse_core_module(
124 &mut module,
125 wasmparser::Parser::new(0),
126 self.info.input_wasm,
127 )?;
128
129 // If an index was used that was actually being removed then flag this
130 // module as no longer applicable to mutate because the item wasn't
131 // actually a candidate for removal.
132 if self.used_index_that_was_removed {
133 return Err(Error::no_mutations_applicable());
134 }
135
136 Ok(module)
137 }
138
139 /// This is a helper function to filter out the items of the `section`
140 /// provided.
141 ///
142 /// The `section` given, which has items of type `section_item`, will be
143 /// iterated over and translated with the `encode` callback. The `encode`
144 /// callback is only called for items we're actually preserving in this
145 /// module.
146 fn filter_out<T>(
147 &mut self,
148 section: impl IntoIterator<Item = wasmparser::Result<T>>,
149 section_item: Item,
150 mut encode: impl FnMut(&mut Self, T) -> ReencodeResult<()>,
151 ) -> ReencodeResult<()> {
152 // Calculate the initial index by taking into account any imported items
153 // in this namespace (note that the filtering of imports doesn't use
154 // this function).
155 let mut index = match section_item {
156 Item::Function => self.info.num_imported_functions(),
157 Item::Table => self.info.num_imported_tables(),
158 Item::Tag => self.info.num_imported_tags(),
159 Item::Memory => self.info.num_imported_memories(),
160 Item::Global => self.info.num_imported_globals(),
161 Item::Data | Item::Element | Item::Type => 0,
162 };
163 for item in section {
164 let item = item?;
165 if index != self.idx || section_item != self.item {
166 encode(self, item)?;
167 }
168 index += 1;
169 }
170 Ok(())
171 }
172
173 /// This is "the point" of this type. This function remaps an `idx`
174 /// provided, in the `item` index space, to a new index.
175 ///
176 /// This `RemoveItem` structure will only remove at most one item which
177 /// means that the index given is in one of four cases:
178 ///
179 /// * If the `item` doesn't match the index space of the item we're
180 /// removing, then `idx` is guaranteed to not need modification.
181 /// * Otherwise if `idx` is less than the index being removed, it's entirely
182 /// unmodified since we're only modifying later items.
183 /// * Otherwise if `idx` matches the index that's being removed then this
184 /// means that the item was actually uses. In this situation we simply say
185 /// that the mutation is not applicable. This will bail out this entire
186 /// attempt to remove the `idx`th item and loops like `wasm-shrink` will
187 /// try something else.
188 /// * Finally our index is larger than the one being removed which means we
189 /// now decrement it by one to account for the removed item.
190 fn remap(&mut self, item: Item, idx: u32) -> ReencodeResult<u32> {
191 // If we're before the code section then all function references, no
192 // matter where they are, are considered "referencing functions" so we
193 // save the indices of that which is referenced.
194 if item == Item::Function {
195 if let Funcref::Save = self.function_reference_action {
196 self.referenced_functions.insert(idx);
197 }
198 }
199
200 Ok(if item != self.item || idx < self.idx {
201 // Different kind of item or a later item was removed, index doesn't change
202 idx
203 } else if idx == self.idx {
204 // If we're removing a referenced item then that means that this
205 // mutation fails. Flag this for later failure and otherwise pass
206 // through the index as-is.
207 self.used_index_that_was_removed = true;
208 idx
209 } else {
210 // Otherwise this item comes after the item being removed, so
211 // this item's index has decreased by one.
212 idx - 1
213 })
214 }
215 }
216
217 impl Reencode for RemoveItem<'_> {
218 type Error = Error;
219
220 fn function_index(&mut self, idx: u32) -> ReencodeResult<u32> {
221 self.remap(Item::Function, idx)
222 }
223
224 fn table_index(&mut self, idx: u32) -> ReencodeResult<u32> {
225 self.remap(Item::Table, idx)
226 }
227
228 fn memory_index(&mut self, idx: u32) -> ReencodeResult<u32> {
229 self.remap(Item::Memory, idx)
230 }
231
232 fn tag_index(&mut self, idx: u32) -> ReencodeResult<u32> {
233 self.remap(Item::Tag, idx)
234 }
235
236 fn global_index(&mut self, idx: u32) -> ReencodeResult<u32> {
237 self.remap(Item::Global, idx)
238 }
239
240 fn type_index(&mut self, idx: u32) -> ReencodeResult<u32> {
241 self.remap(Item::Type, idx)
242 }
243
244 fn data_index(&mut self, idx: u32) -> ReencodeResult<u32> {
245 self.remap(Item::Data, idx)
246 }
247
248 fn element_index(&mut self, idx: u32) -> ReencodeResult<u32> {
249 self.remap(Item::Element, idx)
250 }
251
252 fn parse_type_section(
253 &mut self,
254 types: &mut wasm_encoder::TypeSection,
255 section: wasmparser::TypeSectionReader<'_>,
256 ) -> ReencodeResult<()> {
257 self.filter_out(section, Item::Type, |me, rec_group| {
258 me.parse_recursive_type_group(types.ty(), rec_group)?;
259 Ok(())
260 })
261 }
262
263 fn parse_import_section(
264 &mut self,
265 imports: &mut wasm_encoder::ImportSection,
266 section: wasmparser::ImportSectionReader<'_>,
267 ) -> ReencodeResult<()> {
268 // The import section is a little special because it defines
269 // items in multiple index spaces. This means that the
270 // `filter_out` helper can't be used and we have to process
271 // everything manually here.
272 let mut function = 0;
273 let mut global = 0;
274 let mut table = 0;
275 let mut memory = 0;
276 let mut tag = 0;
277 for item in section {
278 let item = item?;
279 let retain;
280 match &item.ty {
281 wasmparser::TypeRef::Func(_) => {
282 retain = self.item != Item::Function || self.idx != function;
283 function += 1;
284 }
285 wasmparser::TypeRef::Table(_) => {
286 retain = self.item != Item::Table || self.idx != table;
287 table += 1;
288 }
289 wasmparser::TypeRef::Memory(_) => {
290 retain = self.item != Item::Memory || self.idx != memory;
291 memory += 1;
292 }
293 wasmparser::TypeRef::Global(_) => {
294 retain = self.item != Item::Global || self.idx != global;
295 global += 1;
296 }
297 wasmparser::TypeRef::Tag(_) => {
298 retain = self.item != Item::Tag || self.idx != tag;
299 tag += 1;
300 }
301 }
302 if retain {
303 self.parse_import(imports, item)?;
304 }
305 }
306 Ok(())
307 }
308
309 fn parse_function_section(
310 &mut self,
311 funcs: &mut wasm_encoder::FunctionSection,
312 section: wasmparser::FunctionSectionReader<'_>,
313 ) -> ReencodeResult<()> {
314 self.filter_out(section, Item::Function, |me, func| {
315 funcs.function(me.type_index(func)?);
316 Ok(())
317 })
318 }
319
320 fn parse_table_section(
321 &mut self,
322 tables: &mut wasm_encoder::TableSection,
323 section: wasmparser::TableSectionReader<'_>,
324 ) -> ReencodeResult<()> {
325 self.filter_out(section, Item::Table, |me, table| {
326 me.parse_table(tables, table)?;
327 Ok(())
328 })
329 }
330
331 fn parse_memory_section(
332 &mut self,
333 memories: &mut wasm_encoder::MemorySection,
334 section: wasmparser::MemorySectionReader<'_>,
335 ) -> ReencodeResult<()> {
336 self.filter_out(section, Item::Memory, |me, memory| {
337 memories.memory(me.memory_type(memory)?);
338 Ok(())
339 })
340 }
341
342 fn parse_global_section(
343 &mut self,
344 globals: &mut wasm_encoder::GlobalSection,
345 section: wasmparser::GlobalSectionReader<'_>,
346 ) -> ReencodeResult<()> {
347 self.filter_out(section, Item::Global, |me, global| {
348 me.parse_global(globals, global)?;
349 Ok(())
350 })
351 }
352
353 fn parse_element_section(
354 &mut self,
355 elements: &mut wasm_encoder::ElementSection,
356 section: wasmparser::ElementSectionReader<'_>,
357 ) -> ReencodeResult<()> {
358 self.filter_out(section, Item::Element, |me, elem| {
359 me.parse_element(elements, elem)?;
360 Ok(())
361 })
362 }
363
364 fn parse_data_section(
365 &mut self,
366 ret: &mut wasm_encoder::DataSection,
367 section: wasmparser::DataSectionReader<'_>,
368 ) -> ReencodeResult<()> {
369 self.filter_out(section, Item::Data, |me, data| {
370 me.parse_data(ret, data)?;
371 Ok(())
372 })
373 }
374
375 fn parse_tag_section(
376 &mut self,
377 tags: &mut wasm_encoder::TagSection,
378 section: wasmparser::TagSectionReader<'_>,
379 ) -> ReencodeResult<()> {
380 self.filter_out(section, Item::Tag, |me, tag| {
381 tags.tag(me.tag_type(tag)?);
382 Ok(())
383 })
384 }
385
386 fn data_count(&mut self, count: u32) -> ReencodeResult<u32> {
387 // Note that the data count section is decremented here if
388 // we're removing a data item, otherwise it's preserved
389 // as-is.
390 Ok(if self.item == Item::Data {
391 count - 1
392 } else {
393 count
394 })
395 }
396
397 fn start_section(&mut self, func: u32) -> ReencodeResult<u32> {
398 self.function_reference_action = Funcref::Skip;
399 let func = self.remap(Item::Function, func);
400 self.function_reference_action = Funcref::Save;
401 func
402 }
403
404 fn parse_code_section(
405 &mut self,
406 code: &mut wasm_encoder::CodeSection,
407 section: wasmparser::CodeSectionReader<'_>,
408 ) -> ReencodeResult<()> {
409 self.function_reference_action = Funcref::RequireReferenced;
410 self.filter_out(section, Item::Function, |me, body| {
411 me.parse_function_body(code, body)
412 })
413 }
414
415 fn instruction<'a>(&mut self, op: wasmparser::Operator<'a>) -> ReencodeResult<Instruction<'a>> {
416 // The reason for this is that in the code section instructions
417 // such as `ref.func 0` are only valid if function 0 is
418 // otherwise referenced somewhere in the module via things like
419 // globals, exports, element segments, etc. This means that
420 // removal of a global funcref *could* make `ref.func 0`
421 // invalid where it was valid before. To prevent creating an
422 // invalid module this block guards against this by recognizing
423 // when we're in the code section and on seeing a `ref.func`
424 // instruction it'll return an error if the index isn't
425 // otherwise referenced (probably because we removed the one
426 // item that referenced it).
427 if let wasmparser::Operator::RefFunc { function_index } = op {
428 if let Funcref::RequireReferenced = self.function_reference_action {
429 if !self.referenced_functions.contains(&function_index) {
430 self.used_index_that_was_removed = true;
431 }
432 }
433 }
434
435 wasm_encoder::reencode::utils::instruction(self, op)
436 }
437 }
438
439 #[cfg(test)]
440 mod tests {
441 use super::{Item, RemoveItemMutator};
442
443 #[test]
444 fn remove_type() {
445 crate::mutators::match_mutation(
446 r#"(module (type (func)))"#,
447 RemoveItemMutator(Item::Type),
448 r#"(module)"#,
449 );
450 }
451
452 #[test]
453 fn remove_function() {
454 crate::mutators::match_mutation(
455 r#"(module (func))"#,
456 RemoveItemMutator(Item::Function),
457 r#"(module (type (func)))"#,
458 );
459 crate::mutators::match_mutation(
460 r#"(module (import "" "" (func)))"#,
461 RemoveItemMutator(Item::Function),
462 r#"(module (type (func)))"#,
463 );
464 }
465
466 #[test]
467 fn remove_table() {
468 crate::mutators::match_mutation(
469 r#"(module (table 1 funcref))"#,
470 RemoveItemMutator(Item::Table),
471 r#"(module)"#,
472 );
473 crate::mutators::match_mutation(
474 r#"(module (import "" "" (table 1 funcref)))"#,
475 RemoveItemMutator(Item::Table),
476 r#"(module)"#,
477 );
478 }
479
480 #[test]
481 fn remove_memory() {
482 crate::mutators::match_mutation(
483 r#"(module (memory 1))"#,
484 RemoveItemMutator(Item::Memory),
485 r#"(module)"#,
486 );
487 crate::mutators::match_mutation(
488 r#"(module (import "" "" (memory 1)))"#,
489 RemoveItemMutator(Item::Memory),
490 r#"(module)"#,
491 );
492 }
493
494 #[test]
495 fn remove_global() {
496 crate::mutators::match_mutation(
497 r#"(module (global i32 (i32.const 1)))"#,
498 RemoveItemMutator(Item::Global),
499 r#"(module)"#,
500 );
501 crate::mutators::match_mutation(
502 r#"(module (import "" "" (global i32)))"#,
503 RemoveItemMutator(Item::Global),
504 r#"(module)"#,
505 );
506 }
507
508 #[test]
509 fn remove_data() {
510 crate::mutators::match_mutation(
511 r#"(module (data "xxxx"))"#,
512 RemoveItemMutator(Item::Data),
513 r#"(module)"#,
514 );
515 }
516
517 #[test]
518 fn remove_elem() {
519 crate::mutators::match_mutation(
520 r#"(module (elem funcref))"#,
521 RemoveItemMutator(Item::Element),
522 r#"(module)"#,
523 );
524 }
525
526 #[test]
527 fn renumber_functions() {
528 crate::mutators::match_mutation(
529 r#"(module
530 (func)
531 (func)
532 (func (export "renumber")
533 call 0
534 call 3)
535 (func)
536 )"#,
537 RemoveItemMutator(Item::Function),
538 r#"(module
539 (func)
540 (func (export "renumber") call 0 call 2)
541 (func)
542 )"#,
543 );
544 }
545
546 #[test]
547 fn renumber_table() {
548 crate::mutators::match_mutation(
549 r#"(module
550 (func (export "")
551 i32.const 0
552 i32.const 0
553 i32.const 0
554 table.copy 0 2
555 )
556 (table 1 funcref)
557 (table 1 funcref)
558 (table 1 funcref)
559 )"#,
560 RemoveItemMutator(Item::Table),
561 r#"(module
562 (func (export "")
563 i32.const 0
564 i32.const 0
565 i32.const 0
566 table.copy 0 1
567 )
568 (table 1 funcref)
569 (table 1 funcref)
570 )"#,
571 );
572 }
573
574 #[test]
575 fn renumber_memory() {
576 crate::mutators::match_mutation(
577 r#"(module
578 (func (export "")
579 i32.const 0
580 i32.const 0
581 i32.const 0
582 memory.copy 0 2
583 )
584 (memory 1)
585 (memory 1)
586 (memory 1)
587 )"#,
588 RemoveItemMutator(Item::Memory),
589 r#"(module
590 (func (export "")
591 i32.const 0
592 i32.const 0
593 i32.const 0
594 memory.copy 0 1
595 )
596 (memory 1)
597 (memory 1)
598 )"#,
599 );
600 }
601
602 #[test]
603 fn renumber_data() {
604 crate::mutators::match_mutation(
605 r#"(module
606 (func (export "")
607 data.drop 1
608 )
609 (data "a")
610 (data "b")
611 )"#,
612 RemoveItemMutator(Item::Data),
613 r#"(module
614 (func (export "")
615 data.drop 0
616 )
617 (data "b")
618 )"#,
619 );
620 }
621
622 #[test]
623 fn renumber_elem() {
624 crate::mutators::match_mutation(
625 r#"(module
626 (func (export "")
627 elem.drop 1
628 )
629 (func)
630 (elem func 0)
631 (elem func 1)
632 )"#,
633 RemoveItemMutator(Item::Element),
634 r#"(module
635 (func (export "")
636 elem.drop 0
637 )
638 (func)
639 (elem func 1)
640 )"#,
641 );
642 }
643
644 #[test]
645 fn renumber_type() {
646 crate::mutators::match_mutation(
647 r#"(module
648 (type (func))
649 (type (func (param i32)))
650 (func (type 1))
651 )"#,
652 RemoveItemMutator(Item::Type),
653 r#"(module
654 (type (func (param i32)))
655 (func (type 0))
656 )"#,
657 );
658 }
659
660 #[test]
661 fn renumber_global() {
662 crate::mutators::match_mutation(
663 r#"(module
664 (global i32 (i32.const 0))
665 (global i32 (i32.const 1))
666 (func (export "") (result i32) global.get 1)
667 )"#,
668 RemoveItemMutator(Item::Global),
669 r#"(module
670 (global i32 (i32.const 1))
671 (func (export "") (result i32) global.get 0)
672 )"#,
673 );
674 }
675
676 #[test]
677 fn remove_function_with_memarg64() {
678 crate::mutators::match_mutation(
679 r#"(module
680 (memory i64 0)
681 (func)
682 (func (export "")
683 i64.const 0
684 i64.load offset=1125899906842624
685 drop)
686 )"#,
687 RemoveItemMutator(Item::Function),
688 r#"(module
689 (memory i64 0)
690 (func (export "")
691 i64.const 0
692 i64.load offset=1125899906842624
693 drop)
694 )"#,
695 );
696 }
697
698 #[test]
699 fn remove_empty_element() {
700 crate::mutators::match_mutation(
701 r#"(module
702 (func (result funcref)
703 ref.func 0)
704 ;; cannot be removed otherwise the `ref.func 0` would be
705 ;; inapplicable
706 (elem declare func 0)
707 (elem declare func)
708 )"#,
709 RemoveItemMutator(Item::Element),
710 r#"(module
711 (func (result funcref)
712 ref.func 0)
713 (elem declare func 0)
714 )"#,
715 );
716 }
717 }