wasmtime/runtime/externals/
global.rs1use crate::prelude::*;
2use crate::runtime::vm::{self, VMGlobalDefinition, VMGlobalKind, VMOpaqueContext};
3use crate::{
4 AnyRef, AsContext, AsContextMut, ExnRef, ExternRef, Func, GlobalType, HeapType, Mutability,
5 Ref, Unrooted, Val, ValType,
6 store::{AutoAssertNoGc, InstanceId, StoreId, StoreInstanceId, StoreOpaque},
7 trampoline::generate_global_export,
8};
9use core::ptr::NonNull;
10use wasmtime_environ::DefinedGlobalIndex;
11
12#[derive(Copy, Clone, Debug)]
25#[repr(C)] pub struct Global {
27 store: StoreId,
29 instance: u32,
32 kind: VMGlobalKind,
34}
35
36const _: () = {
39 #[repr(C)]
40 struct C(u64, u32, u32, u32);
41 assert!(core::mem::size_of::<C>() == core::mem::size_of::<Global>());
42 assert!(core::mem::align_of::<C>() == core::mem::align_of::<Global>());
43 assert!(core::mem::offset_of!(Global, store) == 0);
44};
45
46impl Global {
47 pub fn new(mut store: impl AsContextMut, ty: GlobalType, val: Val) -> Result<Global> {
99 Global::_new(store.as_context_mut().0, ty, val)
100 }
101
102 fn _new(store: &mut StoreOpaque, ty: GlobalType, val: Val) -> Result<Global> {
103 val.validate_rooted()?;
104 val.ensure_matches_ty(store, ty.content()).context(
105 "type mismatch: initial value provided does not match the type of this global",
106 )?;
107 generate_global_export(store, ty, val)
108 }
109
110 pub(crate) fn new_host(store: &StoreOpaque, index: DefinedGlobalIndex) -> Global {
111 Global {
112 store: store.id(),
113 instance: 0,
114 kind: VMGlobalKind::Host(index),
115 }
116 }
117
118 pub(crate) fn new_instance(
119 store: &StoreOpaque,
120 instance: InstanceId,
121 index: DefinedGlobalIndex,
122 ) -> Global {
123 Global {
124 store: store.id(),
125 instance: instance.as_u32(),
126 kind: VMGlobalKind::Instance(index),
127 }
128 }
129
130 pub fn ty(&self, store: impl AsContext) -> GlobalType {
136 self._ty(store.as_context().0)
137 }
138
139 pub(crate) fn _ty(&self, store: &StoreOpaque) -> GlobalType {
140 GlobalType::from_wasmtime_global(store.engine(), self.wasmtime_ty(store))
141 }
142
143 pub fn get(&self, store: impl AsContext) -> Val {
154 self._get(store.as_context().0)
155 }
156
157 pub fn get_numeric(&self, store: impl AsContext) -> Option<Val> {
169 self._get_numeric(store.as_context().0)
170 }
171
172 fn _get_numeric(&self, store: &StoreOpaque) -> Option<Val> {
173 unsafe {
174 let definition = self.definition(store).as_ref();
175 match self._ty(store).content() {
176 ValType::I32 => Some(Val::from(definition.get_i32())),
177 ValType::I64 => Some(Val::from(definition.get_i64())),
178 ValType::F32 => Some(Val::F32(definition.get_f32_bits())),
179 ValType::F64 => Some(Val::F64(definition.get_f64_bits())),
180 ValType::V128 => Some(Val::V128(definition.get_u128().into())),
181 ValType::Ref(_) => None,
182 }
183 }
184 }
185
186 pub(crate) fn _get(&self, store: &StoreOpaque) -> Val {
187 unsafe {
188 let definition = self.definition(store).as_ref();
189 match self._ty(store).content() {
190 ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64 | ValType::V128 => self
191 ._get_numeric(store)
192 .expect("numeric globals always have a numeric value"),
193 ValType::Ref(ref_ty) => {
194 let reference: Ref = match ref_ty.heap_type() {
195 HeapType::Func | HeapType::ConcreteFunc(_) => Ref::Func(
196 definition
197 .get_func_ref()
198 .map(|f| Func::from_vm_func_ref(store.id(), f)),
199 ),
200
201 HeapType::NoFunc => Ref::Func(None),
202
203 HeapType::Extern => definition
204 .as_gc_ref()
205 .map(|r| Unrooted::<ExternRef>::new(store, r))
206 .into(),
207
208 HeapType::NoCont | HeapType::ConcreteCont(_) | HeapType::Cont => {
209 unimplemented!()
211 }
212
213 HeapType::NoExtern => Ref::Extern(None),
214
215 HeapType::Exn => definition
216 .as_gc_ref()
217 .map(|r| Unrooted::<ExnRef>::new(store, r))
218 .into(),
219
220 HeapType::Any
221 | HeapType::Eq
222 | HeapType::I31
223 | HeapType::Struct
224 | HeapType::ConcreteStruct(_)
225 | HeapType::Array
226 | HeapType::ConcreteArray(_) => definition
227 .as_gc_ref()
228 .map(|r| Unrooted::<AnyRef>::new(store, r))
229 .into(),
230
231 HeapType::NoExn => Ref::Exn(None),
232
233 HeapType::None => Ref::Any(None),
234 };
235 debug_assert!(
236 ref_ty.is_nullable() || !reference.is_null(),
237 "if the type is non-nullable, we better have a non-null reference"
238 );
239 reference.into()
240 }
241 }
242 }
243 }
244
245 pub fn set(&self, mut store: impl AsContextMut, val: Val) -> Result<()> {
261 self._set(store.as_context_mut().0, val)
262 }
263
264 pub(crate) fn _set(&self, store: &mut StoreOpaque, val: Val) -> Result<()> {
265 let global_ty = self._ty(&store);
266 if global_ty.mutability() != Mutability::Var {
267 bail!("immutable global cannot be set");
268 }
269 val.validate_rooted()?;
270 val.ensure_matches_ty(&store, global_ty.content())
271 .context("type mismatch: attempt to set global to value of wrong type")?;
272
273 unsafe { self.set_unchecked(store, &val) }
275 }
276
277 pub(crate) unsafe fn set_unchecked(&self, store: &mut StoreOpaque, val: &Val) -> Result<()> {
285 let mut store = AutoAssertNoGc::new(store);
286 unsafe {
287 let definition = self.definition(&store).as_mut();
288 match val {
289 Val::I32(i) => definition.set_i32(*i),
290 Val::I64(i) => definition.set_i64(*i),
291 Val::F32(f) => definition.set_f32_bits(*f),
292 Val::F64(f) => definition.set_f64_bits(*f),
293 Val::V128(i) => definition.set_u128((*i).into()),
294 Val::FuncRef(f) => {
295 definition.set_func_ref(f.map(|f| f.vm_func_ref(&store)));
296 }
297 Val::ExternRef(e) => {
298 let new = match e {
299 None => None,
300 Some(e) => Some(e.try_gc_ref(&store)?.unchecked_copy()),
301 };
302 let new = new.as_ref();
303 definition.write_gc_ref(&mut store, new)?;
304 }
305 Val::AnyRef(a) => {
306 let new = match a {
307 None => None,
308 Some(a) => Some(a.try_gc_ref(&store)?.unchecked_copy()),
309 };
310 let new = new.as_ref();
311 definition.write_gc_ref(&mut store, new)?;
312 }
313 Val::ExnRef(e) => {
314 let new = match e {
315 None => None,
316 Some(e) => Some(e.try_gc_ref(&store)?.unchecked_copy()),
317 };
318 let new = new.as_ref();
319 definition.write_gc_ref(&mut store, new)?;
320 }
321 Val::ContRef(None) => {
322 definition.write_gc_ref(&mut store, None)?;
324 }
325 Val::ContRef(Some(_)) => {
326 return Err(crate::format_err!(
328 "setting non-null continuation references in globals not yet supported"
329 ));
330 }
331 }
332 }
333 Ok(())
334 }
335
336 #[cfg(feature = "gc")]
337 pub(crate) fn trace_root(&self, store: &mut StoreOpaque, gc_roots_list: &mut vm::GcRootsList) {
338 if let Some(ref_ty) = self._ty(store).content().as_ref() {
339 if !ref_ty.is_vmgcref_type_and_points_to_object() {
340 return;
341 }
342
343 if let Some(gc_ref) = unsafe { self.definition(store).as_mut().as_gc_ref_mut() } {
344 unsafe {
345 gc_roots_list.add_vmgcref_root(gc_ref.into(), "Wasm global");
346 }
347 }
348 }
349 }
350
351 pub(crate) fn from_host(store: StoreId, index: DefinedGlobalIndex) -> Global {
352 Global {
353 store,
354 instance: 0,
355 kind: VMGlobalKind::Host(index),
356 }
357 }
358
359 pub(crate) fn from_core(instance: StoreInstanceId, index: DefinedGlobalIndex) -> Global {
360 Global {
361 store: instance.store_id(),
362 instance: instance.instance().as_u32(),
363 kind: VMGlobalKind::Instance(index),
364 }
365 }
366
367 #[cfg(feature = "component-model")]
368 pub(crate) fn from_component_flags(
369 instance: crate::component::store::StoreComponentInstanceId,
370 index: wasmtime_environ::component::RuntimeComponentInstanceIndex,
371 ) -> Global {
372 Global {
373 store: instance.store_id(),
374 instance: instance.instance().as_u32(),
375 kind: VMGlobalKind::ComponentFlags(index),
376 }
377 }
378
379 pub(crate) fn wasmtime_ty<'a>(&self, store: &'a StoreOpaque) -> &'a wasmtime_environ::Global {
380 self.store.assert_belongs_to(store.id());
381 match self.kind {
382 VMGlobalKind::Instance(index) => {
383 let instance = InstanceId::from_u32(self.instance);
384 let module = store.instance(instance).env_module();
385 let index = module.global_index(index);
386 &module.globals[index]
387 }
388 VMGlobalKind::Host(index) => unsafe { &store.host_globals()[index].get().as_ref().ty },
389 #[cfg(feature = "component-model")]
390 VMGlobalKind::ComponentFlags(_) => {
391 const TY: wasmtime_environ::Global = wasmtime_environ::Global {
392 mutability: true,
393 wasm_ty: wasmtime_environ::WasmValType::I32,
394 };
395 &TY
396 }
397 }
398 }
399
400 pub(crate) fn vmimport(&self, store: &StoreOpaque) -> vm::VMGlobalImport {
401 let vmctx = match self.kind {
402 VMGlobalKind::Instance(_) => {
403 let instance = InstanceId::from_u32(self.instance);
404 Some(VMOpaqueContext::from_vmcontext(store.instance(instance).vmctx()).into())
405 }
406 VMGlobalKind::Host(_) => None,
407 #[cfg(feature = "component-model")]
408 VMGlobalKind::ComponentFlags(_) => {
409 let instance = crate::component::ComponentInstanceId::from_u32(self.instance);
410 Some(
411 VMOpaqueContext::from_vmcomponent(store.component_instance(instance).vmctx())
412 .into(),
413 )
414 }
415 };
416 vm::VMGlobalImport {
417 from: self.definition(store).into(),
418 vmctx,
419 kind: self.kind,
420 }
421 }
422
423 pub(crate) fn comes_from_same_store(&self, store: &StoreOpaque) -> bool {
424 store.id() == self.store
425 }
426
427 #[cfg(feature = "debug")]
432 pub fn debug_index_in_store(&self) -> u64 {
433 match self.kind {
434 VMGlobalKind::Instance(idx) => u64::from(self.instance) << 32 | u64::from(idx.as_u32()),
435 VMGlobalKind::Host(idx) => u64::from(u32::MAX) << 32 | u64::from(idx.as_u32()),
436 #[cfg(feature = "component-model")]
437 VMGlobalKind::ComponentFlags(idx) => {
438 u64::from(self.instance) << 32 | u64::from(idx.as_u32())
439 }
440 }
441 }
442
443 #[cfg(feature = "coredump")]
449 pub(crate) fn hash_key(&self, store: &StoreOpaque) -> impl core::hash::Hash + Eq + use<> {
450 self.definition(store).as_ptr().addr()
451 }
452
453 fn definition(&self, store: &StoreOpaque) -> NonNull<VMGlobalDefinition> {
454 self.store.assert_belongs_to(store.id());
455 match self.kind {
456 VMGlobalKind::Instance(index) => {
457 let instance = InstanceId::from_u32(self.instance);
458 store.instance(instance).global_ptr(index)
459 }
460 VMGlobalKind::Host(index) => unsafe {
461 NonNull::from(&mut store.host_globals()[index].get().as_mut().global)
462 },
463 #[cfg(feature = "component-model")]
464 VMGlobalKind::ComponentFlags(index) => {
465 let instance = crate::component::ComponentInstanceId::from_u32(self.instance);
466 store
467 .component_instance(instance)
468 .instance_flags(index)
469 .as_raw()
470 }
471 }
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use super::*;
478 use crate::{Instance, Module, Store};
479
480 #[test]
481 fn hash_key_is_stable_across_duplicate_store_data_entries() -> Result<()> {
482 let mut store = Store::<()>::default();
483 let module = Module::new(
484 store.engine(),
485 r#"
486 (module
487 (global (export "g") (mut i32) (i32.const 0))
488 )
489 "#,
490 )?;
491 let instance = Instance::new(&mut store, &module, &[])?;
492
493 let g1 = instance.get_global(&mut store, "g").unwrap();
497 let g2 = instance.get_global(&mut store, "g").unwrap();
498
499 assert_eq!(g1.get(&mut store).unwrap_i32(), 0);
501 assert_eq!(g2.get(&mut store).unwrap_i32(), 0);
502 g1.set(&mut store, Val::I32(42))?;
503 assert_eq!(g1.get(&mut store).unwrap_i32(), 42);
504 assert_eq!(g2.get(&mut store).unwrap_i32(), 42);
505
506 assert!(g1.hash_key(&store.as_context().0) == g2.hash_key(&store.as_context().0));
508
509 let instance2 = Instance::new(&mut store, &module, &[])?;
511 let g3 = instance2.get_global(&mut store, "g").unwrap();
512 assert!(g1.hash_key(&store.as_context().0) != g3.hash_key(&store.as_context().0));
513
514 Ok(())
515 }
516}