Debian Codegraph @

crates/wasm-smith/tests/available_imports.rs

raw ◀ ▶
1 Debian patch touch this file
1 #![cfg(feature = "wasmparser")]
2
3 use arbitrary::Unstructured;
•4 use rand::{Rng, SeedableRng, rngs::SmallRng};
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::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 = config.features();
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 recgrp in rdr {
42 let recgrp = recgrp.unwrap();
43 for subtype in recgrp.into_types() {
44 match subtype.composite_type.inner {
45 wasmparser::CompositeInnerType::Func(func_type) => {
46 sig_types.push(Some(func_type))
47 }
48 _ => sig_types.push(None),
49 }
50 }
51 }
52 } else if let wasmparser::Payload::ImportSection(rdr) = payload {
53 // Read out imports, checking that they all are within the
54 // list of expected imports (i.e. we don't generate
55 // arbitrary ones), and that we handle the logic correctly
56 // (i.e. signature types are as expected)
57 for import in rdr {
58 let import = import.unwrap();
59 use AvailableImportKind as I;
60 let entry = imports_seen.get_mut(&(import.module, import.name));
61 match (entry, &import.ty) {
62 (Some((true, _)), _) => panic!("duplicate import of {import:?}"),
63 (Some((seen, I::Memory)), TypeRef::Memory(_)) => *seen = true,
64 (Some((seen, I::Global(t))), TypeRef::Global(gt))
65 if *t == gt.content_type =>
66 {
67 *seen = true
68 }
69 (Some((seen, I::Table(t))), TypeRef::Table(tt))
70 if *t == ValType::Ref(tt.element_type) =>
71 {
72 *seen = true
73 }
74 (Some((seen, I::Func(p, r))), TypeRef::Func(sig_idx))
75 if sig_types[*sig_idx as usize].clone().unwrap().params() == *p
76 && sig_types[*sig_idx as usize].clone().unwrap().results()
77 == *r =>
78 {
79 *seen = true
80 }
81 (
82 Some((seen, I::Tag(p))),
83 TypeRef::Tag(wasmparser::TagType { func_type_idx, .. }),
84 ) if sig_types[*func_type_idx as usize].clone().unwrap().params()
85 == *p
86 && sig_types[*func_type_idx as usize]
87 .clone()
88 .unwrap()
89 .results()
90 .is_empty() =>
91 {
92 *seen = true
93 }
94 (Some((_, expected)), _) => {
95 panic!("import {import:?} type mismatch, expected: {expected:?}")
96 }
97 (None, _) => panic!("import of an unknown entity: {import:?}"),
98 }
99 }
100 }
101 }
102
103 // Verify that we have seen both instances with partial imports
104 // (i.e. we don't always just copy over all the imports from the
105 // example module) and also that we eventually observe all of the
106 // imports being used (i.e. selection is reasonably random)
107 for (m, f, _) in &available[..] {
108 let seen = imports_seen[&(*m, *f)];
109 let global_seen = global_imports_seen
110 .entry((m.to_string(), f.to_string()))
111 .or_default();
112 *global_seen |= seen.0;
113 }
114 if !imports_seen.values().all(|v| v.0) {
115 n_partial += 1;
116 }
117 }
118 }
119 assert!(global_imports_seen.values().all(|v| *v));
120 assert!(n_partial > 0);
121 }
122
123 #[derive(Debug)]
124 enum AvailableImportKind {
125 Func(Vec<ValType>, Vec<ValType>),
126 Tag(Vec<ValType>),
127 Global(ValType),
128 Table(ValType),
129 Memory,
130 }
131
132 fn import_config(
133 u: &mut Unstructured,
134 ) -> (
135 Config,
136 Vec<(&'static str, &'static str, AvailableImportKind)>,
137 ) {
138 let mut config = Config::default();
139 config.exceptions_enabled = u.arbitrary().expect("exceptions enabled for swarm");
140 let available = {
141 use {
142 AvailableImportKind::*,
143 ValType::*,
144 wasmparser::{PackedIndex, RefType},
145 };
146 vec![
147 ("env", "pi", Func(vec![I32], vec![])),
148 ("env", "pi2", Func(vec![I32], vec![])),
149 ("env", "pipi2", Func(vec![I32, I32], vec![])),
150 ("env", "po", Func(vec![], vec![I32])),
151 ("env", "pipo", Func(vec![I32], vec![I32])),
152 ("env", "popo", Func(vec![], vec![I32, I32])),
153 ("env", "mem", Memory),
154 ("env", "tbl", Table(ValType::FUNCREF)),
155 ("vars", "g", Global(I64)),
156 ("tags", "tag1", Tag(vec![I32])),
157 (
158 "tags",
159 "tag2",
160 Tag(vec![Ref(RefType::concrete(
161 true,
162 PackedIndex::from_module_index(0).unwrap(),
163 ))]),
164 ),
165 ]
166 };
167 config.available_imports = Some(
168 wat::parse_str(
169 r#"
170 (module
171 (rec
172 (type $s0 (array (ref $s1)))
173 (type $s1 (array (ref $s0)))
174 )
175 (import "env" "pi" (func (param i32)))
176 (import "env" "pi2" (func (param i32)))
177 (import "env" "pipi2" (func (param i32 i32)))
178 (import "env" "po" (func (result i32)))
179 (import "env" "pipo" (func (param i32) (result i32)))
180 (import "env" "popo" (func (result i32 i32)))
181 (import "env" "mem" (memory 1 16))
182 (import "env" "tbl" (table 1 16 funcref))
183 (import "vars" "g" (global i64))
184 (import "tags" "tag1" (tag (param i32)))
185 (import "tags" "tag2" (tag (param (ref null $s0))))
186 )
187 "#,
188 )
189 .unwrap()
190 .into(),
191 );
192 (config, available)
193 }