Debian Codegraph @

third_party/rust/wasm-smith/tests/available_imports.rs

raw
1 #![cfg(feature = "wasmparser")]
2
3 use arbitrary::{Arbitrary, Unstructured};
4 use rand::{rngs::SmallRng, RngCore, SeedableRng};
5 use std::collections::HashMap;
6 use wasm_smith::{Config, Module};
7 use wasmparser::Validator;
8 use wasmparser::{Parser, TypeRef, ValType};
9
10 mod common;
11 use common::{parser_features_from_config, validate};
12
13 #[test]
14 fn smoke_test_imports_config() {
15 let mut n_partial = 0;
16 let mut global_imports_seen = HashMap::<_, bool>::new();
17 let mut rng = SmallRng::seed_from_u64(11);
18 let mut buf = vec![0; 512];
19 for _ in 0..1024 {
20 rng.fill_bytes(&mut buf);
21
22 let mut u = Unstructured::new(&buf);
23 let (config, available) = import_config(&mut u);
24 let features = parser_features_from_config(&config);
25
26 if let Ok(module) = Module::new(config, &mut u) {
27 let wasm_bytes = module.to_bytes();
28 let mut validator = Validator::new_with_features(features);
29 validate(&mut validator, &wasm_bytes);
30 let mut imports_seen = available
31 .iter()
32 .map(|(m, f, t)| ((*m, *f), (false, t)))
33 .collect::<HashMap<_, _>>();
34 let mut sig_types = Vec::new();
35
36 for payload in Parser::new(0).parse_all(&wasm_bytes) {
37 let payload = payload.unwrap();
38 if let wasmparser::Payload::TypeSection(rdr) = payload {
39 // Gather the signature types to later check function types
40 // against.
41 for ty in rdr.into_iter_err_on_gc_types() {
42 sig_types.push(ty.unwrap());
43 }
44 } else if let wasmparser::Payload::ImportSection(rdr) = payload {
45 // Read out imports, checking that they all are within the
46 // list of expected imports (i.e. we don't generate
47 // arbitrary ones), and that we handle the logic correctly
48 // (i.e. signature types are as expected)
49 for import in rdr {
50 let import = import.unwrap();
51 use AvailableImportKind as I;
52 let entry = imports_seen.get_mut(&(import.module, import.name));
53 match (entry, &import.ty) {
54 (Some((true, _)), _) => panic!("duplicate import of {:?}", import),
55 (Some((seen, I::Memory)), TypeRef::Memory(_)) => *seen = true,
56 (Some((seen, I::Global(t))), TypeRef::Global(gt))
57 if *t == gt.content_type =>
58 {
59 *seen = true
60 }
61 (Some((seen, I::Table(t))), TypeRef::Table(tt))
62 if *t == ValType::Ref(tt.element_type) =>
63 {
64 *seen = true
65 }
66 (Some((seen, I::Func(p, r))), TypeRef::Func(sig_idx))
67 if sig_types[*sig_idx as usize].params() == *p
68 && sig_types[*sig_idx as usize].results() == *r =>
69 {
70 *seen = true
71 }
72 (
73 Some((seen, I::Tag(p))),
74 TypeRef::Tag(wasmparser::TagType { func_type_idx, .. }),
75 ) if sig_types[*func_type_idx as usize].params() == *p
76 && sig_types[*func_type_idx as usize].results().is_empty() =>
77 {
78 *seen = true
79 }
80 (Some((_, expected)), _) => panic!(
81 "import {:?} type mismatch, expected: {:?}",
82 import, expected
83 ),
84 (None, _) => panic!("import of an unknown entity: {:?}", import),
85 }
86 }
87 }
88 }
89
90 // Verify that we have seen both instances with partial imports
91 // (i.e. we don't always just copy over all the imports from the
92 // example module) and also that we eventually observe all of the
93 // imports being used (i.e. selection is reasonably random)
94 for (m, f, _) in &available[..] {
95 let seen = imports_seen[&(*m, *f)];
96 let global_seen = global_imports_seen
97 .entry((m.to_string(), f.to_string()))
98 .or_default();
99 *global_seen |= seen.0;
100 }
101 if !imports_seen.values().all(|v| v.0) {
102 n_partial += 1;
103 }
104 }
105 }
106 assert!(global_imports_seen.values().all(|v| *v));
107 assert!(n_partial > 0);
108 }
109
110 #[derive(Debug)]
111 enum AvailableImportKind {
112 Func(&'static [ValType], &'static [ValType]),
113 Tag(&'static [ValType]),
114 Global(ValType),
115 Table(ValType),
116 Memory,
117 }
118
119 fn import_config(
120 u: &mut Unstructured,
121 ) -> (
122 Config,
123 Vec<(&'static str, &'static str, AvailableImportKind)>,
124 ) {
125 let mut config = Config::arbitrary(u).expect("arbitrary swarm");
126 config.gc_enabled = false;
127 config.exceptions_enabled = u.arbitrary().expect("exceptions enabled for swarm");
128 let available = {
129 use {AvailableImportKind::*, ValType::*};
130 vec![
131 ("env", "pi", Func(&[I32], &[])),
132 ("env", "pi2", Func(&[I32], &[])),
133 ("env", "pipi2", Func(&[I32, I32], &[])),
134 ("env", "po", Func(&[], &[I32])),
135 ("env", "pipo", Func(&[I32], &[I32])),
136 ("env", "popo", Func(&[], &[I32, I32])),
137 ("env", "mem", Memory),
138 ("env", "tbl", Table(ValType::FUNCREF)),
139 ("vars", "g", Global(I64)),
140 ("tags", "tag1", Tag(&[I32])),
141 ]
142 };
143 config.available_imports = Some(
144 wat::parse_str(
145 r#"
146 (module
147 (import "env" "pi" (func (param i32)))
148 (import "env" "pi2" (func (param i32)))
149 (import "env" "pipi2" (func (param i32 i32)))
150 (import "env" "po" (func (result i32)))
151 (import "env" "pipo" (func (param i32) (result i32)))
152 (import "env" "popo" (func (result i32 i32)))
153 (import "env" "mem" (memory 1 16))
154 (import "env" "tbl" (table 1 16 funcref))
155 (import "vars" "g" (global i64))
156 (import "tags" "tag1" (tag (param i32)))
157 )
158 "#,
159 )
160 .unwrap()
161 .into(),
162 );
163 (config, available)
164 }