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