wasmtime/runtime/
instantiate.rs

1//! Define the `instantiate` function, which takes a byte array containing an
2//! encoded wasm module and returns a live wasm instance. Also, define
3//! `CompiledModule` to allow compiling and instantiating to be done as separate
4//! steps.
5
6use crate::prelude::*;
7use crate::runtime::vm::{CompiledModuleId, MmapVec};
8use crate::{code_memory::CodeMemory, profiling_agent::ProfilingAgent};
9use alloc::sync::Arc;
10use core::str;
11use wasmtime_environ::{
12    CompiledFunctionInfo, CompiledModuleInfo, DefinedFuncIndex, FuncIndex, FunctionLoc,
13    FunctionName, Metadata, Module, ModuleInternedTypeIndex, PrimaryMap, StackMapInformation,
14    WasmFunctionInfo,
15};
16
17/// A compiled wasm module, ready to be instantiated.
18pub struct CompiledModule {
19    module: Arc<Module>,
20    funcs: PrimaryMap<DefinedFuncIndex, CompiledFunctionInfo>,
21    wasm_to_array_trampolines: Vec<(ModuleInternedTypeIndex, FunctionLoc)>,
22    meta: Metadata,
23    code_memory: Arc<CodeMemory>,
24    #[cfg(feature = "debug-builtins")]
25    dbg_jit_registration: Option<crate::runtime::vm::GdbJitImageRegistration>,
26    /// A unique ID used to register this module with the engine.
27    unique_id: CompiledModuleId,
28    func_names: Vec<FunctionName>,
29}
30
31impl CompiledModule {
32    /// Creates `CompiledModule` directly from a precompiled artifact.
33    ///
34    /// The `code_memory` argument is expected to be the result of a previous
35    /// call to `ObjectBuilder::finish` above. This is an ELF image, at this
36    /// time, which contains all necessary information to create a
37    /// `CompiledModule` from a compilation.
38    ///
39    /// This method also takes `info`, an optionally-provided deserialization
40    /// of the artifacts' compilation metadata section. If this information is
41    /// not provided then the information will be
42    /// deserialized from the image of the compilation artifacts. Otherwise it
43    /// will be assumed to be what would otherwise happen if the section were
44    /// to be deserialized.
45    ///
46    /// The `profiler` argument here is used to inform JIT profiling runtimes
47    /// about new code that is loaded.
48    pub fn from_artifacts(
49        code_memory: Arc<CodeMemory>,
50        info: CompiledModuleInfo,
51        profiler: &dyn ProfilingAgent,
52    ) -> Result<Self> {
53        let mut ret = Self {
54            module: Arc::new(info.module),
55            funcs: info.funcs,
56            wasm_to_array_trampolines: info.wasm_to_array_trampolines,
57            #[cfg(feature = "debug-builtins")]
58            dbg_jit_registration: None,
59            code_memory,
60            meta: info.meta,
61            unique_id: CompiledModuleId::new(),
62            func_names: info.func_names,
63        };
64        ret.register_debug_and_profiling(profiler)?;
65
66        Ok(ret)
67    }
68
69    fn register_debug_and_profiling(&mut self, profiler: &dyn ProfilingAgent) -> Result<()> {
70        #[cfg(feature = "debug-builtins")]
71        if self.meta.native_debug_info_present {
72            let text = self.text();
73            let bytes = crate::debug::create_gdbjit_image(
74                self.mmap().to_vec(),
75                (text.as_ptr(), text.len()),
76            )
77            .context("failed to create jit image for gdb")?;
78            let reg = crate::runtime::vm::GdbJitImageRegistration::register(bytes);
79            self.dbg_jit_registration = Some(reg);
80        }
81        profiler.register_module(&self.code_memory.mmap()[..], &|addr| {
82            let (idx, _) = self.func_by_text_offset(addr)?;
83            let idx = self.module.func_index(idx);
84            let name = self.func_name(idx)?;
85            let mut demangled = String::new();
86            wasmtime_environ::demangle_function_name(&mut demangled, name).unwrap();
87            Some(demangled)
88        });
89        Ok(())
90    }
91
92    /// Get this module's unique ID. It is unique with respect to a
93    /// single allocator (which is ordinarily held on a Wasm engine).
94    pub fn unique_id(&self) -> CompiledModuleId {
95        self.unique_id
96    }
97
98    /// Returns the underlying memory which contains the compiled module's
99    /// image.
100    pub fn mmap(&self) -> &MmapVec {
101        self.code_memory.mmap()
102    }
103
104    /// Returns the underlying owned mmap of this compiled image.
105    pub fn code_memory(&self) -> &Arc<CodeMemory> {
106        &self.code_memory
107    }
108
109    /// Returns the text section of the ELF image for this compiled module.
110    ///
111    /// This memory should have the read/execute permissions.
112    #[inline]
113    pub fn text(&self) -> &[u8] {
114        self.code_memory.text()
115    }
116
117    /// Return a reference-counting pointer to a module.
118    pub fn module(&self) -> &Arc<Module> {
119        &self.module
120    }
121
122    /// Looks up the `name` section name for the function index `idx`, if one
123    /// was specified in the original wasm module.
124    pub fn func_name(&self, idx: FuncIndex) -> Option<&str> {
125        // Find entry for `idx`, if present.
126        let i = self.func_names.binary_search_by_key(&idx, |n| n.idx).ok()?;
127        let name = &self.func_names[i];
128
129        // Here we `unwrap` the `from_utf8` but this can theoretically be a
130        // `from_utf8_unchecked` if we really wanted since this section is
131        // guaranteed to only have valid utf-8 data. Until it's a problem it's
132        // probably best to double-check this though.
133        let data = self.code_memory().func_name_data();
134        Some(str::from_utf8(&data[name.offset as usize..][..name.len as usize]).unwrap())
135    }
136
137    /// Return a reference to a mutable module (if possible).
138    pub fn module_mut(&mut self) -> Option<&mut Module> {
139        Arc::get_mut(&mut self.module)
140    }
141
142    /// Returns an iterator over all functions defined within this module with
143    /// their index and their body in memory.
144    #[inline]
145    pub fn finished_functions(
146        &self,
147    ) -> impl ExactSizeIterator<Item = (DefinedFuncIndex, &[u8])> + '_ {
148        self.funcs
149            .iter()
150            .map(move |(i, _)| (i, self.finished_function(i)))
151    }
152
153    /// Returns the body of the function that `index` points to.
154    #[inline]
155    pub fn finished_function(&self, index: DefinedFuncIndex) -> &[u8] {
156        let loc = self.funcs[index].wasm_func_loc;
157        &self.text()[loc.start as usize..][..loc.length as usize]
158    }
159
160    /// Get the array-to-Wasm trampoline for the function `index` points to.
161    ///
162    /// If the function `index` points to does not escape, then `None` is
163    /// returned.
164    ///
165    /// These trampolines are used for array callers (e.g. `Func::new`)
166    /// calling Wasm callees.
167    pub fn array_to_wasm_trampoline(&self, index: DefinedFuncIndex) -> Option<&[u8]> {
168        let loc = self.funcs[index].array_to_wasm_trampoline?;
169        Some(&self.text()[loc.start as usize..][..loc.length as usize])
170    }
171
172    /// Get the Wasm-to-array trampoline for the given signature.
173    ///
174    /// These trampolines are used for filling in
175    /// `VMFuncRef::wasm_call` for `Func::wrap`-style host funcrefs
176    /// that don't have access to a compiler when created.
177    pub fn wasm_to_array_trampoline(&self, signature: ModuleInternedTypeIndex) -> &[u8] {
178        let idx = match self
179            .wasm_to_array_trampolines
180            .binary_search_by_key(&signature, |entry| entry.0)
181        {
182            Ok(idx) => idx,
183            Err(_) => panic!("missing trampoline for {signature:?}"),
184        };
185
186        let (_, loc) = self.wasm_to_array_trampolines[idx];
187        &self.text()[loc.start as usize..][..loc.length as usize]
188    }
189
190    /// Returns the stack map information for all functions defined in this
191    /// module.
192    ///
193    /// The iterator returned iterates over the span of the compiled function in
194    /// memory with the stack maps associated with those bytes.
195    pub fn stack_maps(&self) -> impl Iterator<Item = (&[u8], &[StackMapInformation])> {
196        self.finished_functions().map(|(_, f)| f).zip(
197            self.funcs
198                .values()
199                .map(|f| &f.wasm_func_info.stack_maps[..]),
200        )
201    }
202
203    /// Lookups a defined function by a program counter value.
204    ///
205    /// Returns the defined function index and the relative address of
206    /// `text_offset` within the function itself.
207    pub fn func_by_text_offset(&self, text_offset: usize) -> Option<(DefinedFuncIndex, u32)> {
208        let text_offset = u32::try_from(text_offset).unwrap();
209
210        let index = match self.funcs.binary_search_values_by_key(&text_offset, |e| {
211            debug_assert!(e.wasm_func_loc.length > 0);
212            // Return the inclusive "end" of the function
213            e.wasm_func_loc.start + e.wasm_func_loc.length - 1
214        }) {
215            Ok(k) => {
216                // Exact match, pc is at the end of this function
217                k
218            }
219            Err(k) => {
220                // Not an exact match, k is where `pc` would be "inserted"
221                // Since we key based on the end, function `k` might contain `pc`,
222                // so we'll validate on the range check below
223                k
224            }
225        };
226
227        let CompiledFunctionInfo { wasm_func_loc, .. } = self.funcs.get(index)?;
228        let start = wasm_func_loc.start;
229        let end = wasm_func_loc.start + wasm_func_loc.length;
230
231        if text_offset < start || end < text_offset {
232            return None;
233        }
234
235        Some((index, text_offset - wasm_func_loc.start))
236    }
237
238    /// Gets the function location information for a given function index.
239    pub fn func_loc(&self, index: DefinedFuncIndex) -> &FunctionLoc {
240        &self
241            .funcs
242            .get(index)
243            .expect("defined function should be present")
244            .wasm_func_loc
245    }
246
247    /// Gets the function information for a given function index.
248    pub fn wasm_func_info(&self, index: DefinedFuncIndex) -> &WasmFunctionInfo {
249        &self
250            .funcs
251            .get(index)
252            .expect("defined function should be present")
253            .wasm_func_info
254    }
255
256    /// Creates a new symbolication context which can be used to further
257    /// symbolicate stack traces.
258    ///
259    /// Basically this makes a thing which parses debuginfo and can tell you
260    /// what filename and line number a wasm pc comes from.
261    #[cfg(feature = "addr2line")]
262    pub fn symbolize_context(&self) -> Result<Option<SymbolizeContext<'_>>> {
263        use gimli::EndianSlice;
264        if !self.meta.has_wasm_debuginfo {
265            return Ok(None);
266        }
267        let dwarf = gimli::Dwarf::load(|id| -> Result<_> {
268            // Lookup the `id` in the `dwarf` array prepared for this module
269            // during module serialization where it's sorted by the `id` key. If
270            // found this is a range within the general module's concatenated
271            // dwarf section which is extracted here, otherwise it's just an
272            // empty list to represent that it's not present.
273            let data = self
274                .meta
275                .dwarf
276                .binary_search_by_key(&(id as u8), |(id, _)| *id)
277                .map(|i| {
278                    let (_, range) = &self.meta.dwarf[i];
279                    &self.code_memory().dwarf()[range.start as usize..range.end as usize]
280                })
281                .unwrap_or(&[]);
282            Ok(EndianSlice::new(data, gimli::LittleEndian))
283        })?;
284        let cx = addr2line::Context::from_dwarf(dwarf)
285            .context("failed to create addr2line dwarf mapping context")?;
286        Ok(Some(SymbolizeContext {
287            inner: cx,
288            code_section_offset: self.meta.code_section_offset,
289        }))
290    }
291
292    /// Returns whether the original wasm module had unparsed debug information
293    /// based on the tunables configuration.
294    pub fn has_unparsed_debuginfo(&self) -> bool {
295        self.meta.has_unparsed_debuginfo
296    }
297
298    /// Indicates whether this module came with n address map such that lookups
299    /// via `wasmtime_environ::lookup_file_pos` will succeed.
300    ///
301    /// If this function returns `false` then `lookup_file_pos` will always
302    /// return `None`.
303    pub fn has_address_map(&self) -> bool {
304        !self.code_memory.address_map_data().is_empty()
305    }
306}
307
308#[cfg(feature = "addr2line")]
309type Addr2LineContext<'a> = addr2line::Context<gimli::EndianSlice<'a, gimli::LittleEndian>>;
310
311/// A context which contains dwarf debug information to translate program
312/// counters back to filenames and line numbers.
313#[cfg(feature = "addr2line")]
314pub struct SymbolizeContext<'a> {
315    inner: Addr2LineContext<'a>,
316    code_section_offset: u64,
317}
318
319#[cfg(feature = "addr2line")]
320impl<'a> SymbolizeContext<'a> {
321    /// Returns access to the [`addr2line::Context`] which can be used to query
322    /// frame information with.
323    pub fn addr2line(&self) -> &Addr2LineContext<'a> {
324        &self.inner
325    }
326
327    /// Returns the offset of the code section in the original wasm file, used
328    /// to calculate lookup values into the DWARF.
329    pub fn code_section_offset(&self) -> u64 {
330        self.code_section_offset
331    }
332}