1 //! This module generates test cases for the Wasmtime component model function APIs,
2 //! e.g. `wasmtime::component::func::Func` and `TypedFunc`.
3 //!
4 //! Each case includes a list of arbitrary interface types to use as parameters, plus another one to use as a
5 //! result, and a component which exports a function and imports a function.  The exported function forwards its
6 //! parameters to the imported one and forwards the result back to the caller.  This serves to exercise Wasmtime's
7 //! lifting and lowering code and verify the values remain intact during both processes.
8 
9 use crate::block_on;
10 use crate::generators::{self, CompilerStrategy, InstanceAllocationStrategy};
11 use crate::oracles::log_wasm;
12 use arbitrary::{Arbitrary, Unstructured};
13 use std::any::Any;
14 use std::fmt::Debug;
15 use std::ops::ControlFlow;
16 use wasmtime::component::{
17     self, Accessor, Component, ComponentNamedList, Lift, Linker, Lower, Val,
18 };
19 use wasmtime::{AsContextMut, Enabled, Engine, Result, Store, StoreContextMut};
20 use wasmtime_test_util::component_fuzz::{
21     Declarations, EXPORT_FUNCTION, IMPORT_FUNCTION, MAX_TYPE_DEPTH, TestCase, Type,
22 };
23 
24 /// Minimum length of an arbitrary list value generated for a test case
25 const MIN_LIST_LENGTH: u32 = 0;
26 
27 /// Maximum length of an arbitrary list value generated for a test case
28 const MAX_LIST_LENGTH: u32 = 10;
29 
30 /// Generate an arbitrary instance of the specified type.
31 fn arbitrary_val(ty: &component::Type, input: &mut Unstructured) -> arbitrary::Result<Val> {
32     use component::Type;
33 
34     Ok(match ty {
35         Type::Bool => Val::Bool(input.arbitrary()?),
36         Type::S8 => Val::S8(input.arbitrary()?),
37         Type::U8 => Val::U8(input.arbitrary()?),
38         Type::S16 => Val::S16(input.arbitrary()?),
39         Type::U16 => Val::U16(input.arbitrary()?),
40         Type::S32 => Val::S32(input.arbitrary()?),
41         Type::U32 => Val::U32(input.arbitrary()?),
42         Type::S64 => Val::S64(input.arbitrary()?),
43         Type::U64 => Val::U64(input.arbitrary()?),
44         Type::Float32 => Val::Float32(input.arbitrary()?),
45         Type::Float64 => Val::Float64(input.arbitrary()?),
46         Type::Char => Val::Char(input.arbitrary()?),
47         Type::String => Val::String(input.arbitrary()?),
48         Type::List(list) => {
49             let mut values = Vec::new();
50             input.arbitrary_loop(Some(MIN_LIST_LENGTH), Some(MAX_LIST_LENGTH), |input| {
51                 values.push(arbitrary_val(&list.ty(), input)?);
52 
53                 Ok(ControlFlow::Continue(()))
54             })?;
55 
56             Val::List(values)
57         }
58         Type::Record(record) => Val::Record(
59             record
60                 .fields()
61                 .map(|field| Ok((field.name.to_string(), arbitrary_val(&field.ty, input)?)))
62                 .collect::<arbitrary::Result<_>>()?,
63         ),
64         Type::Tuple(tuple) => Val::Tuple(
65             tuple
66                 .types()
67                 .map(|ty| arbitrary_val(&ty, input))
68                 .collect::<arbitrary::Result<_>>()?,
69         ),
70         Type::Variant(variant) => {
71             let cases = variant.cases().collect::<Vec<_>>();
72             let case = input.choose(&cases)?;
73             let payload = match &case.ty {
74                 Some(ty) => Some(Box::new(arbitrary_val(ty, input)?)),
75                 None => None,
76             };
77             Val::Variant(case.name.to_string(), payload)
78         }
79         Type::Enum(en) => {
80             let names = en.names().collect::<Vec<_>>();
81             let name = input.choose(&names)?;
82             Val::Enum(name.to_string())
83         }
84         Type::Option(option) => {
85             let discriminant = input.int_in_range(0..=1)?;
86             Val::Option(match discriminant {
87                 0 => None,
88                 1 => Some(Box::new(arbitrary_val(&option.ty(), input)?)),
89                 _ => unreachable!(),
90             })
91         }
92         Type::Result(result) => {
93             let discriminant = input.int_in_range(0..=1)?;
94             Val::Result(match discriminant {
95                 0 => Ok(match result.ok() {
96                     Some(ty) => Some(Box::new(arbitrary_val(&ty, input)?)),
97                     None => None,
98                 }),
99                 1 => Err(match result.err() {
100                     Some(ty) => Some(Box::new(arbitrary_val(&ty, input)?)),
101                     None => None,
102                 }),
103                 _ => unreachable!(),
104             })
105         }
106         Type::Flags(flags) => Val::Flags(
107             flags
108                 .names()
109                 .filter_map(|name| {
110                     input
111                         .arbitrary()
112                         .map(|p| if p { Some(name.to_string()) } else { None })
113                         .transpose()
114                 })
115                 .collect::<arbitrary::Result<_>>()?,
116         ),
117 
118         // Resources, futures, streams, and error contexts aren't fuzzed at this time.
119         Type::Own(_) | Type::Borrow(_) | Type::Future(_) | Type::Stream(_) | Type::ErrorContext => {
120             unreachable!()
121         }
122     })
123 }
124 
125 fn store<T>(input: &mut Unstructured<'_>, val: T) -> arbitrary::Result<Store<T>> {
126     crate::init_fuzzing();
127 
128     let mut config = input.arbitrary::<generators::Config>()?;
129     config.enable_async(input)?;
130     config.module_config.config.multi_value_enabled = true;
131     config.module_config.config.reference_types_enabled = true;
132     config.module_config.config.max_memories = 2;
133     config.module_config.component_model_async = true;
134     config.module_config.component_model_async_stackful = true;
135     if config.wasmtime.compiler_strategy == CompilerStrategy::Winch {
136         config.wasmtime.compiler_strategy = CompilerStrategy::CraneliftNative;
137     }
138 
139     fn set_min<T>(a: &mut T, min: T)
140     where
141         T: Ord + Copy,
142     {
143         if *a < min {
144             *a = min;
145         }
146     }
147 
148     fn set_opt_min<T>(a: &mut Option<T>, min: T)
149     where
150         T: Ord + Copy,
151     {
152         if let Some(a) = a {
153             set_min(a, min);
154         }
155     }
156 
157     if let InstanceAllocationStrategy::Pooling(p) = &mut config.wasmtime.strategy {
158         set_min(&mut p.total_component_instances, 5);
159         set_min(&mut p.total_core_instances, 5);
160         set_min(&mut p.total_memories, 2);
161         set_min(&mut p.max_memories_per_component, 2);
162         set_min(&mut p.max_memories_per_module, 2);
163         p.memory_protection_keys = Enabled::No;
164         p.max_memory_size = 10 << 20; // 10 MiB
165     }
166     set_opt_min(
167         &mut config.wasmtime.memory_config.memory_reservation,
168         10 << 20,
169     );
170 
171     let engine = Engine::new(
172         config
173             .to_wasmtime()
174             .debug_adapter_modules(input.arbitrary()?),
175     )
176     .unwrap();
177     let mut store = Store::new(&engine, val);
178     config.configure_store_epoch_and_fuel(&mut store);
179     Ok(store)
180 }
181 
182 /// Generate zero or more sets of arbitrary argument and result values and execute the test using those
183 /// values, asserting that they flow from host-to-guest and guest-to-host unchanged.
184 pub fn static_api_test<'a, P, R>(
185     input: &mut Unstructured<'a>,
186     declarations: &Declarations,
187 ) -> arbitrary::Result<()>
188 where
189     P: ComponentNamedList
190         + Lift
191         + Lower
192         + Clone
193         + PartialEq
194         + Debug
195         + Arbitrary<'a>
196         + Send
197         + Sync
198         + 'static,
199     R: ComponentNamedList
200         + Lift
201         + Lower
202         + Clone
203         + PartialEq
204         + Debug
205         + Arbitrary<'a>
206         + Send
207         + Sync
208         + 'static,
209 {
210     crate::init_fuzzing();
211 
212     let mut store = store::<Box<dyn Any + Send>>(input, Box::new(()))?;
213     let engine = store.engine();
214     let wat = declarations.make_component();
215     let wat = wat.as_bytes();
216     crate::oracles::log_wasm(wat);
217     let component = Component::new(&engine, wat).unwrap();
218     let mut linker = Linker::new(&engine);
219 
220     fn host_function<P, R>(
221         cx: StoreContextMut<'_, Box<dyn Any + Send>>,
222         params: P,
223     ) -> anyhow::Result<R>
224     where
225         P: Debug + PartialEq + 'static,
226         R: Debug + Clone + 'static,
227     {
228         log::trace!("received parameters {params:?}");
229         let data: &(P, R) = cx.data().downcast_ref().unwrap();
230         let (expected_params, result) = data;
231         assert_eq!(params, *expected_params);
232         log::trace!("returning result {result:?}");
233         Ok(result.clone())
234     }
235 
236     if declarations.options.host_async {
237         linker
238             .root()
239             .func_wrap_concurrent(IMPORT_FUNCTION, |a, params| {
240                 Box::pin(async move {
241                     a.with(|mut cx| host_function::<P, R>(cx.as_context_mut(), params))
242                 })
243             })
244             .unwrap();
245     } else {
246         linker
247             .root()
248             .func_wrap(IMPORT_FUNCTION, |cx, params| {
249                 host_function::<P, R>(cx, params)
250             })
251             .unwrap();
252     }
253 
254     block_on(async {
255         let instance = linker
256             .instantiate_async(&mut store, &component)
257             .await
258             .unwrap();
259         let func = instance
260             .get_typed_func::<P, R>(&mut store, EXPORT_FUNCTION)
261             .unwrap();
262 
263         while input.arbitrary()? {
264             let params = input.arbitrary::<P>()?;
265             let result = input.arbitrary::<R>()?;
266             *store.data_mut() = Box::new((params.clone(), result.clone()));
267             log::trace!("passing in parameters {params:?}");
268             let actual = if declarations.options.guest_caller_async {
269                 store
270                     .run_concurrent(async |a| func.call_concurrent(a, params).await.unwrap().0)
271                     .await
272                     .unwrap()
273             } else {
274                 let result = func.call_async(&mut store, params).await.unwrap();
275                 func.post_return_async(&mut store).await.unwrap();
276                 result
277             };
278             log::trace!("got result {actual:?}");
279             assert_eq!(actual, result);
280         }
281 
282         Ok(())
283     })
284 }
285 
286 /// Generate and execute a `crate::generators::component_types::TestCase` using the specified `input` to create
287 /// arbitrary types and values.
288 pub fn dynamic_component_api_target(input: &mut arbitrary::Unstructured) -> arbitrary::Result<()> {
289     crate::init_fuzzing();
290 
291     let mut types = Vec::new();
292     let mut type_fuel = 500;
293 
294     for _ in 0..5 {
295         types.push(Type::generate(input, MAX_TYPE_DEPTH, &mut type_fuel)?);
296     }
297 
298     let case = TestCase::generate(&types, input)?;
299 
300     let mut store = store(input, (Vec::new(), None))?;
301     let engine = store.engine();
302     let wat = case.declarations().make_component();
303     let wat = wat.as_bytes();
304     log_wasm(wat);
305     let component = Component::new(&engine, wat).unwrap();
306     let mut linker = Linker::new(&engine);
307 
308     fn host_function(
309         mut cx: StoreContextMut<'_, (Vec<Val>, Option<Vec<Val>>)>,
310         params: &[Val],
311         results: &mut [Val],
312     ) -> Result<()> {
313         log::trace!("received params {params:?}");
314         let (expected_args, expected_results) = cx.data_mut();
315         assert_eq!(params.len(), expected_args.len());
316         for (expected, actual) in expected_args.iter().zip(params) {
317             assert_eq!(expected, actual);
318         }
319         results.clone_from_slice(&expected_results.take().unwrap());
320         log::trace!("returning results {results:?}");
321         Ok(())
322     }
323 
324     if case.options.host_async {
325         linker
326             .root()
327             .func_new_concurrent(IMPORT_FUNCTION, {
328                 move |cx: &Accessor<_, _>, _, params: &[Val], results: &mut [Val]| {
329                     Box::pin(async move {
330                         cx.with(|mut store| host_function(store.as_context_mut(), params, results))
331                     })
332                 }
333             })
334             .unwrap();
335     } else {
336         linker
337             .root()
338             .func_new(IMPORT_FUNCTION, {
339                 move |cx, _, params, results| host_function(cx, params, results)
340             })
341             .unwrap();
342     }
343 
344     block_on(async {
345         let instance = linker
346             .instantiate_async(&mut store, &component)
347             .await
348             .unwrap();
349         let func = instance.get_func(&mut store, EXPORT_FUNCTION).unwrap();
350         let ty = func.ty(&store);
351 
352         while input.arbitrary()? {
353             let params = ty
354                 .params()
355                 .map(|(_, ty)| arbitrary_val(&ty, input))
356                 .collect::<arbitrary::Result<Vec<_>>>()?;
357             let results = ty
358                 .results()
359                 .map(|ty| arbitrary_val(&ty, input))
360                 .collect::<arbitrary::Result<Vec<_>>>()?;
361 
362             *store.data_mut() = (params.clone(), Some(results.clone()));
363 
364             log::trace!("passing params {params:?}");
365             let mut actual = vec![Val::Bool(false); results.len()];
366             if case.options.guest_caller_async {
367                 store
368                     .run_concurrent(async |a| {
369                         func.call_concurrent(a, &params, &mut actual).await.unwrap();
370                     })
371                     .await
372                     .unwrap();
373             } else {
374                 func.call_async(&mut store, &params, &mut actual)
375                     .await
376                     .unwrap();
377                 func.post_return_async(&mut store).await.unwrap();
378             }
379             log::trace!("received results {actual:?}");
380             assert_eq!(actual, results);
381         }
382         Ok(())
383     })
384 }
385 
386 #[cfg(test)]
387 mod tests {
388     use super::*;
389     use crate::test::test_n_times;
390     use wasmtime_test_util::component_fuzz::{TestCase, Type};
391 
392     #[test]
393     fn dynamic_component_api_smoke_test() {
394         test_n_times(50, |(), u| super::dynamic_component_api_target(u));
395     }
396 
397     #[test]
398     fn static_api_smoke_test() {
399         test_n_times(10, |(), u| {
400             let mut case = TestCase::generate(&[], u)?;
401             case.params = vec![&Type::S32, &Type::Bool, &Type::String];
402             case.result = Some(&Type::String);
403 
404             let declarations = case.declarations();
405             static_api_test::<(i32, bool, String), (String,)>(u, &declarations)
406         });
407     }
408 }
409