Skip to main content

wasmtime/runtime/
coredump.rs

1use crate::hash_map::HashMap;
2use crate::prelude::*;
3use crate::{
4    AsContextMut, FrameInfo, Global, HeapTopType, Instance, Memory, Module, StoreContextMut, Val,
5    ValType, WasmBacktrace, store::StoreOpaque,
6};
7use std::fmt;
8
9/// Representation of a core dump of a WebAssembly module
10///
11/// When the Config::coredump_on_trap option is enabled this structure is
12/// attached to the [`Error`](crate::Error) returned from many Wasmtime functions
13/// that execute WebAssembly such as [`Instance::new`] or [`Func::call`]. This
14/// can be acquired with the [`Error::downcast`](crate::Error::downcast) family
15/// of methods to programmatically inspect the coredump. Otherwise since it's
16/// part of the error returned this will get printed along with the rest of the
17/// error when the error is logged.
18///
19/// Note that some state, such as Wasm locals or values on the operand stack,
20/// may be optimized away by the compiler or otherwise not recovered in the
21/// coredump.
22///
23/// Capturing of wasm coredumps can be configured through the
24/// [`Config::coredump_on_trap`][crate::Config::coredump_on_trap] method.
25///
26/// For more information about errors in wasmtime see the documentation of the
27/// [`Trap`][crate::Trap] type.
28///
29/// [`Func::call`]: crate::Func::call
30/// [`Instance::new`]: crate::Instance::new
31pub struct WasmCoreDump {
32    modules: Vec<Module>,
33    instances: Vec<Instance>,
34    memories: Vec<Memory>,
35    globals: Vec<Global>,
36    backtrace: WasmBacktrace,
37}
38
39impl WasmCoreDump {
40    pub(crate) fn new(store: &mut StoreOpaque, backtrace: WasmBacktrace) -> WasmCoreDump {
41        let modules = store
42            .modules()
43            .all_modules()
44            .map(|(_, m)| m.clone())
45            .collect::<Vec<_>>();
46        let instances: Vec<Instance> = store.all_instances().collect();
47        let store_memories: Vec<Memory> =
48            store.all_memories().filter_map(|m| m.unshared()).collect();
49
50        let mut store_globals: Vec<Global> = vec![];
51        store.for_each_global(|_store, global| store_globals.push(global));
52
53        WasmCoreDump {
54            modules,
55            instances,
56            memories: store_memories,
57            globals: store_globals,
58            backtrace,
59        }
60    }
61
62    /// The stack frames for this core dump.
63    ///
64    /// Frames appear in callee to caller order, that is youngest to oldest
65    /// frames.
66    pub fn frames(&self) -> &[FrameInfo] {
67        self.backtrace.frames()
68    }
69
70    /// All modules instantiated inside the store when the core dump was
71    /// created.
72    pub fn modules(&self) -> &[Module] {
73        self.modules.as_ref()
74    }
75
76    /// All instances within the store when the core dump was created.
77    pub fn instances(&self) -> &[Instance] {
78        self.instances.as_ref()
79    }
80
81    /// All globals, instance- or host-defined, within the store when the core
82    /// dump was created.
83    pub fn globals(&self) -> &[Global] {
84        self.globals.as_ref()
85    }
86
87    /// All memories, instance- or host-defined, within the store when the core
88    /// dump was created.
89    pub fn memories(&self) -> &[Memory] {
90        self.memories.as_ref()
91    }
92
93    /// Serialize this core dump into [the standard core dump binary
94    /// format][spec].
95    ///
96    /// The `name` parameter may be a file path, URL, or arbitrary name for the
97    /// "main" Wasm service or executable that was running in this store.
98    ///
99    /// Once serialized, you can write this core dump to disk, send it over the
100    /// network, or pass it to other debugging tools that consume Wasm core
101    /// dumps.
102    ///
103    /// [spec]: https://github.com/WebAssembly/tool-conventions/blob/main/Coredump.md
104    pub fn serialize(&self, mut store: impl AsContextMut, name: &str) -> Vec<u8> {
105        let store = store.as_context_mut();
106        self._serialize(store, name)
107    }
108
109    fn _serialize<T: 'static>(&self, mut store: StoreContextMut<'_, T>, name: &str) -> Vec<u8> {
110        let mut core_dump = wasm_encoder::Module::new();
111
112        core_dump.section(&wasm_encoder::CoreDumpSection::new(name));
113
114        // A map from each memory to its index in the core dump's memories
115        // section.
116        let mut memory_to_idx = HashMap::new();
117
118        let mut data = wasm_encoder::DataSection::new();
119
120        {
121            let mut memories = wasm_encoder::MemorySection::new();
122            for mem in self.memories() {
123                let memory_idx = memories.len();
124                memory_to_idx.insert(mem.hash_key(&store.0), memory_idx);
125                let ty = mem.ty(&store);
126                memories.memory(wasm_encoder::MemoryType {
127                    minimum: mem.size(&store),
128                    maximum: ty.maximum(),
129                    memory64: ty.is_64(),
130                    shared: ty.is_shared(),
131                    page_size_log2: match ty.page_size_log2() {
132                        16 => None,
133                        n => Some(n.into()),
134                    },
135                });
136
137                // Attach the memory data, balancing number of data segments and
138                // binary size. We don't want to attach the whole memory in one
139                // big segment, since it likely contains a bunch of large runs
140                // of zeroes. But we can't encode the data without any potential
141                // runs of zeroes (i.e. including only non-zero data in our
142                // segments) because we can run up against the implementation
143                // limits for number of segments in a Wasm module this way. So
144                // to balance these conflicting desires, we break the memory up
145                // into reasonably-sized chunks and then trim runs of zeroes
146                // from the start and end of each chunk.
147                const CHUNK_SIZE: usize = 4096;
148                for (i, chunk) in mem.data(&store).chunks(CHUNK_SIZE).enumerate() {
149                    if let Some(start) = chunk.iter().position(|byte| *byte != 0) {
150                        let end = chunk.iter().rposition(|byte| *byte != 0).unwrap() + 1;
151                        let offset = i * CHUNK_SIZE + start;
152                        let offset = if ty.is_64() {
153                            let offset = u64::try_from(offset).unwrap();
154                            wasm_encoder::ConstExpr::i64_const(offset as i64)
155                        } else {
156                            let offset = u32::try_from(offset).unwrap();
157                            wasm_encoder::ConstExpr::i32_const(offset as i32)
158                        };
159                        data.active(memory_idx, &offset, chunk[start..end].iter().copied());
160                    }
161                }
162            }
163            core_dump.section(&memories);
164        }
165
166        // A map from each global to its index in the core dump's globals
167        // section.
168        let mut global_to_idx = HashMap::new();
169
170        {
171            let mut globals = wasm_encoder::GlobalSection::new();
172            for g in self.globals() {
173                global_to_idx.insert(g.hash_key(&store.0), globals.len());
174                let ty = g.ty(&store);
175                let mutable = matches!(ty.mutability(), crate::Mutability::Var);
176                let val_type = match ty.content() {
177                    ValType::I32 => wasm_encoder::ValType::I32,
178                    ValType::I64 => wasm_encoder::ValType::I64,
179                    ValType::F32 => wasm_encoder::ValType::F32,
180                    ValType::F64 => wasm_encoder::ValType::F64,
181                    ValType::V128 => wasm_encoder::ValType::V128,
182
183                    // We encode all references as null in the core dump, so
184                    // choose the common super type of all the actual function
185                    // reference types. This lets us avoid needing to figure out
186                    // what a concrete type reference's index is in the local
187                    // core dump index space.
188                    ValType::Ref(r) => match r.heap_type().top() {
189                        HeapTopType::Extern => wasm_encoder::ValType::EXTERNREF,
190                        HeapTopType::Func => wasm_encoder::ValType::FUNCREF,
191                        HeapTopType::Any => {
192                            wasm_encoder::ValType::Ref(wasm_encoder::RefType::ANYREF)
193                        }
194                        HeapTopType::Exn => {
195                            wasm_encoder::ValType::Ref(wasm_encoder::RefType::EXNREF)
196                        }
197                        HeapTopType::Cont => {
198                            wasm_encoder::ValType::Ref(wasm_encoder::RefType::new_abstract(
199                                wasm_encoder::AbstractHeapType::Cont,
200                                true,
201                                false,
202                            ))
203                        }
204                    },
205                };
206                let init = match g.get(&mut store) {
207                    Val::I32(x) => wasm_encoder::ConstExpr::i32_const(x),
208                    Val::I64(x) => wasm_encoder::ConstExpr::i64_const(x),
209                    Val::F32(x) => wasm_encoder::ConstExpr::f32_const(f32::from_bits(x).into()),
210                    Val::F64(x) => wasm_encoder::ConstExpr::f64_const(f64::from_bits(x).into()),
211                    Val::V128(x) => wasm_encoder::ConstExpr::v128_const(x.as_u128() as i128),
212                    Val::FuncRef(_) => {
213                        wasm_encoder::ConstExpr::ref_null(wasm_encoder::HeapType::FUNC)
214                    }
215                    Val::ExternRef(_) => {
216                        wasm_encoder::ConstExpr::ref_null(wasm_encoder::HeapType::EXTERN)
217                    }
218                    Val::AnyRef(_) => {
219                        wasm_encoder::ConstExpr::ref_null(wasm_encoder::HeapType::ANY)
220                    }
221                    Val::ExnRef(_) => {
222                        wasm_encoder::ConstExpr::ref_null(wasm_encoder::HeapType::Abstract {
223                            shared: false,
224                            ty: wasm_encoder::AbstractHeapType::Exn,
225                        })
226                    }
227                    Val::ContRef(_) => {
228                        wasm_encoder::ConstExpr::ref_null(wasm_encoder::HeapType::Abstract {
229                            shared: false,
230                            ty: wasm_encoder::AbstractHeapType::Cont,
231                        })
232                    }
233                };
234                globals.global(
235                    wasm_encoder::GlobalType {
236                        val_type,
237                        mutable,
238                        shared: false,
239                    },
240                    &init,
241                );
242            }
243            core_dump.section(&globals);
244        }
245
246        core_dump.section(&data);
247        drop(data);
248
249        // A map from module id to its index within the core dump's modules
250        // section.
251        let mut module_to_index = HashMap::new();
252
253        {
254            let mut modules = wasm_encoder::CoreDumpModulesSection::new();
255            for module in self.modules() {
256                module_to_index.insert(module.id(), modules.len());
257                match module.name() {
258                    Some(name) => modules.module(name),
259                    None => modules.module(&format!("<anonymous-module-{}>", modules.len())),
260                };
261            }
262            core_dump.section(&modules);
263        }
264
265        // TODO: We can't currently recover instances from stack frames. We can
266        // recover module via the frame's PC, but if there are multiple
267        // instances of the same module, we don't know which instance the frame
268        // is associated with. Therefore, we do a best effort job: remember the
269        // last instance of each module and always choose that one. We record
270        // that information here.
271        let mut module_to_instance = HashMap::new();
272
273        {
274            let mut instances = wasm_encoder::CoreDumpInstancesSection::new();
275            for instance in self.instances() {
276                let module = instance.module(&store);
277                module_to_instance.insert(module.id(), instances.len());
278
279                let module_index = module_to_index[&module.id()];
280
281                // Core dumps are best-effort and may not capture every memory
282                // referenced by an instance. In particular, shared memories
283                // are intentionally omitted because their data cannot be
284                // safely read through `Memory`. Use an invalid index for any
285                // absent memory instead of panicking while serializing.
286                let memories = instance
287                    .all_memories(store.0)
288                    .filter_map(|(_, m)| m.unshared())
289                    .map(|memory| {
290                        memory_to_idx
291                            .get(&memory.hash_key(&store.0))
292                            .copied()
293                            .unwrap_or(u32::MAX)
294                    })
295                    .collect::<Vec<_>>();
296
297                // Component adapter modules can import runtime-managed globals,
298                // such as component instance flags, whose definitions are not
299                // enumerated by `StoreOpaque::for_each_global`. These globals
300                // are visible through `Instance::all_globals` but absent from
301                // the dump's globals section, so use an invalid index rather
302                // than panicking while serializing.
303                let globals = instance
304                    .all_globals(store.0)
305                    .collect::<Vec<_>>()
306                    .into_iter()
307                    .map(|(_i, global)| {
308                        global_to_idx
309                            .get(&global.hash_key(&store.0))
310                            .copied()
311                            .unwrap_or(u32::MAX)
312                    })
313                    .collect::<Vec<_>>();
314
315                instances.instance(module_index, memories, globals);
316            }
317            core_dump.section(&instances);
318        }
319
320        {
321            let thread_name = "main";
322            let mut stack = wasm_encoder::CoreDumpStackSection::new(thread_name);
323            for frame in self.frames() {
324                // This isn't necessarily the right instance if there are
325                // multiple instances of the same module. See comment above
326                // `module_to_instance` for details.
327                let instance = module_to_instance[&frame.module().id()];
328
329                let func = frame.func_index();
330
331                let offset = frame
332                    .func_offset()
333                    .and_then(|o| u32::try_from(o).ok())
334                    .unwrap_or(0);
335
336                // We can't currently recover locals and the operand stack. We
337                // should eventually be able to do that with Winch though.
338                let locals = [];
339                let operand_stack = [];
340
341                stack.frame(instance, func, offset, locals, operand_stack);
342            }
343            core_dump.section(&stack);
344        }
345
346        core_dump.finish()
347    }
348}
349
350impl fmt::Display for WasmCoreDump {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        write!(f, "wasm core dump captured")
353    }
354}
355
356impl fmt::Debug for WasmCoreDump {
357    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
358        write!(f, "<wasm core dump>")
359    }
360}