wasmtime/runtime/code.rs
1use crate::{code_memory::CodeMemory, type_registry::TypeCollection};
2use alloc::sync::Arc;
3#[cfg(feature = "component-model")]
4use wasmtime_environ::component::ComponentTypes;
5use wasmtime_environ::ModuleTypes;
6
7/// Metadata in Wasmtime about a loaded compiled artifact in memory which is
8/// ready to execute.
9///
10/// This structure is used in both `Module` and `Component`. For components it's
11/// notably shared amongst the core wasm modules within a component and the
12/// component itself. For core wasm modules this is uniquely owned within a
13/// `Module`.
14pub struct CodeObject {
15 /// Actual underlying mmap which is executable and contains other compiled
16 /// information.
17 ///
18 /// Note the `Arc` here is used to share this with `CompiledModule` and the
19 /// global module registry of traps. While probably not strictly necessary
20 /// and could be avoided with some refactorings is a hopefully a relatively
21 /// minor `Arc` for now.
22 mmap: Arc<CodeMemory>,
23
24 /// Registered shared signature for the loaded object.
25 ///
26 /// Note that this type has a significant destructor which unregisters
27 /// signatures within the `Engine` it was originally tied to, and this ends
28 /// up corresponding to the lifetime of a `Component` or `Module`.
29 signatures: TypeCollection,
30
31 /// Type information for the loaded object.
32 ///
33 /// This is either a `ModuleTypes` or a `ComponentTypes` depending on the
34 /// top-level creator of this code.
35 types: Types,
36}
37
38impl CodeObject {
39 pub fn new(mmap: Arc<CodeMemory>, signatures: TypeCollection, types: Types) -> CodeObject {
40 // The corresponding unregister for this is below in `Drop for
41 // CodeObject`.
42 crate::module::register_code(&mmap);
43
44 CodeObject {
45 mmap,
46 signatures,
47 types,
48 }
49 }
50
51 pub fn code_memory(&self) -> &Arc<CodeMemory> {
52 &self.mmap
53 }
54
55 #[cfg(feature = "component-model")]
56 pub fn types(&self) -> &Types {
57 &self.types
58 }
59
60 pub fn module_types(&self) -> &ModuleTypes {
61 self.types.module_types()
62 }
63
64 pub fn signatures(&self) -> &TypeCollection {
65 &self.signatures
66 }
67}
68
69impl Drop for CodeObject {
70 fn drop(&mut self) {
71 crate::module::unregister_code(&self.mmap);
72 }
73}
74
75pub enum Types {
76 Module(ModuleTypes),
77 #[cfg(feature = "component-model")]
78 Component(Arc<ComponentTypes>),
79}
80
81impl Types {
82 fn module_types(&self) -> &ModuleTypes {
83 match self {
84 Types::Module(m) => m,
85 #[cfg(feature = "component-model")]
86 Types::Component(c) => c.module_types(),
87 }
88 }
89}
90
91impl From<ModuleTypes> for Types {
92 fn from(types: ModuleTypes) -> Types {
93 Types::Module(types)
94 }
95}
96
97#[cfg(feature = "component-model")]
98impl From<Arc<ComponentTypes>> for Types {
99 fn from(types: Arc<ComponentTypes>) -> Types {
100 Types::Component(types)
101 }
102}