1 //! Evaluating const expressions.
2 
3 use crate::runtime::vm::{Instance, VMGcRef, ValRaw, I31};
4 use crate::store::AutoAssertNoGc;
5 use crate::{
6     prelude::*, ArrayRef, ArrayRefPre, ArrayType, StructRef, StructRefPre, StructType, Val,
7 };
8 use smallvec::SmallVec;
9 use wasmtime_environ::{
10     ConstExpr, ConstOp, FuncIndex, GlobalIndex, ModuleInternedTypeIndex, WasmCompositeType,
11     WasmSubType,
12 };
13 
14 /// An interpreter for const expressions.
15 ///
16 /// This can be reused across many const expression evaluations to reuse
17 /// allocated resources, if any.
18 #[derive(Default)]
19 pub struct ConstExprEvaluator {
20     stack: SmallVec<[ValRaw; 2]>,
21 }
22 
23 /// The context within which a particular const expression is evaluated.
24 pub struct ConstEvalContext<'a> {
25     pub(crate) instance: &'a mut Instance,
26 }
27 
28 impl<'a> ConstEvalContext<'a> {
29     /// Create a new context.
30     pub fn new(instance: &'a mut Instance) -> Self {
31         Self { instance }
32     }
33 
34     fn global_get(&mut self, store: &mut AutoAssertNoGc<'_>, index: GlobalIndex) -> Result<ValRaw> {
35         unsafe {
36             let global = self
37                 .instance
38                 .defined_or_imported_global_ptr(index)
39                 .as_ref()
40                 .unwrap();
41             let mut gc_store = store.unwrap_gc_store_mut();
42             Ok(global.to_val_raw(
43                 &mut gc_store,
44                 self.instance.env_module().globals[index].wasm_ty,
45             ))
46         }
47     }
48 
49     fn ref_func(&mut self, index: FuncIndex) -> Result<ValRaw> {
50         Ok(ValRaw::funcref(
51             self.instance.get_func_ref(index).unwrap().cast(),
52         ))
53     }
54 
55     #[cfg(feature = "gc")]
56     fn struct_fields_len(&self, struct_type_index: ModuleInternedTypeIndex) -> usize {
57         let module = self
58             .instance
59             .runtime_module()
60             .expect("should never be allocating a struct type defined in a dummy module");
61 
62         let struct_ty = match &module.types()[struct_type_index].composite_type {
63             WasmCompositeType::Struct(s) => s,
64             _ => unreachable!(),
65         };
66 
67         struct_ty.fields.len()
68     }
69 
70     /// Safety: field values must be of the correct types.
71     #[cfg(feature = "gc")]
72     unsafe fn struct_new(
73         &mut self,
74         store: &mut AutoAssertNoGc<'_>,
75         struct_type_index: ModuleInternedTypeIndex,
76         fields: &[ValRaw],
77     ) -> Result<ValRaw> {
78         let module = self
79             .instance
80             .runtime_module()
81             .expect("should never be allocating a struct type defined in a dummy module");
82         let shared_ty = module
83             .signatures()
84             .shared_type(struct_type_index)
85             .expect("should have an engine type for module type");
86 
87         let struct_ty = StructType::from_shared_type_index(store.engine(), shared_ty);
88         let fields = fields
89             .iter()
90             .zip(struct_ty.fields())
91             .map(|(raw, ty)| {
92                 let ty = ty.element_type().unpack();
93                 Val::_from_raw(store, *raw, ty)
94             })
95             .collect::<Vec<_>>();
96 
97         let allocator = StructRefPre::_new(store, struct_ty);
98         let struct_ref = StructRef::_new(store, &allocator, &fields)?;
99         let raw = struct_ref.to_anyref()._to_raw(store)?;
100         Ok(ValRaw::anyref(raw))
101     }
102 
103     #[cfg(feature = "gc")]
104     fn struct_new_default(
105         &mut self,
106         store: &mut AutoAssertNoGc<'_>,
107         struct_type_index: ModuleInternedTypeIndex,
108     ) -> Result<ValRaw> {
109         let module = self
110             .instance
111             .runtime_module()
112             .expect("should never be allocating a struct type defined in a dummy module");
113 
114         let shared_ty = module
115             .signatures()
116             .shared_type(struct_type_index)
117             .expect("should have an engine type for module type");
118 
119         let borrowed = module
120             .engine()
121             .signatures()
122             .borrow(shared_ty)
123             .expect("should have a registered type for struct");
124         let WasmSubType {
125             composite_type: WasmCompositeType::Struct(struct_ty),
126             ..
127         } = &*borrowed
128         else {
129             unreachable!("registered type should be a struct");
130         };
131 
132         let fields = struct_ty
133             .fields
134             .iter()
135             .map(|ty| match &ty.element_type {
136                 wasmtime_environ::WasmStorageType::I8 | wasmtime_environ::WasmStorageType::I16 => {
137                     ValRaw::i32(0)
138                 }
139                 wasmtime_environ::WasmStorageType::Val(v) => match v {
140                     wasmtime_environ::WasmValType::I32 => ValRaw::i32(0),
141                     wasmtime_environ::WasmValType::I64 => ValRaw::i64(0),
142                     wasmtime_environ::WasmValType::F32 => ValRaw::f32(0.0f32.to_bits()),
143                     wasmtime_environ::WasmValType::F64 => ValRaw::f64(0.0f64.to_bits()),
144                     wasmtime_environ::WasmValType::V128 => ValRaw::v128(0),
145                     wasmtime_environ::WasmValType::Ref(r) => {
146                         assert!(r.nullable);
147                         ValRaw::null()
148                     }
149                 },
150             })
151             .collect::<SmallVec<[_; 8]>>();
152 
153         unsafe { self.struct_new(store, struct_type_index, &fields) }
154     }
155 }
156 
157 impl ConstExprEvaluator {
158     /// Evaluate the given const expression in the given context.
159     ///
160     /// # Unsafety
161     ///
162     /// The given const expression must be valid within the given context,
163     /// e.g. the const expression must be well-typed and the context must return
164     /// global values of the expected types. This evaluator operates directly on
165     /// untyped `ValRaw`s and does not and cannot check that its operands are of
166     /// the correct type.
167     pub unsafe fn eval(
168         &mut self,
169         context: &mut ConstEvalContext<'_>,
170         expr: &ConstExpr,
171     ) -> Result<ValRaw> {
172         self.stack.clear();
173 
174         let mut store = (*context.instance.store()).store_opaque_mut();
175 
176         // Ensure that we don't permanently root any GC references we allocate
177         // during const evaluation, keeping them alive for the duration of the
178         // store's lifetime.
179         #[cfg(feature = "gc")]
180         let mut store = crate::OpaqueRootScope::new(&mut store);
181 
182         // We cannot allow GC during const evaluation because the stack of
183         // `ValRaw`s are not rooted. If we had a GC reference on our stack, and
184         // then performed a collection, that on-stack reference's object could
185         // be reclaimed or relocated by the collector, and then when we use the
186         // reference again we would basically get a use-after-free bug.
187         let mut store = AutoAssertNoGc::new(&mut store);
188 
189         for op in expr.ops() {
190             match op {
191                 ConstOp::I32Const(i) => self.stack.push(ValRaw::i32(*i)),
192                 ConstOp::I64Const(i) => self.stack.push(ValRaw::i64(*i)),
193                 ConstOp::F32Const(f) => self.stack.push(ValRaw::f32(*f)),
194                 ConstOp::F64Const(f) => self.stack.push(ValRaw::f64(*f)),
195                 ConstOp::V128Const(v) => self.stack.push(ValRaw::v128(*v)),
196                 ConstOp::GlobalGet(g) => self.stack.push(context.global_get(&mut store, *g)?),
197                 ConstOp::RefNull => self.stack.push(ValRaw::null()),
198                 ConstOp::RefFunc(f) => self.stack.push(context.ref_func(*f)?),
199                 ConstOp::RefI31 => {
200                     let i = self.pop()?.get_i32();
201                     let i31 = I31::wrapping_i32(i);
202                     let raw = VMGcRef::from_i31(i31).as_raw_u32();
203                     self.stack.push(ValRaw::anyref(raw));
204                 }
205                 ConstOp::I32Add => {
206                     let b = self.pop()?.get_i32();
207                     let a = self.pop()?.get_i32();
208                     self.stack.push(ValRaw::i32(a.wrapping_add(b)));
209                 }
210                 ConstOp::I32Sub => {
211                     let b = self.pop()?.get_i32();
212                     let a = self.pop()?.get_i32();
213                     self.stack.push(ValRaw::i32(a.wrapping_sub(b)));
214                 }
215                 ConstOp::I32Mul => {
216                     let b = self.pop()?.get_i32();
217                     let a = self.pop()?.get_i32();
218                     self.stack.push(ValRaw::i32(a.wrapping_mul(b)));
219                 }
220                 ConstOp::I64Add => {
221                     let b = self.pop()?.get_i64();
222                     let a = self.pop()?.get_i64();
223                     self.stack.push(ValRaw::i64(a.wrapping_add(b)));
224                 }
225                 ConstOp::I64Sub => {
226                     let b = self.pop()?.get_i64();
227                     let a = self.pop()?.get_i64();
228                     self.stack.push(ValRaw::i64(a.wrapping_sub(b)));
229                 }
230                 ConstOp::I64Mul => {
231                     let b = self.pop()?.get_i64();
232                     let a = self.pop()?.get_i64();
233                     self.stack.push(ValRaw::i64(a.wrapping_mul(b)));
234                 }
235 
236                 #[cfg(not(feature = "gc"))]
237                 ConstOp::StructNew { .. }
238                 | ConstOp::StructNewDefault { .. }
239                 | ConstOp::ArrayNew { .. }
240                 | ConstOp::ArrayNewDefault { .. }
241                 | ConstOp::ArrayNewFixed { .. } => {
242                     bail!(
243                         "const expr evaluation error: struct operations are not \
244                          supported without the `gc` feature"
245                     )
246                 }
247 
248                 #[cfg(feature = "gc")]
249                 ConstOp::StructNew { struct_type_index } => {
250                     let interned_type_index =
251                         context.instance.env_module().types[*struct_type_index];
252                     let len = context.struct_fields_len(interned_type_index);
253 
254                     if self.stack.len() < len {
255                         bail!(
256                             "const expr evaluation error: expected at least {len} values on the stack, found {}",
257                             self.stack.len()
258                         )
259                     }
260 
261                     let start = self.stack.len() - len;
262                     let s = context.struct_new(
263                         &mut store,
264                         interned_type_index,
265                         &self.stack[start..],
266                     )?;
267                     self.stack.truncate(start);
268                     self.stack.push(s);
269                 }
270 
271                 #[cfg(feature = "gc")]
272                 ConstOp::StructNewDefault { struct_type_index } => {
273                     let interned_type_index =
274                         context.instance.env_module().types[*struct_type_index];
275                     self.stack
276                         .push(context.struct_new_default(&mut store, interned_type_index)?);
277                 }
278 
279                 #[cfg(feature = "gc")]
280                 ConstOp::ArrayNew { array_type_index } => {
281                     let interned_type_index =
282                         context.instance.env_module().types[*array_type_index];
283                     let module = context.instance.runtime_module().expect(
284                         "should never be allocating a struct type defined in a dummy module",
285                     );
286                     let shared_ty = module
287                         .signatures()
288                         .shared_type(interned_type_index)
289                         .expect("should have an engine type for module type");
290                     let ty = ArrayType::from_shared_type_index(store.engine(), shared_ty);
291 
292                     #[allow(clippy::cast_sign_loss)]
293                     let len = self.pop()?.get_i32() as u32;
294 
295                     let elem = Val::_from_raw(&mut store, self.pop()?, ty.element_type().unpack());
296 
297                     let pre = ArrayRefPre::_new(&mut store, ty);
298                     let array = ArrayRef::_new(&mut store, &pre, &elem, len)?;
299 
300                     self.stack
301                         .push(ValRaw::anyref(array.to_anyref()._to_raw(&mut store)?));
302                 }
303 
304                 #[cfg(feature = "gc")]
305                 ConstOp::ArrayNewDefault { array_type_index } => {
306                     let interned_type_index =
307                         context.instance.env_module().types[*array_type_index];
308                     let module = context.instance.runtime_module().expect(
309                         "should never be allocating a struct type defined in a dummy module",
310                     );
311                     let shared_ty = module
312                         .signatures()
313                         .shared_type(interned_type_index)
314                         .expect("should have an engine type for module type");
315                     let ty = ArrayType::from_shared_type_index(store.engine(), shared_ty);
316 
317                     #[allow(clippy::cast_sign_loss)]
318                     let len = self.pop()?.get_i32() as u32;
319 
320                     let elem = Val::default_for_ty(ty.element_type().unpack())
321                         .expect("type should have a default value");
322 
323                     let pre = ArrayRefPre::_new(&mut store, ty);
324                     let array = ArrayRef::_new(&mut store, &pre, &elem, len)?;
325 
326                     self.stack
327                         .push(ValRaw::anyref(array.to_anyref()._to_raw(&mut store)?));
328                 }
329 
330                 #[cfg(feature = "gc")]
331                 ConstOp::ArrayNewFixed {
332                     array_type_index,
333                     array_size,
334                 } => {
335                     let interned_type_index =
336                         context.instance.env_module().types[*array_type_index];
337                     let module = context.instance.runtime_module().expect(
338                         "should never be allocating a struct type defined in a dummy module",
339                     );
340                     let shared_ty = module
341                         .signatures()
342                         .shared_type(interned_type_index)
343                         .expect("should have an engine type for module type");
344                     let ty = ArrayType::from_shared_type_index(store.engine(), shared_ty);
345 
346                     let array_size = usize::try_from(*array_size).unwrap();
347                     if self.stack.len() < array_size {
348                         bail!(
349                             "const expr evaluation error: expected at least {array_size} values on the stack, found {}",
350                             self.stack.len()
351                         )
352                     }
353 
354                     let start = self.stack.len() - array_size;
355 
356                     let elem_ty = ty.element_type();
357                     let elem_ty = elem_ty.unpack();
358 
359                     let elems = self
360                         .stack
361                         .drain(start..)
362                         .map(|raw| Val::_from_raw(&mut store, raw, elem_ty))
363                         .collect::<SmallVec<[_; 8]>>();
364 
365                     let pre = ArrayRefPre::_new(&mut store, ty);
366                     let array = ArrayRef::_new_fixed(&mut store, &pre, &elems)?;
367 
368                     self.stack
369                         .push(ValRaw::anyref(array.to_anyref()._to_raw(&mut store)?));
370                 }
371             }
372         }
373 
374         if self.stack.len() == 1 {
375             Ok(self.stack[0])
376         } else {
377             bail!(
378                 "const expr evaluation error: expected 1 resulting value, found {}",
379                 self.stack.len()
380             )
381         }
382     }
383 
384     fn pop(&mut self) -> Result<ValRaw> {
385         self.stack.pop().ok_or_else(|| {
386             anyhow!(
387                 "const expr evaluation error: attempted to pop from an empty \
388                  evaluation stack"
389             )
390         })
391     }
392 }
393