Debian Codegraph @

third_party/rust/minidump/src/minidump.rs

raw
1 // Copyright 2015 Ted Mielczarek. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3
4 use debugid::{CodeId, DebugId};
5 use memmap2::Mmap;
6 use num_traits::FromPrimitive;
7 use procfs_core::prelude::*;
8 use procfs_core::process::{MMPermissions, MemoryMap, MemoryMaps};
9 use scroll::ctx::{SizeWith, TryFromCtx};
10 use scroll::{Pread, BE, LE};
11 use std::borrow::Cow;
12 use std::collections::BTreeMap;
13 use std::collections::HashMap;
14 use std::convert::TryInto;
15 use std::fmt;
16 use std::fs::File;
17 use std::io;
18 use std::io::prelude::*;
19 use std::iter;
20 use std::marker::PhantomData;
21 use std::mem;
22 use std::ops::Deref;
23 use std::path::Path;
24 use std::str;
25 use std::time::{Duration, SystemTime};
26 use tracing::warn;
27 use uuid::Uuid;
28
29 pub use crate::context::*;
30 use crate::strings::*;
31 use crate::system_info::{Cpu, Os, PointerWidth};
32 use minidump_common::errors::{self as err};
33 use minidump_common::format::{self as md};
34 use minidump_common::format::{CvSignature, MINIDUMP_STREAM_TYPE};
35 use minidump_common::traits::{IntoRangeMapSafe, Module};
36 use range_map::{Range, RangeMap};
37 use time::format_description::well_known::Rfc3339;
38
39 /// An index into the contents of a minidump.
40 ///
41 /// The `Minidump` struct represents the parsed header and
42 /// indices contained at the start of a minidump file. It can be instantiated
43 /// by calling the [`Minidump::read`][read] or
44 /// [`Minidump::read_path`][read_path] methods.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use minidump::Minidump;
50 ///
51 /// # fn foo() -> Result<(), minidump::Error> {
52 /// let dump = Minidump::read_path("../testdata/test.dmp")?;
53 /// # Ok(())
54 /// # }
55 /// ```
56 ///
57 /// [read]: struct.Minidump.html#method.read
58 /// [read_path]: struct.Minidump.html#method.read_path
59 #[derive(Debug)]
60 pub struct Minidump<'a, T>
61 where
62 T: Deref<Target = [u8]> + 'a,
63 {
64 data: T,
65 /// The raw minidump header from the file.
66 pub header: md::MINIDUMP_HEADER,
67 streams: BTreeMap<u32, (u32, md::MINIDUMP_DIRECTORY)>,
68 system_info: Option<MinidumpSystemInfo>,
69 /// The endianness of this minidump file.
70 pub endian: scroll::Endian,
71 _phantom: PhantomData<&'a [u8]>,
72 }
73
74 /// Errors encountered while reading a `Minidump`.
75 #[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
76 pub enum Error {
77 #[error("File not found")]
78 FileNotFound,
79 #[error("I/O error")]
80 IoError,
81 #[error("Missing minidump header (empty minidump?)")]
82 MissingHeader,
83 #[error("Header mismatch")]
84 HeaderMismatch,
85 #[error("Minidump version mismatch")]
86 VersionMismatch,
87 #[error("Missing stream directory (heavily truncated minidump?)")]
88 MissingDirectory,
89 #[error("Error reading stream")]
90 StreamReadFailure,
91 #[error("Stream size mismatch: expected {expected} bytes, found {actual} bytes")]
92 StreamSizeMismatch { expected: usize, actual: usize },
93 #[error("Stream not found")]
94 StreamNotFound,
95 #[error("Module read failure")]
96 ModuleReadFailure,
97 #[error("Memory read failure")]
98 MemoryReadFailure,
99 #[error("Data error")]
100 DataError,
101 #[error("Error reading CodeView data")]
102 CodeViewReadFailure,
103 #[error("Uknown element type")]
104 UknownElementType,
105 }
106
107 impl Error {
108 /// Returns just the name of the error, as a more human-friendly version of
109 /// an error-code for error logging.
110 pub fn name(&self) -> &'static str {
111 match self {
112 Error::FileNotFound => "FileNotFound",
113 Error::IoError => "IoError",
114 Error::MissingHeader => "MissingHeader",
115 Error::HeaderMismatch => "HeaderMismatch",
116 Error::VersionMismatch => "VersionMismatch",
117 Error::MissingDirectory => "MissingDirectory",
118 Error::StreamReadFailure => "StreamReadFailure",
119 Error::StreamSizeMismatch { .. } => "StreamSizeMismatch",
120 Error::StreamNotFound => "StreamNotFound",
121 Error::ModuleReadFailure => "ModuleReadFailure",
122 Error::MemoryReadFailure => "MemoryReadFailure",
123 Error::DataError => "DataError",
124 Error::CodeViewReadFailure => "CodeViewReadFailure",
125 Error::UknownElementType => "UnknownElementType",
126 }
127 }
128 }
129
130 /// The fundamental unit of data in a `Minidump`.
131 pub trait MinidumpStream<'a>: Sized {
132 /// The stream type constant used in the `md::MDRawDirectory` entry.
133 /// This is usually a [MINIDUMP_STREAM_TYPE][] but it's left as a u32
134 /// to allow external projects to add support for their own custom streams.
135 const STREAM_TYPE: u32;
136
137 /// Read this `MinidumpStream` type from `bytes`.
138 ///
139 /// * `bytes` is the contents of this specific stream.
140 /// * `all` refers to the full contents of the minidump, for reading auxilliary data
141 /// referred to with `MINIDUMP_LOCATION_DESCRIPTOR`s.
142 /// * `system_info` is the preparsed SystemInfo stream, if it exists in the minidump.
143 fn read(
144 bytes: &'a [u8],
145 all: &'a [u8],
146 endian: scroll::Endian,
147 system_info: Option<&MinidumpSystemInfo>,
148 ) -> Result<Self, Error>;
149 }
150
151 /// Provides a unified interface for getting metadata about the process's mapped memory regions
152 /// at the time of the crash.
153 ///
154 /// Currently this is one of [`MinidumpMemoryInfoList`], available in Windows minidumps,
155 /// or [`MinidumpLinuxMaps`], available in Linux minidumps.
156 ///
157 /// This allows you to e.g. check whether an address was executable or not without
158 /// worrying about which platform the crash occured on. If you need to do more
159 /// specific analysis, you can get the native formats with [`UnifiedMemoryInfoList::info`]
160 /// and [`UnifiedMemoryInfoList::maps`].
161 ///
162 /// Currently an enum because there is no situation where you can have both,
163 /// but this may change if the format evolves. Prefer using this type's methods
164 /// over pattern matching.
165 #[derive(Debug, Clone)]
166 pub enum UnifiedMemoryInfoList<'a> {
167 Maps(MinidumpLinuxMaps<'a>),
168 Info(MinidumpMemoryInfoList<'a>),
169 }
170
171 #[derive(Debug, Copy, Clone)]
172 /// A [`UnifiedMemoryInfoList`] entry, providing metatadata on a region of
173 /// memory in the crashed process.
174 pub enum UnifiedMemoryInfo<'a> {
175 Map(&'a MinidumpLinuxMapInfo<'a>),
176 Info(&'a MinidumpMemoryInfo<'a>),
177 }
178
179 /// The contents of `/proc/self/maps` for the crashing process.
180 ///
181 /// This is roughly equivalent in functionality to [`MinidumpMemoryInfoList`].
182 /// Use [`UnifiedMemoryInfoList`] to handle the two uniformly.
183 #[derive(Debug, Clone)]
184 pub struct MinidumpLinuxMaps<'a> {
185 /// The memory regions, in the order they were stored in the minidump.
186 regions: Vec<MinidumpLinuxMapInfo<'a>>,
187 /// Map from address range to index in regions. Use
188 /// [`MinidumpLinuxMaps::memory_info_at_address`].
189 regions_by_addr: RangeMap<u64, usize>,
190 }
191
192 /// A memory mapping entry for the process we are analyzing.
193 #[derive(Debug, Clone, PartialEq, Eq)]
194 pub struct MinidumpLinuxMapInfo<'a> {
195 pub map: MemoryMap,
196 _phantom: PhantomData<&'a u8>,
197 }
198
199 #[derive(Debug, Clone)]
200 pub struct MinidumpMemoryInfoList<'a> {
201 /// The memory regions, in the order they were stored in the minidump.
202 regions: Vec<MinidumpMemoryInfo<'a>>,
203 /// Map from address range to index in regions. Use
204 /// [`MinidumpMemoryInfoList::memory_info_at_address`].
205 regions_by_addr: RangeMap<u64, usize>,
206 }
207
208 #[derive(Debug, Clone, PartialEq, Eq)]
209 /// Metadata about a region of memory (whether it is executable, freed, private, and so on).
210 pub struct MinidumpMemoryInfo<'a> {
211 /// The raw value from the minidump.
212 pub raw: md::MINIDUMP_MEMORY_INFO,
213 /// The memory protection when the region was initially allocated.
214 pub allocation_protection: md::MemoryProtection,
215 /// The state of the pages in the region (whether it is freed or not).
216 pub state: md::MemoryState,
217 /// The access protection of the pages in the region.
218 pub protection: md::MemoryProtection,
219 /// What kind of memory mapping the pages in this region are.
220 pub ty: md::MemoryType,
221 _phantom: PhantomData<&'a u8>,
222 }
223
224 /// CodeView data describes how to locate debug symbols
225 #[derive(Debug, Clone)]
226 pub enum CodeView {
227 /// PDB 2.0 format data in a separate file
228 Pdb20(md::CV_INFO_PDB20),
229 /// PDB 7.0 format data in a separate file (most common)
230 Pdb70(md::CV_INFO_PDB70),
231 /// Indicates data is in an ELF binary with build ID `build_id`
232 Elf(md::CV_INFO_ELF),
233 /// An unknown format containing the raw bytes of data
234 Unknown(Vec<u8>),
235 }
236
237 /// An executable or shared library loaded in the process at the time the `Minidump` was written.
238 #[derive(Debug, Clone)]
239 pub struct MinidumpModule {
240 /// The `MINIDUMP_MODULE` direct from the minidump file.
241 pub raw: md::MINIDUMP_MODULE,
242 /// The module name. This is stored separately in the minidump.
243 pub name: String,
244 /// A `CodeView` record, if one is present.
245 pub codeview_info: Option<CodeView>,
246 /// A misc debug record, if one is present.
247 pub misc_info: Option<md::IMAGE_DEBUG_MISC>,
248 os: Os,
249 /// The parsed DebugId of the module, if one is present.
250 debug_id: Option<DebugId>,
251 }
252
253 /// A list of `MinidumpModule`s contained in a `Minidump`.
254 #[derive(Debug, Clone)]
255 pub struct MinidumpModuleList {
256 /// The modules, in the order they were stored in the minidump.
257 modules: Vec<MinidumpModule>,
258 /// Map from address range to index in modules. Use `MinidumpModuleList::module_at_address`.
259 modules_by_addr: RangeMap<u64, usize>,
260 }
261
262 /// A mapping of thread ids to their names.
263 #[derive(Debug, Clone, Default)]
264 pub struct MinidumpThreadNames {
265 names: BTreeMap<u32, String>,
266 }
267
268 /// An executable or shared library that was once loaded into the process, but was unloaded
269 /// by the time the `Minidump` was written.
270 #[derive(Debug, Clone)]
271 pub struct MinidumpUnloadedModule {
272 /// The `MINIDUMP_UNLOADED_MODULE` direct from the minidump file.
273 pub raw: md::MINIDUMP_UNLOADED_MODULE,
274 /// The module name. This is stored separately in the minidump.
275 pub name: String,
276 }
277
278 /// A list of `MinidumpUnloadedModule`s contained in a `Minidump`.
279 #[derive(Debug, Clone)]
280 pub struct MinidumpUnloadedModuleList {
281 /// The modules, in the order they were stored in the minidump.
282 modules: Vec<MinidumpUnloadedModule>,
283 /// Map from address range to index in modules.
284 /// Use `MinidumpUnloadedModuleList::modules_at_address`.
285 modules_by_addr: Vec<(Range<u64>, usize)>,
286 }
287
288 /// Contains object-specific information for a handle. Microsoft documentation
289 /// doesn't describe the contents of this type.
290 #[derive(Debug, Clone)]
291 pub struct MinidumpHandleObjectInformation {
292 pub raw: md::MINIDUMP_HANDLE_OBJECT_INFORMATION,
293 pub info_type: md::MINIDUMP_HANDLE_OBJECT_INFORMATION_TYPE,
294 }
295
296 impl fmt::Display for MinidumpHandleObjectInformation {
297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298 write!(f, "{{raw: {:?}, type: {:?}}}", self.raw, self.info_type)
299 }
300 }
301
302 #[allow(clippy::large_enum_variant)]
303 #[derive(Debug, Clone)]
304 pub enum RawHandleDescriptor {
305 HandleDescriptor(md::MINIDUMP_HANDLE_DESCRIPTOR),
306 HandleDescriptor2(md::MINIDUMP_HANDLE_DESCRIPTOR_2),
307 }
308
309 /// Describes the state of an individual system handle at the time the minidump was written.
310 #[derive(Debug, Clone)]
311 pub struct MinidumpHandleDescriptor {
312 /// The `MINIDUMP_HANDKE_DESCRIPTOR` data direct from the minidump file.
313 pub raw: RawHandleDescriptor,
314 /// The name of the type of this handle, if present.
315 pub type_name: Option<String>,
316 /// The object name of this handle, if present.
317 /// On Linux this is the file path.
318 pub object_name: Option<String>,
319 /// Object information for this handle, can be empty, platform-specific.
320 pub object_infos: Vec<MinidumpHandleObjectInformation>,
321 }
322
323 /// A stream holding all the system handles at the time the minidump was written.
324 /// On Linux this is the list of open file descriptors.
325 #[derive(Debug, Clone)]
326 pub struct MinidumpHandleDataStream {
327 pub handles: Vec<MinidumpHandleDescriptor>,
328 }
329
330 /// The state of a thread from the process when the minidump was written.
331 #[derive(Debug)]
332 pub struct MinidumpThread<'a> {
333 /// The `MINIDUMP_THREAD` direct from the minidump file.
334 pub raw: md::MINIDUMP_THREAD,
335 /// The CPU context for the thread, if present.
336 context: Option<&'a [u8]>,
337 /// The stack memory for the thread, if present.
338 stack: Option<MinidumpMemory<'a>>,
339 /// Saved endianness for lazy parsing.
340 endian: scroll::Endian,
341 }
342
343 /// A list of `MinidumpThread`s contained in a `Minidump`.
344 #[derive(Debug)]
345 pub struct MinidumpThreadList<'a> {
346 /// The threads, in the order they were present in the `Minidump`.
347 pub threads: Vec<MinidumpThread<'a>>,
348 /// A map of thread id to index in `threads`.
349 thread_ids: HashMap<u32, usize>,
350 }
351
352 /// The state of a thread from the process when the minidump was written.
353 #[derive(Debug)]
354 pub struct MinidumpThreadInfo {
355 /// The `MINIDUMP_THREAD_INFO` direct from the minidump file.
356 pub raw: md::MINIDUMP_THREAD_INFO,
357 }
358
359 /// A list of `MinidumpThread`s contained in a `Minidump`.
360 #[derive(Debug)]
361 pub struct MinidumpThreadInfoList {
362 /// The thread info entries, in the order they were present in the `Minidump`.
363 pub thread_infos: Vec<MinidumpThreadInfo>,
364 /// A map of thread id to index in `entries`.
365 thread_ids: HashMap<u32, usize>,
366 }
367
368 /// Information about the system that generated the minidump.
369 #[derive(Debug, Clone)]
370 pub struct MinidumpSystemInfo {
371 /// The `MINIDUMP_SYSTEM_INFO` direct from the minidump
372 pub raw: md::MINIDUMP_SYSTEM_INFO,
373 /// The operating system that generated the minidump
374 pub os: Os,
375 /// The CPU on which the minidump was generated
376 pub cpu: Cpu,
377 /// A string that describes the latest Service Pack installed on the system.
378 /// If no Service Pack has been installed, the string is empty.
379 /// This is stored separately in the minidump.
380 csd_version: Option<String>,
381 /// An x86 (not x64!) CPU vendor name that is stored in `raw` but in a way
382 /// that's
383 cpu_info: Option<String>,
384 }
385
386 /// A region of memory from the process that wrote the minidump.
387 /// This is the underlying generic type for [MinidumpMemory] and [MinidumpMemory64].
388 #[derive(Clone, Debug)]
389 pub struct MinidumpMemoryBase<'a, Descriptor> {
390 /// The raw `MINIDUMP_MEMORY_DESCRIPTOR` from the minidump.
391 pub desc: Descriptor,
392 /// The starting address of this range of memory.
393 pub base_address: u64,
394 /// The length of this range of memory.
395 pub size: u64,
396 /// The contents of the memory.
397 pub bytes: &'a [u8],
398 /// The endianness of the minidump which is used for memory accesses.
399 pub endian: scroll::Endian,
400 }
401
402 /// A region of memory from the process that wrote the minidump.
403 pub type MinidumpMemory<'a> = MinidumpMemoryBase<'a, md::MINIDUMP_MEMORY_DESCRIPTOR>;
404
405 /// A large region of memory from the process that wrote the minidump (usually a full dump).
406 pub type MinidumpMemory64<'a> = MinidumpMemoryBase<'a, md::MINIDUMP_MEMORY_DESCRIPTOR64>;
407
408 /// Provides a unified interface for MinidumpMemory and MinidumpMemory64
409 #[derive(Debug, Clone, Copy)]
410 pub enum UnifiedMemory<'a, 'mdmp> {
411 Memory(&'a MinidumpMemory<'mdmp>),
412 Memory64(&'a MinidumpMemory64<'mdmp>),
413 }
414
415 #[derive(Debug, Clone)]
416 pub enum RawMacCrashInfo {
417 V1(
418 md::MINIDUMP_MAC_CRASH_INFO_RECORD,
419 md::MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS,
420 ),
421 V4(
422 md::MINIDUMP_MAC_CRASH_INFO_RECORD_4,
423 md::MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS_4,
424 ),
425 V5(
426 md::MINIDUMP_MAC_CRASH_INFO_RECORD_5,
427 md::MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS_5,
428 ),
429 }
430
431 #[derive(Debug, Clone)]
432 pub struct MinidumpMacCrashInfo {
433 /// The `MINIDUMP_MAC_CRASH_INFO_RECORD` and `MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS`.
434 pub raw: Vec<RawMacCrashInfo>,
435 }
436
437 #[derive(Debug, Clone)]
438 pub struct MinidumpMacBootargs {
439 pub raw: md::MINIDUMP_MAC_BOOTARGS,
440 pub bootargs: Option<String>,
441 }
442
443 #[allow(clippy::large_enum_variant)]
444 #[derive(Debug, Clone)]
445 pub enum RawMiscInfo {
446 MiscInfo(md::MINIDUMP_MISC_INFO),
447 MiscInfo2(md::MINIDUMP_MISC_INFO_2),
448 MiscInfo3(md::MINIDUMP_MISC_INFO_3),
449 MiscInfo4(md::MINIDUMP_MISC_INFO_4),
450 MiscInfo5(md::MINIDUMP_MISC_INFO_5),
451 }
452
453 /// Miscellaneous information about the process that wrote the minidump.
454 #[derive(Debug, Clone)]
455 pub struct MinidumpMiscInfo {
456 /// The `MINIDUMP_MISC_INFO` struct direct from the minidump.
457 pub raw: RawMiscInfo,
458 }
459
460 /// Additional information about process state.
461 ///
462 /// MinidumpBreakpadInfo wraps MINIDUMP_BREAKPAD_INFO, which is an optional stream
463 /// in a minidump that provides additional information about the process state
464 /// at the time the minidump was generated.
465 #[derive(Debug, Clone)]
466 pub struct MinidumpBreakpadInfo {
467 raw: md::MINIDUMP_BREAKPAD_INFO,
468 /// The thread that wrote the minidump.
469 pub dump_thread_id: Option<u32>,
470 /// The thread that requested that a minidump be written.
471 pub requesting_thread_id: Option<u32>,
472 }
473
474 #[derive(Default, Debug)]
475 /// Interesting values extracted from /etc/lsb-release
476 pub struct MinidumpLinuxLsbRelease<'a> {
477 data: &'a [u8],
478 }
479
480 /// Interesting values extracted from /proc/self/environ
481 #[derive(Default, Debug)]
482 pub struct MinidumpLinuxEnviron<'a> {
483 data: &'a [u8],
484 }
485
486 /// Interesting values extracted from /proc/cpuinfo
487 #[derive(Default, Debug)]
488 pub struct MinidumpLinuxCpuInfo<'a> {
489 data: &'a [u8],
490 }
491
492 /// Interesting values extracted from /proc/self/status
493 #[derive(Default, Debug)]
494 pub struct MinidumpLinuxProcStatus<'a> {
495 data: &'a [u8],
496 }
497
498 /// Interesting values extracted from /proc/self/limits
499 #[derive(Default, Debug)]
500 pub struct MinidumpLinuxProcLimits<'a> {
501 data: &'a [u8],
502 }
503
504 /// The reason for a process crash.
505 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
506 pub enum CrashReason {
507 /// A Mac/iOS error code with no other interesting details.
508 MacGeneral(err::ExceptionCodeMac, u32),
509 MacBadAccessKern(err::ExceptionCodeMacBadAccessKernType),
510 MacBadAccessArm(err::ExceptionCodeMacBadAccessArmType),
511 MacBadAccessPpc(err::ExceptionCodeMacBadAccessPpcType),
512 MacBadAccessX86(err::ExceptionCodeMacBadAccessX86Type),
513 MacBadInstructionArm(err::ExceptionCodeMacBadInstructionArmType),
514 MacBadInstructionPpc(err::ExceptionCodeMacBadInstructionPpcType),
515 MacBadInstructionX86(err::ExceptionCodeMacBadInstructionX86Type),
516 MacArithmeticArm(err::ExceptionCodeMacArithmeticArmType),
517 MacArithmeticPpc(err::ExceptionCodeMacArithmeticPpcType),
518 MacArithmeticX86(err::ExceptionCodeMacArithmeticX86Type),
519 MacSoftware(err::ExceptionCodeMacSoftwareType),
520 MacBreakpointArm(err::ExceptionCodeMacBreakpointArmType),
521 MacBreakpointPpc(err::ExceptionCodeMacBreakpointPpcType),
522 MacBreakpointX86(err::ExceptionCodeMacBreakpointX86Type),
523 MacResource(err::ExceptionCodeMacResourceType, u64, u64),
524 MacGuard(err::ExceptionCodeMacGuardType, u64, u64),
525
526 /// A Linux/Android error code with no other interesting metadata.
527 LinuxGeneral(err::ExceptionCodeLinux, u32),
528 LinuxSigill(err::ExceptionCodeLinuxSigillKind),
529 LinuxSigtrap(err::ExceptionCodeLinuxSigtrapKind),
530 LinuxSigbus(err::ExceptionCodeLinuxSigbusKind),
531 LinuxSigfpe(err::ExceptionCodeLinuxSigfpeKind),
532 LinuxSigsegv(err::ExceptionCodeLinuxSigsegvKind),
533 LinuxSigsys(err::ExceptionCodeLinuxSigsysKind),
534
535 /// A Windows error code with no other interesting metadata.
536 WindowsGeneral(err::ExceptionCodeWindows),
537 /// A Windows error from winerror.h.
538 WindowsWinError(err::WinErrorWindows),
539 /// A Windows error for a specific facility from winerror.h.
540 WindowsWinErrorWithFacility(err::WinErrorFacilityWindows, err::WinErrorWindows),
541 /// A Windows error from ntstatus.h
542 WindowsNtStatus(err::NtStatusWindows),
543 /// ExceptionCodeWindows::EXCEPTION_ACCESS_VIOLATION but with details on the kind of access.
544 WindowsAccessViolation(err::ExceptionCodeWindowsAccessType),
545 /// ExceptionCodeWindows::EXCEPTION_IN_PAGE_ERROR but with details on the kind of access.
546 /// Second argument is a windows NTSTATUS value.
547 WindowsInPageError(err::ExceptionCodeWindowsInPageErrorType, u64),
548 /// ExceptionCodeWindows::EXCEPTION_STACK_BUFFER_OVERRUN with an accompanying
549 /// windows FAST_FAIL value.
550 WindowsStackBufferOverrun(u64),
551 /// A Windows error with no known mapping.
552 WindowsUnknown(u32),
553
554 Unknown(u32, u32),
555 }
556
557 /// Information about the exception that caused the minidump to be generated.
558 ///
559 /// `MinidumpException` wraps `MINIDUMP_EXCEPTION_STREAM`, which contains information
560 /// about the exception that caused the minidump to be generated, if the
561 /// minidump was generated in an exception handler called as a result of an
562 /// exception. It also provides access to a `MinidumpContext` object, which
563 /// contains the CPU context for the exception thread at the time the exception
564 /// occurred.
565 #[derive(Debug)]
566 pub struct MinidumpException<'a> {
567 /// The raw exception information from the minidump stream.
568 pub raw: md::MINIDUMP_EXCEPTION_STREAM,
569 /// The thread that encountered this exception.
570 pub thread_id: u32,
571 /// If present, the CPU context from the time the thread encountered the exception.
572 ///
573 /// This should be used in place of the context contained within the thread with id
574 /// `thread_id`, since it points to the code location where the exception happened,
575 /// without any exception handling routines that are likely to be on the stack after
576 /// that point.
577 context: Option<&'a [u8]>,
578 /// Saved endianess for lazy parsing.
579 endian: scroll::Endian,
580 }
581
582 /// A list of memory regions included in a minidump.
583 /// This is the underlying generic type for [MinidumpMemoryList] and [MinidumpMemory64List].
584 #[derive(Debug)]
585 pub struct MinidumpMemoryListBase<'a, Descriptor> {
586 /// The memory regions, in the order they were stored in the minidump.
587 regions: Vec<MinidumpMemoryBase<'a, Descriptor>>,
588 /// Map from address range to index in regions. Use `MinidumpMemoryList::memory_at_address`.
589 regions_by_addr: RangeMap<u64, usize>,
590 }
591
592 /// A list of memory regions included in a minidump.
593 pub type MinidumpMemoryList<'a> = MinidumpMemoryListBase<'a, md::MINIDUMP_MEMORY_DESCRIPTOR>;
594
595 /// A list of large memory regions included in a minidump (usually a full dump).
596 pub type MinidumpMemory64List<'a> = MinidumpMemoryListBase<'a, md::MINIDUMP_MEMORY_DESCRIPTOR64>;
597
598 /// Provides a unified interface for MinidumpMemoryList and MinidumpMemory64List
599 #[derive(Debug)]
600 pub enum UnifiedMemoryList<'a> {
601 Memory(MinidumpMemoryList<'a>),
602 Memory64(MinidumpMemory64List<'a>),
603 }
604 impl Default for UnifiedMemoryList<'_> {
605 fn default() -> Self {
606 Self::Memory(Default::default())
607 }
608 }
609
610 /// Information about an assertion that caused a crash.
611 #[derive(Debug)]
612 pub struct MinidumpAssertion {
613 pub raw: md::MINIDUMP_ASSERTION_INFO,
614 }
615
616 /// A typed annotation object.
617 #[derive(Clone, Debug)]
618 #[non_exhaustive]
619 pub enum MinidumpAnnotation {
620 /// An invalid annotation. Reserved for internal use.
621 Invalid,
622 /// A `NUL`-terminated C-string.
623 String(String),
624 /// Clients may declare their own custom types.
625 UserDefined(md::MINIDUMP_ANNOTATION),
626 /// An unsupported annotation from a future crashpad version.
627 Unsupported(md::MINIDUMP_ANNOTATION),
628 }
629
630 impl PartialEq for MinidumpAnnotation {
631 fn eq(&self, other: &Self) -> bool {
632 match (self, other) {
633 (Self::Invalid, Self::Invalid) => true,
634 (Self::String(a), Self::String(b)) => a == b,
635 _ => false,
636 }
637 }
638 }
639
640 /// Additional Crashpad-specific information about a module carried within a minidump file.
641 #[derive(Debug)]
642 pub struct MinidumpModuleCrashpadInfo {
643 /// The raw crashpad module extension information.
644 pub raw: md::MINIDUMP_MODULE_CRASHPAD_INFO,
645 /// Index of the corresponding module in the `MinidumpModuleList`.
646 pub module_index: usize,
647 pub list_annotations: Vec<String>,
648 pub simple_annotations: BTreeMap<String, String>,
649 pub annotation_objects: BTreeMap<String, MinidumpAnnotation>,
650 }
651
652 /// Additional Crashpad-specific information carried within a minidump file.
653 #[derive(Debug)]
654 pub struct MinidumpCrashpadInfo {
655 pub raw: md::MINIDUMP_CRASHPAD_INFO,
656 pub simple_annotations: BTreeMap<String, String>,
657 pub module_list: Vec<MinidumpModuleCrashpadInfo>,
658 }
659
660 //======================================================
661 // Implementations
662
663 fn format_time_t(t: u32) -> String {
664 time::OffsetDateTime::from_unix_timestamp(t as i64)
665 .ok()
666 .and_then(|datetime| datetime.format(&Rfc3339).ok())
667 .unwrap_or_default()
668 }
669
670 fn format_system_time(time: &md::SYSTEMTIME) -> String {
671 // Note this drops the day_of_week field on the ground -- is that fine?
672 let format_date = || {
673 use std::convert::TryFrom;
674 let month = time::Month::try_from(time.month as u8).ok()?;
675 let date = time::Date::from_calendar_date(time.year as i32, month, time.day as u8).ok()?;
676 let datetime = date
677 .with_hms_milli(
678 time.hour as u8,
679 time.minute as u8,
680 time.second as u8,
681 time.milliseconds,
682 )
683 .ok()?
684 .assume_utc();
685 datetime.format(&Rfc3339).ok()
686 };
687 format_date().unwrap_or_else(|| "<invalid date>".to_owned())
688 }
689
690 /// Produce a slice of `bytes` corresponding to the offset and size in `loc`, or an
691 /// `Error` if the data is not fully contained within `bytes`.
692 fn location_slice<'a>(
693 bytes: &'a [u8],
694 loc: &md::MINIDUMP_LOCATION_DESCRIPTOR,
695 ) -> Result<&'a [u8], Error> {
696 let start = loc.rva as usize;
697 start
698 .checked_add(loc.data_size as usize)
699 .and_then(|end| bytes.get(start..end))
700 .ok_or(Error::StreamReadFailure)
701 }
702
703 /// Read a u32 length-prefixed UTF-16 string from `bytes` at `offset`.
704 fn read_string_utf16(offset: &mut usize, bytes: &[u8], endian: scroll::Endian) -> Option<String> {
705 let u: u32 = bytes.gread_with(offset, endian).ok()?;
706 let size = u as usize;
707 if size % 2 != 0 || (*offset + size) > bytes.len() {
708 return None;
709 }
710 let encoding = match endian {
711 scroll::Endian::Little => encoding_rs::UTF_16LE,
712 scroll::Endian::Big => encoding_rs::UTF_16BE,
713 };
714
715 let s = encoding
716 .decode_without_bom_handling_and_without_replacement(&bytes[*offset..*offset + size])?;
717 *offset += size;
718 Some(s.into())
719 }
720
721 #[inline]
722 fn read_string_utf8_unterminated<'a>(
723 offset: &mut usize,
724 bytes: &'a [u8],
725 endian: scroll::Endian,
726 ) -> Option<&'a str> {
727 let length: u32 = bytes.gread_with(offset, endian).ok()?;
728 let slice = bytes.gread_with(offset, length as usize).ok()?;
729 std::str::from_utf8(slice).ok()
730 }
731
732 fn read_string_utf8<'a>(
733 offset: &mut usize,
734 bytes: &'a [u8],
735 endian: scroll::Endian,
736 ) -> Option<&'a str> {
737 let string = read_string_utf8_unterminated(offset, bytes, endian)?;
738 match bytes.gread(offset) {
739 Ok(0u8) => Some(string),
740 _ => None,
741 }
742 }
743
744 fn read_cstring_utf8(offset: &mut usize, bytes: &[u8]) -> Option<String> {
745 let initial_offset = *offset;
746 loop {
747 let byte: u8 = bytes.gread(offset).ok()?;
748 if byte == 0 {
749 break;
750 }
751 }
752 std::str::from_utf8(&bytes[initial_offset..*offset - 1])
753 .map(String::from)
754 .ok()
755 }
756
757 /// Convert `bytes` with trailing NUL characters to a string
758 fn string_from_bytes_nul(bytes: &[u8]) -> Option<Cow<'_, str>> {
759 bytes.split(|&b| b == 0).next().map(String::from_utf8_lossy)
760 }
761
762 /// Format `bytes` as a String of hex digits
763 fn bytes_to_hex(bytes: &[u8]) -> String {
764 let hex_bytes: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
765 hex_bytes.join("")
766 }
767
768 /// Attempt to read a CodeView record from `data` at `location`
769 fn read_codeview(
770 location: &md::MINIDUMP_LOCATION_DESCRIPTOR,
771 data: &[u8],
772 endian: scroll::Endian,
773 ) -> Option<CodeView> {
774 let bytes = location_slice(data, location).ok()?;
775 // The CodeView data can be one of a few different formats. Try to read the
776 // signature first to figure out what format the data is.
777 let signature: u32 = bytes.pread_with(0, endian).ok()?;
778 Some(match CvSignature::from_u32(signature) {
779 // PDB data has two known versions: the current 7.0 and the older 2.0 version.
780 Some(CvSignature::Pdb70) => CodeView::Pdb70(bytes.pread_with(0, endian).ok()?),
781 Some(CvSignature::Pdb20) => CodeView::Pdb20(bytes.pread_with(0, endian).ok()?),
782 // Breakpad's ELF build ID format.
783 Some(CvSignature::Elf) => CodeView::Elf(bytes.pread_with(0, endian).ok()?),
784 // Other formats aren't handled, but save the raw bytes.
785 _ => CodeView::Unknown(bytes.to_owned()),
786 })
787 }
788
789 fn read_debug_id(codeview_info: &CodeView, endian: scroll::Endian) -> Option<DebugId> {
790 match codeview_info {
791 CodeView::Pdb70(ref raw) => {
792 // For macOS, this should be its code ID with the age (0)
793 // appended to the end of it. This makes it identical to debug
794 // IDs for Windows, and is why it doesn't have a special case
795 // here.
796 let uuid = Uuid::from_fields(
797 raw.signature.data1,
798 raw.signature.data2,
799 raw.signature.data3,
800 &raw.signature.data4,
801 );
802 (!uuid.is_nil()).then(|| DebugId::from_parts(uuid, raw.age))
803 }
804 CodeView::Pdb20(ref raw) => Some(DebugId::from_pdb20(raw.signature, raw.age)),
805 CodeView::Elf(ref raw) => {
806 // For empty or trivial `build_id`s, we don't want to return a `DebugId`.
807 // This can happen for mapped files that aren't executable, like fonts or .jar files.
808 if raw.build_id.iter().all(|byte| *byte == 0) {
809 return None;
810 }
811
812 // For backwards-compat (Linux minidumps have historically
813 // been written using PDB70 CodeView info), treat build_id
814 // as if the first 16 bytes were a GUID.
815 let guid_size = <md::GUID>::size_with(&endian);
816 let guid = if raw.build_id.len() < guid_size {
817 // Pad with zeros.
818 let v: Vec<u8> = raw
819 .build_id
820 .iter()
821 .cloned()
822 .chain(iter::repeat(0))
823 .take(guid_size)
824 .collect();
825 v.pread_with::<md::GUID>(0, endian).ok()
826 } else {
827 raw.build_id.pread_with::<md::GUID>(0, endian).ok()
828 };
829 guid.map(|g| Uuid::from_fields(g.data1, g.data2, g.data3, &g.data4))
830 .map(DebugId::from_uuid)
831 }
832 _ => None,
833 }
834 }
835
836 /// Checks that the buffer is large enough for the given number of items.
837 ///
838 /// Essentially ensures that `buf.len() >= offset + (number_of_entries * size_of_entry)`.
839 /// Returns `(number_of_entries, expected_size)` on success.
840 fn ensure_count_in_bound(
841 buf: &[u8],
842 number_of_entries: usize,
843 size_of_entry: usize,
844 offset: usize,
845 ) -> Result<(usize, usize), Error> {
846 let expected_size = number_of_entries
847 .checked_mul(size_of_entry)
848 .and_then(|v| v.checked_add(offset))
849 .ok_or(Error::StreamReadFailure)?;
850 if buf.len() < expected_size {
851 return Err(Error::StreamSizeMismatch {
852 expected: expected_size,
853 actual: buf.len(),
854 });
855 }
856 Ok((number_of_entries, expected_size))
857 }
858
859 impl MinidumpModule {
860 /// Create a `MinidumpModule` with some basic info.
861 ///
862 /// Useful for testing.
863 pub fn new(base: u64, size: u32, name: &str) -> MinidumpModule {
864 MinidumpModule {
865 raw: md::MINIDUMP_MODULE {
866 base_of_image: base,
867 size_of_image: size,
868 ..md::MINIDUMP_MODULE::default()
869 },
870 name: String::from(name),
871 codeview_info: None,
872 misc_info: None,
873 os: Os::Unknown(0),
874 debug_id: None,
875 }
876 }
877
878 /// Read additional data to construct a `MinidumpModule` from `bytes` using the information
879 /// from the module list in `raw`.
880 pub fn read(
881 raw: md::MINIDUMP_MODULE,
882 bytes: &[u8],
883 endian: scroll::Endian,
884 system_info: Option<&MinidumpSystemInfo>,
885 ) -> Result<MinidumpModule, Error> {
886 let mut offset = raw.module_name_rva as usize;
887 let name =
888 read_string_utf16(&mut offset, bytes, endian).ok_or(Error::CodeViewReadFailure)?;
889 let codeview_info = if raw.cv_record.data_size == 0 {
890 None
891 } else {
892 Some(read_codeview(&raw.cv_record, bytes, endian).ok_or(Error::CodeViewReadFailure)?)
893 };
894
895 let os = system_info.map(|info| info.os).unwrap_or(Os::Unknown(0));
896
897 let debug_id = codeview_info
898 .as_ref()
899 .and_then(|cv| read_debug_id(cv, endian));
900
901 Ok(MinidumpModule {
902 raw,
903 name,
904 codeview_info,
905 misc_info: None,
906 os,
907 debug_id,
908 })
909 }
910
911 /// Write a human-readable description of this `MinidumpModule` to `f`.
912 ///
913 /// This is very verbose, it is the format used by `minidump_dump`.
914 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
915 write!(
916 f,
917 "MINIDUMP_MODULE
918 base_of_image = {:#x}
919 size_of_image = {:#x}
920 checksum = {:#x}
921 time_date_stamp = {:#x} {}
922 module_name_rva = {:#x}
923 version_info.signature = {:#x}
924 version_info.struct_version = {:#x}
925 version_info.file_version = {:#x}:{:#x}
926 version_info.product_version = {:#x}:{:#x}
927 version_info.file_flags_mask = {:#x}
928 version_info.file_flags = {:#x}
929 version_info.file_os = {:#x}
930 version_info.file_type = {:#x}
931 version_info.file_subtype = {:#x}
932 version_info.file_date = {:#x}:{:#x}
933 cv_record.data_size = {}
934 cv_record.rva = {:#x}
935 misc_record.data_size = {}
936 misc_record.rva = {:#x}
937 (code_file) = \"{}\"
938 (code_identifier) = \"{}\"
939 ",
940 self.raw.base_of_image,
941 self.raw.size_of_image,
942 self.raw.checksum,
943 self.raw.time_date_stamp,
944 format_time_t(self.raw.time_date_stamp),
945 self.raw.module_name_rva,
946 self.raw.version_info.signature,
947 self.raw.version_info.struct_version,
948 self.raw.version_info.file_version_hi,
949 self.raw.version_info.file_version_lo,
950 self.raw.version_info.product_version_hi,
951 self.raw.version_info.product_version_lo,
952 self.raw.version_info.file_flags_mask,
953 self.raw.version_info.file_flags,
954 self.raw.version_info.file_os,
955 self.raw.version_info.file_type,
956 self.raw.version_info.file_subtype,
957 self.raw.version_info.file_date_hi,
958 self.raw.version_info.file_date_lo,
959 self.raw.cv_record.data_size,
960 self.raw.cv_record.rva,
961 self.raw.misc_record.data_size,
962 self.raw.misc_record.rva,
963 self.code_file(),
964 self.code_identifier().unwrap_or_default(),
965 )?;
966 // Print CodeView data.
967 match self.codeview_info {
968 Some(CodeView::Pdb70(ref raw)) => {
969 let pdb_file_name =
970 string_from_bytes_nul(&raw.pdb_file_name).unwrap_or(Cow::Borrowed("(invalid)"));
971 write!(f, " (cv_record).cv_signature = {:#x}
972 (cv_record).signature = {:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}
973 (cv_record).age = {}
974 (cv_record).pdb_file_name = \"{}\"
975 ",
976 raw.cv_signature,
977 raw.signature.data1,
978 raw.signature.data2,
979 raw.signature.data3,
980 raw.signature.data4[0],
981 raw.signature.data4[1],
982 raw.signature.data4[2],
983 raw.signature.data4[3],
984 raw.signature.data4[4],
985 raw.signature.data4[5],
986 raw.signature.data4[6],
987 raw.signature.data4[7],
988 raw.age,
989 pdb_file_name,
990 )?;
991 }
992 Some(CodeView::Pdb20(ref raw)) => {
993 let pdb_file_name =
994 string_from_bytes_nul(&raw.pdb_file_name).unwrap_or(Cow::Borrowed("(invalid)"));
995 write!(
996 f,
997 " (cv_record).cv_header.signature = {:#x}
998 (cv_record).cv_header.offset = {:#x}
999 (cv_record).signature = {:#x} {}
1000 (cv_record).age = {}
1001 (cv_record).pdb_file_name = \"{}\"
1002 ",
1003 raw.cv_signature,
1004 raw.cv_offset,
1005 raw.signature,
1006 format_time_t(raw.signature),
1007 raw.age,
1008 pdb_file_name,
1009 )?;
1010 }
1011 Some(CodeView::Elf(ref raw)) => {
1012 // Fibbing about having cv_signature handy here.
1013 write!(
1014 f,
1015 " (cv_record).cv_signature = {:#x}
1016 (cv_record).build_id = {}
1017 ",
1018 raw.cv_signature,
1019 bytes_to_hex(&raw.build_id),
1020 )?;
1021 }
1022 Some(CodeView::Unknown(ref bytes)) => {
1023 writeln!(
1024 f,
1025 " (cv_record) = {}",
1026 bytes_to_hex(bytes),
1027 )?;
1028 }
1029 None => {
1030 writeln!(f, " (cv_record) = (null)")?;
1031 }
1032 }
1033
1034 // Print misc record data.
1035 if let Some(ref _misc) = self.misc_info {
1036 //TODO, not terribly important.
1037 writeln!(f, " (misc_record) = (unimplemented)")?;
1038 } else {
1039 writeln!(f, " (misc_record) = (null)")?;
1040 }
1041
1042 // Print remaining data.
1043 write!(
1044 f,
1045 r#" (debug_file) = "{}"
1046 (debug_identifier) = "{}"
1047 (version) = "{}"
1048
1049 "#,
1050 self.debug_file().unwrap_or(Cow::Borrowed("")),
1051 self.debug_identifier().unwrap_or_default(),
1052 self.version().unwrap_or(Cow::Borrowed("")),
1053 )?;
1054 Ok(())
1055 }
1056
1057 fn memory_range(&self) -> Option<Range<u64>> {
1058 if self.size() == 0 {
1059 return None;
1060 }
1061 Some(Range::new(
1062 self.base_address(),
1063 self.base_address().checked_add(self.size())? - 1,
1064 ))
1065 }
1066 }
1067
1068 impl Module for MinidumpModule {
1069 fn base_address(&self) -> u64 {
1070 self.raw.base_of_image
1071 }
1072 fn size(&self) -> u64 {
1073 self.raw.size_of_image as u64
1074 }
1075 fn code_file(&self) -> Cow<'_, str> {
1076 Cow::Borrowed(&self.name)
1077 }
1078
1079 fn code_identifier(&self) -> Option<CodeId> {
1080 match self.codeview_info {
1081 Some(CodeView::Pdb70(ref raw)) if matches!(self.os, Os::MacOs | Os::Ios) => {
1082 // MacOs uses PDB70 instead of its own dedicated format.
1083 // See the following issue for a potential MacOs-specific format:
1084 // https://github.com/rust-minidump/rust-minidump/issues/455
1085 Some(CodeId::new(format!("{:#}", raw.signature)))
1086 }
1087 Some(CodeView::Pdb20(_)) | Some(CodeView::Pdb70(_)) => Some(CodeId::new(format!(
1088 "{0:08X}{1:x}",
1089 self.raw.time_date_stamp, self.raw.size_of_image
1090 ))),
1091 Some(CodeView::Elf(ref raw)) => {
1092 // Return None instead of sentinel CodeIds for empty
1093 // `build_id`s. Non-executable mapped files like fonts or .jar
1094 // files will usually fall under this case.
1095 if raw.build_id.iter().all(|byte| *byte == 0) {
1096 None
1097 } else {
1098 Some(CodeId::from_binary(&raw.build_id))
1099 }
1100 }
1101 None if self.os == Os::Windows => {
1102 // Fall back to the timestamp + size-based debug-id for Windows.
1103 // Some Module records from Windows have no codeview record, but
1104 // the CodeId generated here is valid and can be looked up on
1105 // the Microsoft symbol server.
1106 // One example might be `wow64cpu.dll` with code-id `378BC3CDa000`.
1107 // This can however lead to "false positive" code-ids for modules
1108 // that have no timestamp, in which case the code-id looks extremely
1109 // low-entropy. The same can happen though if they *do* have a
1110 // codeview record.
1111 Some(CodeId::new(format!(
1112 "{0:08X}{1:x}",
1113 self.raw.time_date_stamp, self.raw.size_of_image
1114 )))
1115 }
1116 // Occasionally things will make it into the module stream that
1117 // shouldn't be there, and so no meaningful CodeId can be found from
1118 // those. One of those things are SysV shared memory segments which
1119 // have no CodeView record.
1120 _ => None,
1121 }
1122 }
1123 fn debug_file(&self) -> Option<Cow<'_, str>> {
1124 match self.codeview_info {
1125 Some(CodeView::Pdb70(ref raw)) => string_from_bytes_nul(&raw.pdb_file_name),
1126 Some(CodeView::Pdb20(ref raw)) => string_from_bytes_nul(&raw.pdb_file_name),
1127 Some(CodeView::Elf(_)) => Some(Cow::Borrowed(&self.name)),
1128 // TODO: support misc record? not really important.
1129 _ => None,
1130 }
1131 }
1132 fn debug_identifier(&self) -> Option<DebugId> {
1133 self.debug_id
1134 }
1135 fn version(&self) -> Option<Cow<'_, str>> {
1136 if self.raw.version_info.signature == md::VS_FFI_SIGNATURE
1137 && self.raw.version_info.struct_version == md::VS_FFI_STRUCVERSION
1138 {
1139 if matches!(self.os, Os::MacOs | Os::Ios | Os::Windows) {
1140 let ver = format!(
1141 "{}.{}.{}.{}",
1142 self.raw.version_info.file_version_hi >> 16,
1143 self.raw.version_info.file_version_hi & 0xffff,
1144 self.raw.version_info.file_version_lo >> 16,
1145 self.raw.version_info.file_version_lo & 0xffff
1146 );
1147 Some(Cow::Owned(ver))
1148 } else {
1149 // Assume Elf
1150 let ver = format!(
1151 "{}.{}.{}.{}",
1152 self.raw.version_info.file_version_hi,
1153 self.raw.version_info.file_version_lo,
1154 self.raw.version_info.product_version_hi,
1155 self.raw.version_info.product_version_lo
1156 );
1157 Some(Cow::Owned(ver))
1158 }
1159 } else {
1160 None
1161 }
1162 }
1163 }
1164
1165 impl MinidumpUnloadedModule {
1166 /// Create a `MinidumpUnloadedModule` with some basic info.
1167 ///
1168 /// Useful for testing.
1169 pub fn new(base: u64, size: u32, name: &str) -> MinidumpUnloadedModule {
1170 MinidumpUnloadedModule {
1171 raw: md::MINIDUMP_UNLOADED_MODULE {
1172 base_of_image: base,
1173 size_of_image: size,
1174 ..md::MINIDUMP_UNLOADED_MODULE::default()
1175 },
1176 name: String::from(name),
1177 }
1178 }
1179
1180 /// Read additional data to construct a `MinidumpUnloadedModule` from `bytes` using the information
1181 /// from the module list in `raw`.
1182 pub fn read(
1183 raw: md::MINIDUMP_UNLOADED_MODULE,
1184 bytes: &[u8],
1185 endian: scroll::Endian,
1186 ) -> Result<MinidumpUnloadedModule, Error> {
1187 let mut offset = raw.module_name_rva as usize;
1188 let name = read_string_utf16(&mut offset, bytes, endian).ok_or(Error::DataError)?;
1189 Ok(MinidumpUnloadedModule { raw, name })
1190 }
1191
1192 /// Write a human-readable description of this `MinidumpModule` to `f`.
1193 ///
1194 /// This is very verbose, it is the format used by `minidump_dump`.
1195 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
1196 write!(
1197 f,
1198 "MINIDUMP_UNLOADED_MODULE
1199 base_of_image = {:#x}
1200 size_of_image = {:#x}
1201 checksum = {:#x}
1202 time_date_stamp = {:#x} {}
1203 module_name_rva = {:#x}
1204 (code_file) = \"{}\"
1205 (code_identifier) = \"{}\"
1206 ",
1207 self.raw.base_of_image,
1208 self.raw.size_of_image,
1209 self.raw.checksum,
1210 self.raw.time_date_stamp,
1211 format_time_t(self.raw.time_date_stamp),
1212 self.raw.module_name_rva,
1213 self.code_file(),
1214 self.code_identifier().unwrap_or_default(),
1215 )?;
1216
1217 Ok(())
1218 }
1219
1220 fn memory_range(&self) -> Option<Range<u64>> {
1221 if self.size() == 0 {
1222 return None;
1223 }
1224 Some(Range::new(
1225 self.base_address(),
1226 self.base_address().checked_add(self.size())? - 1,
1227 ))
1228 }
1229 }
1230
1231 impl Module for MinidumpUnloadedModule {
1232 fn base_address(&self) -> u64 {
1233 self.raw.base_of_image
1234 }
1235 fn size(&self) -> u64 {
1236 self.raw.size_of_image as u64
1237 }
1238 fn code_file(&self) -> Cow<'_, str> {
1239 Cow::Borrowed(&self.name)
1240 }
1241 fn code_identifier(&self) -> Option<CodeId> {
1242 // TODO: This should be returning None if the unloaded module is coming
1243 // from a non-Windows minidump. We'll need info about the operating
1244 // system, ideally sourced from the SystemInfo to be able to do this.
1245 Some(CodeId::new(format!(
1246 "{0:08X}{1:x}",
1247 self.raw.time_date_stamp, self.raw.size_of_image
1248 )))
1249 }
1250 fn debug_file(&self) -> Option<Cow<'_, str>> {
1251 None
1252 }
1253 fn debug_identifier(&self) -> Option<DebugId> {
1254 None
1255 }
1256 fn version(&self) -> Option<Cow<'_, str>> {
1257 None
1258 }
1259 }
1260
1261 /// Parses X:Y or X=Y lists, skipping any blank/unparseable lines
1262 fn linux_list_iter(
1263 bytes: &[u8],
1264 separator: u8,
1265 ) -> impl Iterator<Item = (&LinuxOsStr, &LinuxOsStr)> {
1266 fn strip_quotes(input: &LinuxOsStr) -> &LinuxOsStr {
1267 // Remove any extra surrounding whitespace since formats are inconsistent on this.
1268 let input = input.trim_ascii_whitespace();
1269
1270 // Convert `"MyValue"` into `MyValue`, or just return the trimmed input.
1271 let output = input
1272 .strip_prefix(b"\"")
1273 .and_then(|input| input.strip_suffix(b"\""))
1274 .unwrap_or(input);
1275
1276 LinuxOsStr::from_bytes(output)
1277 }
1278
1279 let input = LinuxOsStr::from_bytes(bytes);
1280 input.lines().filter_map(move |line| {
1281 line.split_once(separator)
1282 .map(|(label, val)| (strip_quotes(label), (strip_quotes(val))))
1283 })
1284 }
1285
1286 fn read_stream_list<'a, T>(
1287 offset: &mut usize,
1288 bytes: &'a [u8],
1289 endian: scroll::Endian,
1290 ) -> Result<Vec<T>, Error>
1291 where
1292 T: TryFromCtx<'a, scroll::Endian, [u8], Error = scroll::Error>,
1293 T: SizeWith<scroll::Endian>,
1294 {
1295 let u: u32 = bytes
1296 .gread_with(offset, endian)
1297 .or(Err(Error::StreamReadFailure))?;
1298
1299 let (count, counted_size) = ensure_count_in_bound(
1300 bytes,
1301 u as usize,
1302 <T>::size_with(&endian),
1303 mem::size_of::<u32>(),
1304 )?;
1305
1306 match bytes.len() - counted_size {
1307 0 => {}
1308 4 => {
1309 // 4 bytes of padding.
1310 *offset += 4;
1311 }
1312 _ => {
1313 return Err(Error::StreamSizeMismatch {
1314 expected: counted_size,
1315 actual: bytes.len(),
1316 });
1317 }
1318 };
1319 // read count T raw stream entries
1320 let mut raw_entries = Vec::with_capacity(count);
1321 for _ in 0..count {
1322 let raw: T = bytes
1323 .gread_with(offset, endian)
1324 .or(Err(Error::StreamReadFailure))?;
1325 raw_entries.push(raw);
1326 }
1327 Ok(raw_entries)
1328 }
1329
1330 fn read_ex_stream_list<'a, T>(
1331 offset: &mut usize,
1332 bytes: &'a [u8],
1333 endian: scroll::Endian,
1334 ) -> Result<Vec<T>, Error>
1335 where
1336 T: TryFromCtx<'a, scroll::Endian, [u8], Error = scroll::Error>,
1337 T: SizeWith<scroll::Endian>,
1338 {
1339 // Some newer list streams have an extended header:
1340 //
1341 // size_of_header: u32,
1342 // size_of_entry: u32,
1343 // number_of_entries: u32,
1344 // ...entries
1345
1346 // In theory this allows the format of the stream to be extended without
1347 // us knowing how to handle the new parts.
1348
1349 let size_of_header: u32 = bytes
1350 .gread_with(offset, endian)
1351 .or(Err(Error::StreamReadFailure))?;
1352
1353 let size_of_entry: u32 = bytes
1354 .gread_with(offset, endian)
1355 .or(Err(Error::StreamReadFailure))?;
1356
1357 let number_of_entries: u32 = bytes
1358 .gread_with(offset, endian)
1359 .or(Err(Error::StreamReadFailure))?;
1360
1361 let expected_size_of_entry = <T>::size_with(&endian);
1362
1363 if size_of_entry as usize != expected_size_of_entry {
1364 // For now, conservatively bail out if entries don't have
1365 // the expected size. In theory we can assume entries are
1366 // always extended with new trailing fields, and this information
1367 // would let us walk over trailing fields we don't know about?
1368 // But without an example let's be safe.
1369 return Err(Error::StreamReadFailure);
1370 }
1371
1372 let (number_of_entries, _) = ensure_count_in_bound(
1373 bytes,
1374 number_of_entries as usize,
1375 size_of_entry as usize,
1376 size_of_header as usize,
1377 )?;
1378
1379 let header_padding = match (size_of_header as usize).checked_sub(*offset) {
1380 Some(s) => s,
1381 None => return Err(Error::StreamReadFailure),
1382 };
1383 *offset += header_padding;
1384
1385 // read count T raw stream entries
1386 let mut raw_entries = Vec::with_capacity(number_of_entries);
1387 for _ in 0..number_of_entries {
1388 let raw: T = bytes
1389 .gread_with(offset, endian)
1390 .or(Err(Error::StreamReadFailure))?;
1391 raw_entries.push(raw);
1392 }
1393 Ok(raw_entries)
1394 }
1395
1396 impl<'a> MinidumpStream<'a> for MinidumpThreadNames {
1397 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::ThreadNamesStream as u32;
1398
1399 fn read(
1400 bytes: &'a [u8],
1401 all: &'a [u8],
1402 endian: scroll::Endian,
1403 _system_info: Option<&MinidumpSystemInfo>,
1404 ) -> Result<Self, Error> {
1405 let mut offset = 0;
1406 let raw_names: Vec<md::MINIDUMP_THREAD_NAME> =
1407 read_stream_list(&mut offset, bytes, endian)?;
1408 // read out the actual names
1409 let mut names = BTreeMap::new();
1410 for raw_name in raw_names {
1411 let mut offset = raw_name.thread_name_rva as usize;
1412 // Better to just drop unreadable names individually than the whole stream.
1413 if let Some(name) = read_string_utf16(&mut offset, all, endian) {
1414 names.insert(raw_name.thread_id, name);
1415 } else {
1416 warn!(
1417 "Couldn't read thread name for thread id {}",
1418 raw_name.thread_id
1419 );
1420 }
1421 }
1422 Ok(MinidumpThreadNames { names })
1423 }
1424 }
1425
1426 impl MinidumpThreadNames {
1427 pub fn get_name(&self, thread_id: u32) -> Option<Cow<str>> {
1428 self.names
1429 .get(&thread_id)
1430 .map(|name| Cow::Borrowed(&**name))
1431 }
1432
1433 /// Write a human-readable description of this `MinidumpThreadNames` to `f`.
1434 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
1435 write!(
1436 f,
1437 "MinidumpThreadNames
1438 thread_count = {}
1439
1440 ",
1441 self.names.len()
1442 )?;
1443 for (i, (thread_id, name)) in self.names.iter().enumerate() {
1444 writeln!(
1445 f,
1446 "thread_name[{i}]
1447 MINIDUMP_THREAD_NAME
1448 thread_id = {thread_id:#x}
1449 name = \"{name}\"
1450 "
1451 )?;
1452 }
1453
1454 Ok(())
1455 }
1456 }
1457
1458 impl MinidumpModuleList {
1459 /// Return an empty `MinidumpModuleList`.
1460 pub fn new() -> MinidumpModuleList {
1461 MinidumpModuleList {
1462 modules: vec![],
1463 modules_by_addr: RangeMap::new(),
1464 }
1465 }
1466 /// Create a `MinidumpModuleList` from a list of `MinidumpModule`s.
1467 pub fn from_modules(modules: Vec<MinidumpModule>) -> MinidumpModuleList {
1468 let modules_by_addr = modules
1469 .iter()
1470 .enumerate()
1471 .map(|(i, module)| (module.memory_range(), i))
1472 .into_rangemap_safe();
1473 MinidumpModuleList {
1474 modules,
1475 modules_by_addr,
1476 }
1477 }
1478
1479 /// Returns the module corresponding to the main executable.
1480 pub fn main_module(&self) -> Option<&MinidumpModule> {
1481 // The main code module is the first one present in a minidump file's
1482 // MINIDUMP_MODULEList.
1483 if !self.modules.is_empty() {
1484 Some(&self.modules[0])
1485 } else {
1486 None
1487 }
1488 }
1489
1490 /// Return a `MinidumpModule` whose address range covers `address`.
1491 pub fn module_at_address(&self, address: u64) -> Option<&MinidumpModule> {
1492 self.modules_by_addr
1493 .get(address)
1494 .map(|&index| &self.modules[index])
1495 }
1496
1497 /// Iterate over the modules in arbitrary order.
1498 pub fn iter(&self) -> impl Iterator<Item = &MinidumpModule> {
1499 self.modules.iter()
1500 }
1501
1502 /// Iterate over the modules in order by memory address.
1503 pub fn by_addr(&self) -> impl DoubleEndedIterator<Item = &MinidumpModule> {
1504 self.modules_by_addr
1505 .ranges_values()
1506 .map(move |&(_, index)| &self.modules[index])
1507 }
1508
1509 /// Write a human-readable description of this `MinidumpModuleList` to `f`.
1510 ///
1511 /// This is very verbose, it is the format used by `minidump_dump`.
1512 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
1513 write!(
1514 f,
1515 "MinidumpModuleList
1516 module_count = {}
1517
1518 ",
1519 self.modules.len()
1520 )?;
1521 for (i, module) in self.modules.iter().enumerate() {
1522 writeln!(f, "module[{i}]")?;
1523 module.print(f)?;
1524 }
1525 Ok(())
1526 }
1527 }
1528
1529 impl Default for MinidumpModuleList {
1530 fn default() -> Self {
1531 Self::new()
1532 }
1533 }
1534
1535 impl<'a> MinidumpStream<'a> for MinidumpModuleList {
1536 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::ModuleListStream as u32;
1537
1538 fn read(
1539 bytes: &'a [u8],
1540 all: &'a [u8],
1541 endian: scroll::Endian,
1542 system_info: Option<&MinidumpSystemInfo>,
1543 ) -> Result<MinidumpModuleList, Error> {
1544 let mut offset = 0;
1545 let raw_modules: Vec<md::MINIDUMP_MODULE> = read_stream_list(&mut offset, bytes, endian)?;
1546 // read auxiliary data for each module
1547 let mut modules = Vec::with_capacity(raw_modules.len());
1548 for (module_index, raw) in raw_modules.into_iter().enumerate() {
1549 if raw.size_of_image == 0 || raw.size_of_image as u64 > (u64::MAX - raw.base_of_image) {
1550 // Bad image size.
1551 tracing::warn!(
1552 module_index,
1553 base = raw.base_of_image,
1554 size = raw.size_of_image,
1555 "bad module image size"
1556 );
1557 continue;
1558 }
1559 modules.push(MinidumpModule::read(raw, all, endian, system_info)?);
1560 }
1561 Ok(MinidumpModuleList::from_modules(modules))
1562 }
1563 }
1564
1565 impl MinidumpUnloadedModuleList {
1566 /// Return an empty `MinidumpModuleList`.
1567 pub fn new() -> MinidumpUnloadedModuleList {
1568 MinidumpUnloadedModuleList {
1569 modules: vec![],
1570 modules_by_addr: vec![],
1571 }
1572 }
1573 /// Create a `MinidumpModuleList` from a list of `MinidumpModule`s.
1574 pub fn from_modules(modules: Vec<MinidumpUnloadedModule>) -> MinidumpUnloadedModuleList {
1575 let mut modules_by_addr = (0..modules.len())
1576 .filter_map(|i| modules[i].memory_range().map(|r| (r, i)))
1577 .collect::<Vec<_>>();
1578
1579 modules_by_addr.sort_by_key(|(range, _idx)| *range);
1580
1581 MinidumpUnloadedModuleList {
1582 modules,
1583 modules_by_addr,
1584 }
1585 }
1586
1587 /// Return an iterator of `MinidumpUnloadedModules` whose address range covers `address`.
1588 pub fn modules_at_address(
1589 &self,
1590 address: u64,
1591 ) -> impl Iterator<Item = &MinidumpUnloadedModule> {
1592 // We have all of our modules sorted by memory range (base address being the
1593 // high-order value), and we need to get the range of values that overlap
1594 // with our target address. I'm a bit too tired to work out the exact
1595 // combination of binary searches to do this, so let's just use `filter`
1596 // for now (unloaded_modules should be a bounded list anyway).
1597 self.modules_by_addr
1598 .iter()
1599 .filter(move |(range, _idx)| range.contains(address))
1600 .map(move |(_range, idx)| &self.modules[*idx])
1601 }
1602
1603 /// Iterate over the modules in arbitrary order.
1604 pub fn iter(&self) -> impl Iterator<Item = &MinidumpUnloadedModule> {
1605 self.modules.iter()
1606 }
1607
1608 /// Iterate over the modules in order by memory address.
1609 pub fn by_addr(&self) -> impl Iterator<Item = &MinidumpUnloadedModule> {
1610 self.modules_by_addr
1611 .iter()
1612 .map(move |&(_, index)| &self.modules[index])
1613 }
1614
1615 /// Write a human-readable description of this `MinidumpModuleList` to `f`.
1616 ///
1617 /// This is very verbose, it is the format used by `minidump_dump`.
1618 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
1619 write!(
1620 f,
1621 "MinidumpUnloadedModuleList
1622 module_count = {}
1623
1624 ",
1625 self.modules.len()
1626 )?;
1627 for (i, module) in self.modules.iter().enumerate() {
1628 writeln!(f, "module[{i}]")?;
1629 module.print(f)?;
1630 }
1631 Ok(())
1632 }
1633 }
1634
1635 impl Default for MinidumpUnloadedModuleList {
1636 fn default() -> Self {
1637 Self::new()
1638 }
1639 }
1640
1641 impl<'a> MinidumpStream<'a> for MinidumpUnloadedModuleList {
1642 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::UnloadedModuleListStream as u32;
1643
1644 fn read(
1645 bytes: &'a [u8],
1646 all: &'a [u8],
1647 endian: scroll::Endian,
1648 _system_info: Option<&MinidumpSystemInfo>,
1649 ) -> Result<MinidumpUnloadedModuleList, Error> {
1650 let mut offset = 0;
1651 let raw_modules: Vec<md::MINIDUMP_UNLOADED_MODULE> =
1652 read_ex_stream_list(&mut offset, bytes, endian)?;
1653 // read auxiliary data for each module
1654 let mut modules = Vec::with_capacity(raw_modules.len());
1655 for raw in raw_modules.into_iter() {
1656 if raw.size_of_image == 0 || raw.size_of_image as u64 > (u64::MAX - raw.base_of_image) {
1657 // Bad image size.
1658 // TODO: just drop this module, keep the rest?
1659 return Err(Error::ModuleReadFailure);
1660 }
1661 modules.push(MinidumpUnloadedModule::read(raw, all, endian)?);
1662 }
1663 Ok(MinidumpUnloadedModuleList::from_modules(modules))
1664 }
1665 }
1666
1667 // Generates an accessor for a HANDLE_DESCRIPTOR field with the following syntax:
1668 //
1669 // * VERSION_NUMBER: FIELD_NAME -> FIELD_TYPE
1670 //
1671 // With the following definitions:
1672 //
1673 // * VERSION_NUMBER: The HANDLE_DESCRIPTOR version this field was introduced in
1674 // * FIELD_NAME: The name of the field to read
1675 // * FIELD_TYPE: The type of the field
1676 macro_rules! handle_descriptor_accessors {
1677 () => {};
1678 (@def $name:ident $t:ty [$($variant:ident)+]) => {
1679 #[allow(unreachable_patterns)]
1680 pub fn $name(&self) -> Option<&$t> {
1681 match self {
1682 $(
1683 RawHandleDescriptor::$variant(ref raw) => Some(&raw.$name),
1684 )+
1685 _ => None,
1686 }
1687 }
1688 };
1689 (1: $name:ident -> $t:ty, $($rest:tt)*) => {
1690 handle_descriptor_accessors!(@def $name $t [HandleDescriptor HandleDescriptor2]);
1691 handle_descriptor_accessors!($($rest)*);
1692 };
1693
1694 (2: $name:ident -> $t:ty, $($rest:tt)*) => {
1695 handle_descriptor_accessors!(@def $name $t [HandleDescriptor2]);
1696 handle_descriptor_accessors!($($rest)*);
1697 };
1698 }
1699
1700 impl RawHandleDescriptor {
1701 handle_descriptor_accessors!(
1702 1: handle -> u64,
1703 1: type_name_rva -> md::RVA,
1704 1: object_name_rva -> md::RVA,
1705 1: attributes -> u32,
1706 1: granted_access -> u32,
1707 1: handle_count -> u32,
1708 1: pointer_count -> u32,
1709 2: object_info_rva -> md::RVA,
1710 );
1711 }
1712
1713 impl MinidumpHandleDescriptor {
1714 /// Write a human-readable description.
1715 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
1716 macro_rules! write_simple_field {
1717 ($stream:ident, $field:ident, $format:literal) => {
1718 write!(f, " {:18}= ", stringify!($field))?;
1719 match self.raw.$field() {
1720 Some($field) => {
1721 writeln!(f, $format, $field)?;
1722 }
1723 None => writeln!(f, "(invalid)")?,
1724 }
1725 };
1726 ($stream:ident, $field:ident) => {
1727 write_simple_field!($stream, $field, "{}");
1728 };
1729 }
1730
1731 writeln!(f, "MINIDUMP_HANDLE_DESCRIPTOR")?;
1732 write_simple_field!(f, handle, "{:#x}");
1733 write_simple_field!(f, type_name_rva, "{:#x}");
1734 write_simple_field!(f, object_name_rva, "{:#x}");
1735 write_simple_field!(f, attributes, "{:#x}");
1736 write_simple_field!(f, granted_access, "{:#x}");
1737 write_simple_field!(f, handle_count);
1738 write_simple_field!(f, pointer_count);
1739 write_simple_field!(f, object_info_rva, "{:#x}");
1740 write!(f, " (type_name) = ")?;
1741 if let Some(type_name) = &self.type_name {
1742 writeln!(f, "{type_name:}")?;
1743 } else {
1744 writeln!(f, "(null)")?;
1745 };
1746 write!(f, " (object_name) = ")?;
1747 if let Some(object_name) = &self.object_name {
1748 writeln!(f, "{object_name:}")?;
1749 } else {
1750 writeln!(f, "(null)")?;
1751 };
1752 if self.object_infos.is_empty() {
1753 writeln!(f, " (object_info) = (null)")?;
1754 } else {
1755 for object_info in &self.object_infos {
1756 writeln!(f, " (object_info) = {object_info:}")?;
1757 }
1758 }
1759 writeln!(f)
1760 }
1761
1762 fn read_string(offset: usize, ctx: HandleDescriptorContext) -> Option<String> {
1763 let mut offset = offset;
1764 if offset != 0 {
1765 read_string_utf16(&mut offset, ctx.bytes, ctx.endianess)
1766 } else {
1767 None
1768 }
1769 }
1770
1771 fn read_object_info(
1772 offset: usize,
1773 ctx: HandleDescriptorContext,
1774 ) -> Option<MinidumpHandleObjectInformation> {
1775 if offset != 0 {
1776 ctx.bytes
1777 .pread_with::<md::MINIDUMP_HANDLE_OBJECT_INFORMATION>(offset, ctx.endianess)
1778 .ok()
1779 .map(|raw| MinidumpHandleObjectInformation {
1780 raw: raw.clone(),
1781 info_type: md::MINIDUMP_HANDLE_OBJECT_INFORMATION_TYPE::from_u32(raw.info_type)
1782 .unwrap(),
1783 })
1784 } else {
1785 None
1786 }
1787 }
1788 }
1789
1790 #[derive(Copy, Clone)]
1791 struct HandleDescriptorContext<'a> {
1792 bytes: &'a [u8],
1793 fieldsize: u32,
1794 endianess: scroll::Endian,
1795 }
1796
1797 impl<'a> HandleDescriptorContext<'a> {
1798 fn new(
1799 bytes: &'a [u8],
1800 fieldsize: u32,
1801 endianess: scroll::Endian,
1802 ) -> HandleDescriptorContext<'a> {
1803 HandleDescriptorContext {
1804 bytes,
1805 fieldsize,
1806 endianess,
1807 }
1808 }
1809 }
1810
1811 impl<'a> TryFromCtx<'a, HandleDescriptorContext<'a>> for MinidumpHandleDescriptor {
1812 type Error = scroll::Error;
1813
1814 fn try_from_ctx(
1815 src: &'a [u8],
1816 ctx: HandleDescriptorContext,
1817 ) -> Result<(Self, usize), Self::Error> {
1818 const MINIDUMP_HANDLE_DESCRIPTOR_SIZE: u32 =
1819 mem::size_of::<md::MINIDUMP_HANDLE_DESCRIPTOR>() as u32;
1820 const MINIDUMP_HANDLE_DESCRIPTOR_2_SIZE: u32 =
1821 mem::size_of::<md::MINIDUMP_HANDLE_DESCRIPTOR_2>() as u32;
1822
1823 match ctx.fieldsize {
1824 MINIDUMP_HANDLE_DESCRIPTOR_SIZE => {
1825 let raw = src.pread_with::<md::MINIDUMP_HANDLE_DESCRIPTOR>(0, ctx.endianess)?;
1826 let type_name = Self::read_string(raw.type_name_rva as usize, ctx);
1827 let object_name = Self::read_string(raw.object_name_rva as usize, ctx);
1828 Ok((
1829 MinidumpHandleDescriptor {
1830 raw: RawHandleDescriptor::HandleDescriptor(raw),
1831 type_name,
1832 object_name,
1833 object_infos: Vec::new(),
1834 },
1835 ctx.fieldsize as usize,
1836 ))
1837 }
1838 MINIDUMP_HANDLE_DESCRIPTOR_2_SIZE => {
1839 let raw = src.pread_with::<md::MINIDUMP_HANDLE_DESCRIPTOR_2>(0, ctx.endianess)?;
1840 let type_name = Self::read_string(raw.type_name_rva as usize, ctx);
1841 let object_name = Self::read_string(raw.object_name_rva as usize, ctx);
1842 let mut object_infos = Vec::<MinidumpHandleObjectInformation>::new();
1843 let mut object_info_rva = raw.object_info_rva;
1844
1845 while object_info_rva != 0 {
1846 if let Some(object_info) = Self::read_object_info(object_info_rva as usize, ctx)
1847 {
1848 object_info_rva = object_info.raw.next_info_rva;
1849 object_infos.push(object_info);
1850 } else {
1851 break;
1852 }
1853 }
1854
1855 Ok((
1856 MinidumpHandleDescriptor {
1857 raw: RawHandleDescriptor::HandleDescriptor2(raw),
1858 type_name,
1859 object_name,
1860 object_infos,
1861 },
1862 ctx.fieldsize as usize,
1863 ))
1864 }
1865 _ => Err(scroll::Error::BadInput {
1866 size: ctx.fieldsize as usize,
1867 msg: "Unknown MINIDUMP_HANDLE_DESCRIPTOR type",
1868 }),
1869 }
1870 }
1871 }
1872
1873 impl MinidumpHandleDataStream {
1874 /// Return an empty `MinidumpHandleDataStream`.
1875 pub fn new() -> MinidumpHandleDataStream {
1876 MinidumpHandleDataStream { handles: vec![] }
1877 }
1878
1879 /// Create a `MinidumpHandleDataStream` from a list of `MinidumpHandleDescriptor`s.
1880 pub fn from_handles(handles: Vec<MinidumpHandleDescriptor>) -> MinidumpHandleDataStream {
1881 MinidumpHandleDataStream { handles }
1882 }
1883
1884 /// Iterate over the handles in the order contained in the minidump.
1885 pub fn iter(&self) -> impl Iterator<Item = &MinidumpHandleDescriptor> {
1886 self.handles.iter()
1887 }
1888
1889 /// Write a human-readable description.
1890 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
1891 write!(
1892 f,
1893 "MinidumpHandleDataStream
1894 handle_count = {}
1895
1896 ",
1897 self.handles.len()
1898 )?;
1899 for (i, handle) in self.handles.iter().enumerate() {
1900 writeln!(f, "handle[{i}]")?;
1901 handle.print(f)?;
1902 }
1903 Ok(())
1904 }
1905 }
1906
1907 impl Default for MinidumpHandleDataStream {
1908 fn default() -> Self {
1909 Self::new()
1910 }
1911 }
1912
1913 impl<'a> MinidumpStream<'a> for MinidumpHandleDataStream {
1914 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::HandleDataStream as u32;
1915
1916 fn read(
1917 bytes: &'a [u8],
1918 all: &'a [u8],
1919 endian: scroll::Endian,
1920 _system_info: Option<&MinidumpSystemInfo>,
1921 ) -> Result<MinidumpHandleDataStream, Error> {
1922 let mut offset = 0;
1923
1924 let size_of_header = bytes
1925 .gread_with::<u32>(&mut offset, endian)
1926 .or(Err(Error::StreamReadFailure))?;
1927 let size_of_descriptor = bytes
1928 .gread_with::<u32>(&mut offset, endian)
1929 .or(Err(Error::StreamReadFailure))?;
1930 let number_of_descriptors = bytes
1931 .gread_with::<u32>(&mut offset, endian)
1932 .or(Err(Error::StreamReadFailure))?;
1933
1934 let ctx = HandleDescriptorContext::new(all, size_of_descriptor, endian);
1935 let (number_of_entries, _) = ensure_count_in_bound(
1936 bytes,
1937 number_of_descriptors as usize,
1938 size_of_descriptor as usize,
1939 size_of_header as usize,
1940 )?;
1941
1942 // Skip the header
1943 offset = size_of_header as usize;
1944
1945 let mut descriptors = Vec::<MinidumpHandleDescriptor>::with_capacity(number_of_entries);
1946 for _ in 0..number_of_entries {
1947 let descriptor: MinidumpHandleDescriptor = bytes
1948 .gread_with(&mut offset, ctx)
1949 .or(Err(Error::StreamReadFailure))?;
1950 descriptors.push(descriptor);
1951 }
1952
1953 Ok(MinidumpHandleDataStream::from_handles(descriptors))
1954 }
1955 }
1956
1957 impl<'a> MinidumpMemory<'a> {
1958 pub fn read(
1959 desc: &md::MINIDUMP_MEMORY_DESCRIPTOR,
1960 data: &'a [u8],
1961 endian: scroll::Endian,
1962 ) -> Result<MinidumpMemory<'a>, Error> {
1963 if desc.memory.rva == 0 || desc.memory.data_size == 0 {
1964 // Windows will sometimes emit null stack RVAs, indicating that
1965 // we need to lookup the address in a memory region. It's ok to
1966 // emit an error for that here, the thread processing code will
1967 // catch it.
1968 return Err(Error::MemoryReadFailure);
1969 }
1970 let bytes = location_slice(data, &desc.memory).or(Err(Error::StreamReadFailure))?;
1971 Ok(MinidumpMemory {
1972 desc: *desc,
1973 base_address: desc.start_of_memory_range,
1974 size: desc.memory.data_size as u64,
1975 bytes,
1976 endian,
1977 })
1978 }
1979
1980 /// Write a human-readable description of this `MinidumpMemory` to `f`.
1981 ///
1982 /// This is very verbose, it is the format used by `minidump_dump`.
1983 pub fn print<T: Write>(&self, f: &mut T, brief: bool) -> io::Result<()> {
1984 write!(
1985 f,
1986 "MINIDUMP_MEMORY_DESCRIPTOR
1987 start_of_memory_range = {:#x}
1988 memory.data_size = {:#x}
1989 memory.rva = {:#x}
1990 ",
1991 self.desc.start_of_memory_range, self.desc.memory.data_size, self.desc.memory.rva,
1992 )?;
1993 if !brief {
1994 writeln!(f, "Memory")?;
1995 self.print_contents(f)?;
1996 }
1997 writeln!(f)
1998 }
1999 }
2000
2001 impl MinidumpMemory64<'_> {
2002 /// Write a human-readable description of this `MinidumpMemory64` to `f`.
2003 ///
2004 /// This is very verbose, it is the format used by `minidump_dump`.
2005 pub fn print<T: Write>(&self, f: &mut T, brief: bool) -> io::Result<()> {
2006 write!(
2007 f,
2008 "MINIDUMP_MEMORY_DESCRIPTOR64
2009 start_of_memory_range = {:#x}
2010 memory.data_size = {:#x}
2011 ",
2012 self.desc.start_of_memory_range, self.desc.data_size,
2013 )?;
2014 if !brief {
2015 writeln!(f, "Memory")?;
2016 self.print_contents(f)?;
2017 }
2018 writeln!(f)
2019 }
2020 }
2021
2022 impl<'a, Descriptor> MinidumpMemoryBase<'a, Descriptor> {
2023 /// Get `mem::size_of::<T>()` bytes of memory at `addr` from this region.
2024 ///
2025 /// Return `None` if the requested address range falls out of the bounds
2026 /// of this memory region.
2027 pub fn get_memory_at_address<T>(&self, addr: u64) -> Option<T>
2028 where
2029 T: TryFromCtx<'a, scroll::Endian, [u8], Error = scroll::Error>,
2030 {
2031 let start = addr.checked_sub(self.base_address)? as usize;
2032
2033 self.bytes.pread_with::<T>(start, self.endian).ok()
2034 }
2035
2036 /// Write the contents of this `MinidumpMemory` to `f` as a hex string.
2037 pub fn print_contents<T: Write>(&self, f: &mut T) -> io::Result<()> {
2038 const PARAGRAPH_SIZE: usize = 16;
2039 let mut offset = 0;
2040 for paragraph in self.bytes.chunks(PARAGRAPH_SIZE) {
2041 write!(f, " {offset:08x}: ")?;
2042 let mut byte_iter = paragraph.iter().fuse();
2043 for _ in 0..PARAGRAPH_SIZE {
2044 if let Some(byte) = byte_iter.next() {
2045 write!(f, "{byte:02x} ")?;
2046 } else {
2047 write!(f, " ")?;
2048 }
2049 }
2050 for &byte in paragraph.iter() {
2051 let ascii_char = if !byte.is_ascii() || byte.is_ascii_control() {
2052 '.'
2053 } else {
2054 char::from(byte)
2055 };
2056
2057 write!(f, "{ascii_char}")?;
2058 }
2059 writeln!(f)?;
2060
2061 offset += PARAGRAPH_SIZE;
2062 }
2063 Ok(())
2064 }
2065
2066 pub fn memory_range(&self) -> Option<Range<u64>> {
2067 if self.size == 0 {
2068 return None;
2069 }
2070 Some(Range::new(
2071 self.base_address,
2072 self.base_address.checked_add(self.size)? - 1,
2073 ))
2074 }
2075 }
2076
2077 impl<'a, 'mdmp> UnifiedMemory<'a, 'mdmp> {
2078 pub fn get_memory_at_address<T>(&self, addr: u64) -> Option<T>
2079 where
2080 T: TryFromCtx<'mdmp, scroll::Endian, [u8], Error = scroll::Error>,
2081 {
2082 match self {
2083 UnifiedMemory::Memory(this) => this.get_memory_at_address(addr),
2084 UnifiedMemory::Memory64(this) => this.get_memory_at_address(addr),
2085 }
2086 }
2087
2088 pub fn memory_range(&self) -> Option<Range<u64>> {
2089 match self {
2090 UnifiedMemory::Memory(this) => this.memory_range(),
2091 UnifiedMemory::Memory64(this) => this.memory_range(),
2092 }
2093 }
2094
2095 pub fn bytes(&self) -> &'a [u8] {
2096 match self {
2097 UnifiedMemory::Memory(this) => this.bytes,
2098 UnifiedMemory::Memory64(this) => this.bytes,
2099 }
2100 }
2101
2102 pub fn base_address(&self) -> u64 {
2103 match self {
2104 UnifiedMemory::Memory(this) => this.base_address,
2105 UnifiedMemory::Memory64(this) => this.base_address,
2106 }
2107 }
2108
2109 pub fn size(&self) -> u64 {
2110 match self {
2111 UnifiedMemory::Memory(this) => this.size,
2112 UnifiedMemory::Memory64(this) => this.size,
2113 }
2114 }
2115
2116 pub fn print_contents<T: Write>(&self, f: &mut T) -> io::Result<()> {
2117 match self {
2118 UnifiedMemory::Memory(this) => this.print_contents(f),
2119 UnifiedMemory::Memory64(this) => this.print_contents(f),
2120 }
2121 }
2122
2123 pub fn print<T: Write>(&self, f: &mut T, brief: bool) -> io::Result<()> {
2124 match self {
2125 UnifiedMemory::Memory(this) => this.print(f, brief),
2126 UnifiedMemory::Memory64(this) => this.print(f, brief),
2127 }
2128 }
2129 }
2130
2131 impl<'mdmp, Descriptor> MinidumpMemoryListBase<'mdmp, Descriptor> {
2132 /// Return an empty `MinidumpMemoryListBase`.
2133 pub fn new() -> MinidumpMemoryListBase<'mdmp, Descriptor> {
2134 MinidumpMemoryListBase {
2135 regions: vec![],
2136 regions_by_addr: RangeMap::new(),
2137 }
2138 }
2139
2140 /// Create a `MinidumpMemoryListBase` from a list of `MinidumpMemoryBase`s.
2141 pub fn from_regions(
2142 regions: Vec<MinidumpMemoryBase<'mdmp, Descriptor>>,
2143 ) -> MinidumpMemoryListBase<'mdmp, Descriptor> {
2144 let regions_by_addr = regions
2145 .iter()
2146 .enumerate()
2147 .map(|(i, region)| (region.memory_range(), i))
2148 .into_rangemap_safe();
2149 MinidumpMemoryListBase {
2150 regions,
2151 regions_by_addr,
2152 }
2153 }
2154
2155 /// Return a `MinidumpMemoryBase` containing memory at `address`, if one exists.
2156 pub fn memory_at_address(
2157 &self,
2158 address: u64,
2159 ) -> Option<&MinidumpMemoryBase<'mdmp, Descriptor>> {
2160 self.regions_by_addr
2161 .get(address)
2162 .and_then(|&index| self.regions.get(index))
2163 }
2164
2165 /// Iterate over the memory regions in the order contained in the minidump.
2166 ///
2167 /// The iterator returns items of [MinidumpMemoryBase] as `&'slf MinidumpMemoryBase<'mdmp, Descriptor>`.
2168 /// That is the lifetime of the item is bound to the lifetime of the iterator itself
2169 /// (`'slf`), while the slice inside [MinidumpMemoryBase] pointing at the memory itself has
2170 /// the lifetime of the [Minidump] struct ('mdmp).
2171 pub fn iter<'slf>(
2172 &'slf self,
2173 ) -> impl Iterator<Item = &'slf MinidumpMemoryBase<'mdmp, Descriptor>> {
2174 self.regions.iter()
2175 }
2176
2177 /// Iterate over the memory regions in order by memory address.
2178 pub fn by_addr<'slf>(
2179 &'slf self,
2180 ) -> impl Iterator<Item = &'slf MinidumpMemoryBase<'mdmp, Descriptor>> {
2181 self.regions_by_addr
2182 .ranges_values()
2183 .map(move |&(_, index)| &self.regions[index])
2184 }
2185 }
2186
2187 impl MinidumpMemoryList<'_> {
2188 /// Write a human-readable description of this `MinidumpMemoryList` to `f`.
2189 ///
2190 /// This is very verbose, it is the format used by `minidump_dump`.
2191 pub fn print<T: Write>(&self, f: &mut T, brief: bool) -> io::Result<()> {
2192 write!(
2193 f,
2194 "MinidumpMemoryList
2195 region_count = {}
2196
2197 ",
2198 self.regions.len()
2199 )?;
2200 for (i, region) in self.regions.iter().enumerate() {
2201 writeln!(f, "region[{i}]")?;
2202 region.print(f, brief)?;
2203 }
2204 Ok(())
2205 }
2206 }
2207
2208 impl MinidumpMemory64List<'_> {
2209 /// Write a human-readable description of this `MinidumpMemory64List` to `f`.
2210 ///
2211 /// This is very verbose, it is the format used by `minidump_dump`.
2212 pub fn print<T: Write>(&self, f: &mut T, brief: bool) -> io::Result<()> {
2213 write!(
2214 f,
2215 "MinidumpMemory64List
2216 region_count = {}
2217
2218 ",
2219 self.regions.len()
2220 )?;
2221 for (i, region) in self.regions.iter().enumerate() {
2222 writeln!(f, "region[{i}]")?;
2223 region.print(f, brief)?;
2224 }
2225 Ok(())
2226 }
2227 }
2228
2229 impl<'mdmp> UnifiedMemoryList<'mdmp> {
2230 pub fn memory_at_address<'slf>(&'slf self, address: u64) -> Option<UnifiedMemory<'slf, 'mdmp>> {
2231 match self {
2232 UnifiedMemoryList::Memory(this) => {
2233 this.memory_at_address(address).map(UnifiedMemory::Memory)
2234 }
2235 UnifiedMemoryList::Memory64(this) => {
2236 this.memory_at_address(address).map(UnifiedMemory::Memory64)
2237 }
2238 }
2239 }
2240
2241 pub fn iter<'slf>(&'slf self) -> impl Iterator<Item = UnifiedMemory<'slf, 'mdmp>> {
2242 let iter1 = if let UnifiedMemoryList::Memory(this) = self {
2243 Some(this.iter().map(UnifiedMemory::Memory))
2244 } else {
2245 None
2246 };
2247 let iter2 = if let UnifiedMemoryList::Memory64(this) = self {
2248 Some(this.iter().map(UnifiedMemory::Memory64))
2249 } else {
2250 None
2251 };
2252 iter1
2253 .into_iter()
2254 .flatten()
2255 .chain(iter2.into_iter().flatten())
2256 }
2257
2258 /// Iterate over the memory regions in order by memory address.
2259 pub fn by_addr<'slf>(&'slf self) -> impl Iterator<Item = UnifiedMemory<'slf, 'mdmp>> {
2260 let iter1 = if let UnifiedMemoryList::Memory(this) = self {
2261 Some(this.by_addr().map(UnifiedMemory::Memory))
2262 } else {
2263 None
2264 };
2265 let iter2 = if let UnifiedMemoryList::Memory64(this) = self {
2266 Some(this.by_addr().map(UnifiedMemory::Memory64))
2267 } else {
2268 None
2269 };
2270 iter1
2271 .into_iter()
2272 .flatten()
2273 .chain(iter2.into_iter().flatten())
2274 }
2275
2276 pub fn print<T: Write>(&self, f: &mut T, brief: bool) -> io::Result<()> {
2277 match self {
2278 UnifiedMemoryList::Memory(this) => this.print(f, brief),
2279 UnifiedMemoryList::Memory64(this) => this.print(f, brief),
2280 }
2281 }
2282 }
2283
2284 impl<Descriptor> Default for MinidumpMemoryListBase<'_, Descriptor> {
2285 fn default() -> Self {
2286 Self::new()
2287 }
2288 }
2289
2290 impl<'a> MinidumpStream<'a> for MinidumpMemoryList<'a> {
2291 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::MemoryListStream as u32;
2292
2293 fn read(
2294 bytes: &'a [u8],
2295 all: &'a [u8],
2296 endian: scroll::Endian,
2297 _system_info: Option<&MinidumpSystemInfo>,
2298 ) -> Result<MinidumpMemoryList<'a>, Error> {
2299 let mut offset = 0;
2300 let descriptors: Vec<md::MINIDUMP_MEMORY_DESCRIPTOR> =
2301 read_stream_list(&mut offset, bytes, endian)?;
2302 // read memory contents for each region
2303 let mut regions = Vec::with_capacity(descriptors.len());
2304 for raw in descriptors.into_iter() {
2305 if let Ok(memory) = MinidumpMemory::read(&raw, all, endian) {
2306 regions.push(memory);
2307 } else {
2308 // Just skip over corrupt entries and try to limp along.
2309 continue;
2310 }
2311 }
2312 Ok(MinidumpMemoryList::from_regions(regions))
2313 }
2314 }
2315
2316 impl<'a> MinidumpStream<'a> for MinidumpMemory64List<'a> {
2317 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::Memory64ListStream as u32;
2318
2319 fn read(
2320 bytes: &'a [u8],
2321 all: &'a [u8],
2322 endian: scroll::Endian,
2323 _system_info: Option<&MinidumpSystemInfo>,
2324 ) -> Result<MinidumpMemory64List<'a>, Error> {
2325 let mut offset = 0;
2326 let u: u64 = bytes
2327 .gread_with(&mut offset, endian)
2328 .or(Err(Error::StreamReadFailure))?;
2329
2330 let mut rva: u64 = bytes
2331 .gread_with(&mut offset, endian)
2332 .or(Err(Error::StreamReadFailure))?;
2333
2334 let (count, counted_size) = ensure_count_in_bound(
2335 bytes,
2336 u.try_into().map_err(|_| Error::StreamReadFailure)?,
2337 md::MINIDUMP_MEMORY_DESCRIPTOR64::size_with(&endian),
2338 offset,
2339 )?;
2340
2341 if bytes.len() != counted_size {
2342 return Err(Error::StreamSizeMismatch {
2343 expected: counted_size,
2344 actual: bytes.len(),
2345 });
2346 }
2347
2348 let mut raw_entries = Vec::with_capacity(count);
2349 for _ in 0..count {
2350 let raw: md::MINIDUMP_MEMORY_DESCRIPTOR64 = bytes
2351 .gread_with(&mut offset, endian)
2352 .or(Err(Error::StreamReadFailure))?;
2353 raw_entries.push(raw);
2354 }
2355
2356 let mut regions = Vec::with_capacity(raw_entries.len());
2357 for raw in raw_entries {
2358 let start = rva;
2359 let end = rva
2360 .checked_add(raw.data_size)
2361 .ok_or(Error::StreamReadFailure)?;
2362 let bytes = all
2363 .get(start as usize..end as usize)
2364 .ok_or(Error::StreamReadFailure)?;
2365
2366 regions.push(MinidumpMemory64 {
2367 desc: raw,
2368 base_address: raw.start_of_memory_range,
2369 size: raw.data_size,
2370 bytes,
2371 endian,
2372 });
2373
2374 rva = end;
2375 }
2376 Ok(MinidumpMemory64List::from_regions(regions))
2377 }
2378 }
2379
2380 impl<'a> MinidumpStream<'a> for MinidumpMemoryInfoList<'a> {
2381 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::MemoryInfoListStream as u32;
2382
2383 fn read(
2384 bytes: &'a [u8],
2385 _all: &'a [u8],
2386 endian: scroll::Endian,
2387 _system_info: Option<&MinidumpSystemInfo>,
2388 ) -> Result<MinidumpMemoryInfoList<'a>, Error> {
2389 let mut offset = 0;
2390 let raw_regions: Vec<md::MINIDUMP_MEMORY_INFO> =
2391 read_ex_stream_list(&mut offset, bytes, endian)?;
2392 let regions = raw_regions
2393 .into_iter()
2394 .map(|raw| MinidumpMemoryInfo {
2395 allocation_protection: md::MemoryProtection::from_bits_truncate(
2396 raw.allocation_protection,
2397 ),
2398 state: md::MemoryState::from_bits_truncate(raw.state),
2399 protection: md::MemoryProtection::from_bits_truncate(raw.protection),
2400 ty: md::MemoryType::from_bits_truncate(raw._type),
2401 raw,
2402 _phantom: PhantomData,
2403 })
2404 .collect();
2405 Ok(MinidumpMemoryInfoList::from_regions(regions))
2406 }
2407 }
2408
2409 impl Default for MinidumpMemoryInfoList<'_> {
2410 fn default() -> Self {
2411 Self::new()
2412 }
2413 }
2414
2415 impl<'mdmp> MinidumpMemoryInfoList<'mdmp> {
2416 /// Return an empty `MinidumpMemoryList`.
2417 pub fn new() -> MinidumpMemoryInfoList<'mdmp> {
2418 MinidumpMemoryInfoList {
2419 regions: vec![],
2420 regions_by_addr: RangeMap::new(),
2421 }
2422 }
2423
2424 /// Create a `MinidumpMemoryList` from a list of `MinidumpMemory`s.
2425 pub fn from_regions(regions: Vec<MinidumpMemoryInfo<'mdmp>>) -> MinidumpMemoryInfoList<'mdmp> {
2426 let regions_by_addr = regions
2427 .iter()
2428 .enumerate()
2429 .map(|(i, region)| (region.memory_range(), i))
2430 .into_rangemap_safe();
2431 MinidumpMemoryInfoList {
2432 regions,
2433 regions_by_addr,
2434 }
2435 }
2436
2437 /// Return a `MinidumpMemory` containing memory at `address`, if one exists.
2438 pub fn memory_info_at_address(&self, address: u64) -> Option<&MinidumpMemoryInfo<'mdmp>> {
2439 self.regions_by_addr
2440 .get(address)
2441 .map(|&index| &self.regions[index])
2442 }
2443
2444 /// Iterate over the memory regions in the order contained in the minidump.
2445 ///
2446 /// The iterator returns items of [MinidumpMemory] as `&'slf MinidumpMemory<'mdmp>`.
2447 /// That is the lifetime of the item is bound to the lifetime of the iterator itself
2448 /// (`'slf`), while the slice inside [MinidumpMemory] pointing at the memory itself has
2449 /// the lifetime of the [Minidump] struct ('mdmp).
2450 pub fn iter<'slf>(&'slf self) -> impl Iterator<Item = &'slf MinidumpMemoryInfo<'mdmp>> {
2451 self.regions.iter()
2452 }
2453
2454 /// Iterate over the memory regions in order by memory address.
2455 pub fn by_addr<'slf>(&'slf self) -> impl Iterator<Item = &'slf MinidumpMemoryInfo<'mdmp>> {
2456 self.regions_by_addr
2457 .ranges_values()
2458 .map(move |&(_, index)| &self.regions[index])
2459 }
2460
2461 /// Write a human-readable description.
2462 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
2463 write!(
2464 f,
2465 "MinidumpMemoryInfoList
2466 region_count = {}
2467
2468 ",
2469 self.regions.len()
2470 )?;
2471 for (i, region) in self.regions.iter().enumerate() {
2472 writeln!(f, "region[{i}]")?;
2473 region.print(f)?;
2474 }
2475 Ok(())
2476 }
2477 }
2478
2479 impl MinidumpMemoryInfo<'_> {
2480 /// Write a human-readable description.
2481 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
2482 write!(
2483 f,
2484 "MINIDUMP_MEMORY_INFO
2485 base_address = {:#x}
2486 allocation_base = {:#x}
2487 allocation_protection = {:#x}
2488 region_size = {:#x}
2489 state = {:#x}
2490 protection = {:#x}
2491 _type = {:#x}
2492 ",
2493 self.raw.base_address,
2494 self.raw.allocation_base,
2495 self.allocation_protection,
2496 self.raw.region_size,
2497 self.state,
2498 self.protection,
2499 self.ty,
2500 )?;
2501 writeln!(f)
2502 }
2503
2504 pub fn memory_range(&self) -> Option<Range<u64>> {
2505 if self.raw.region_size == 0 {
2506 return None;
2507 }
2508 Some(Range::new(
2509 self.raw.base_address,
2510 self.raw.base_address.checked_add(self.raw.region_size)? - 1,
2511 ))
2512 }
2513
2514 /// Whether this memory range was readable.
2515 pub fn is_readable(&self) -> bool {
2516 self.protection.intersects(
2517 md::MemoryProtection::PAGE_READONLY
2518 | md::MemoryProtection::PAGE_READWRITE
2519 | md::MemoryProtection::PAGE_EXECUTE_READ
2520 | md::MemoryProtection::PAGE_EXECUTE_READWRITE,
2521 )
2522 }
2523
2524 /// Whether this memory range was writable.
2525 pub fn is_writable(&self) -> bool {
2526 self.protection.intersects(
2527 md::MemoryProtection::PAGE_READWRITE
2528 | md::MemoryProtection::PAGE_WRITECOPY
2529 | md::MemoryProtection::PAGE_EXECUTE_READWRITE
2530 | md::MemoryProtection::PAGE_EXECUTE_WRITECOPY,
2531 )
2532 }
2533
2534 /// Whether this memory range was executable.
2535 pub fn is_executable(&self) -> bool {
2536 self.protection.intersects(
2537 md::MemoryProtection::PAGE_EXECUTE
2538 | md::MemoryProtection::PAGE_EXECUTE_READ
2539 | md::MemoryProtection::PAGE_EXECUTE_READWRITE
2540 | md::MemoryProtection::PAGE_EXECUTE_WRITECOPY,
2541 )
2542 }
2543 }
2544
2545 impl<'a> MinidumpStream<'a> for MinidumpLinuxMaps<'a> {
2546 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::LinuxMaps as u32;
2547
2548 fn read(
2549 bytes: &'a [u8],
2550 _all: &'a [u8],
2551 _endian: scroll::Endian,
2552 _system_info: Option<&MinidumpSystemInfo>,
2553 ) -> Result<MinidumpLinuxMaps<'a>, Error> {
2554 let maps = MemoryMaps::from_read(std::io::Cursor::new(bytes)).map_err(|e| {
2555 tracing::error!("linux memory map read error: {e}");
2556 Error::StreamReadFailure
2557 })?;
2558
2559 Ok(MinidumpLinuxMaps::from_regions(
2560 maps.into_iter()
2561 .map(|map| MinidumpLinuxMapInfo {
2562 map,
2563 _phantom: PhantomData,
2564 })
2565 .collect(),
2566 ))
2567 }
2568 }
2569
2570 impl Default for MinidumpLinuxMaps<'_> {
2571 fn default() -> Self {
2572 Self::new()
2573 }
2574 }
2575
2576 impl<'mdmp> MinidumpLinuxMaps<'mdmp> {
2577 /// Return an empty `MinidumpMemoryList`.
2578 pub fn new() -> Self {
2579 Self {
2580 regions: vec![],
2581 regions_by_addr: RangeMap::new(),
2582 }
2583 }
2584
2585 /// Create a `MinidumpMemoryList` from a list of `MinidumpMemory`s.
2586 pub fn from_regions(regions: Vec<MinidumpLinuxMapInfo<'mdmp>>) -> Self {
2587 let regions_by_addr = regions
2588 .iter()
2589 .enumerate()
2590 .map(|(i, region)| (region.memory_range(), i))
2591 .into_rangemap_safe();
2592 Self {
2593 regions,
2594 regions_by_addr,
2595 }
2596 }
2597
2598 /// Return a `MinidumpMemory` containing memory at `address`, if one exists.
2599 pub fn memory_info_at_address(&self, address: u64) -> Option<&MinidumpLinuxMapInfo<'mdmp>> {
2600 self.regions_by_addr
2601 .get(address)
2602 .map(|&index| &self.regions[index])
2603 }
2604
2605 /// Iterate over the memory regions in the order contained in the minidump.
2606 pub fn iter<'slf>(&'slf self) -> impl Iterator<Item = &'slf MinidumpLinuxMapInfo<'mdmp>> {
2607 self.regions.iter()
2608 }
2609
2610 /// Iterate over the memory regions in order by memory address.
2611 pub fn by_addr<'slf>(&'slf self) -> impl Iterator<Item = &'slf MinidumpLinuxMapInfo<'mdmp>> {
2612 self.regions_by_addr
2613 .ranges_values()
2614 .map(move |&(_, index)| &self.regions[index])
2615 }
2616
2617 /// Write a human-readable description.
2618 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
2619 write!(
2620 f,
2621 "MinidumpLinuxMapInfo
2622 region_count = {}
2623
2624 ",
2625 self.regions.len()
2626 )?;
2627 for (i, region) in self.regions.iter().enumerate() {
2628 writeln!(f, "region[{i}]")?;
2629 region.print(f)?;
2630 }
2631 Ok(())
2632 }
2633
2634 // Return number of memory mappings
2635 pub fn memory_map_count(&self) -> usize {
2636 self.regions.len()
2637 }
2638 }
2639
2640 impl MinidumpLinuxMapInfo<'_> {
2641 /// Write a human-readable description of this.
2642 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
2643 write!(
2644 f,
2645 "MINIDUMP_LINUX_MAP_INFO
2646 base_address = {:#x}
2647 final_address = {:#x}
2648 kind = {:#?}
2649 permissions = {}
2650 ",
2651 self.map.address.0,
2652 self.map.address.1,
2653 self.map.pathname,
2654 self.map.perms.as_str()
2655 )?;
2656 writeln!(f)
2657 }
2658
2659 pub fn memory_range(&self) -> Option<Range<u64>> {
2660 // final address is inclusive afaik
2661 if self.map.address.0 > self.map.address.1 {
2662 return None;
2663 }
2664 Some(Range::new(self.map.address.0, self.map.address.1))
2665 }
2666
2667 /// Whether this memory range was readable.
2668 pub fn is_readable(&self) -> bool {
2669 self.map.perms.contains(MMPermissions::READ)
2670 }
2671
2672 /// Whether this memory range was writable.
2673 pub fn is_writable(&self) -> bool {
2674 self.map.perms.contains(MMPermissions::WRITE)
2675 }
2676
2677 /// Whether this memory range was executable.
2678 pub fn is_executable(&self) -> bool {
2679 self.map.perms.contains(MMPermissions::EXECUTE)
2680 }
2681
2682 #[cfg(test)]
2683 pub fn from_line(bytes: &[u8]) -> Option<Self> {
2684 let map = MemoryMaps::from_read(std::io::Cursor::new(bytes))
2685 .ok()?
2686 .into_iter()
2687 .next()?;
2688 Some(MinidumpLinuxMapInfo {
2689 map,
2690 _phantom: PhantomData,
2691 })
2692 }
2693 }
2694
2695 impl Default for UnifiedMemoryInfoList<'_> {
2696 fn default() -> Self {
2697 Self::Info(MinidumpMemoryInfoList::default())
2698 }
2699 }
2700
2701 impl<'a> UnifiedMemoryInfoList<'a> {
2702 /// Take two potential memory info sources and create an interface that unifies them.
2703 ///
2704 /// Under normal circumstances a minidump should only contain one of these.
2705 /// If both are provided, one will be arbitrarily preferred to attempt to
2706 /// make progress.
2707 pub fn new(
2708 info: Option<MinidumpMemoryInfoList<'a>>,
2709 maps: Option<MinidumpLinuxMaps<'a>>,
2710 ) -> Option<Self> {
2711 match (info, maps) {
2712 (Some(info), Some(_maps)) => {
2713 warn!("UnifiedMemoryInfoList got both kinds of info! (using InfoList)");
2714 // Just pick one I guess?
2715 Some(Self::Info(info))
2716 }
2717 (Some(info), None) => Some(Self::Info(info)),
2718 (None, Some(maps)) => Some(Self::Maps(maps)),
2719 (None, None) => None,
2720 }
2721 }
2722
2723 /// Return a `MinidumpMemory` containing memory at `address`, if one exists.
2724 pub fn memory_info_at_address(&self, address: u64) -> Option<UnifiedMemoryInfo> {
2725 match self {
2726 Self::Info(info) => info
2727 .memory_info_at_address(address)
2728 .map(UnifiedMemoryInfo::Info),
2729 Self::Maps(maps) => maps
2730 .memory_info_at_address(address)
2731 .map(UnifiedMemoryInfo::Map),
2732 }
2733 }
2734
2735 /// Iterate over the memory regions in the order contained in the minidump.
2736 pub fn iter(&self) -> impl Iterator<Item = UnifiedMemoryInfo> {
2737 // Use `flat_map` and `chain` to create a unified stream of the two types
2738 // (only one of which will conatin any values). Note that we are using
2739 // the fact that `Option` can be iterated (producing 1 to 0 values).
2740 let info = self
2741 .info()
2742 .into_iter()
2743 .flat_map(|info| info.iter().map(UnifiedMemoryInfo::Info));
2744 let maps = self
2745 .maps()
2746 .into_iter()
2747 .flat_map(|maps| maps.iter().map(UnifiedMemoryInfo::Map));
2748
2749 info.chain(maps)
2750 }
2751
2752 /// Iterate over the memory regions in order by memory address.
2753 pub fn by_addr(&self) -> impl Iterator<Item = UnifiedMemoryInfo> {
2754 let info = self
2755 .info()
2756 .into_iter()
2757 .flat_map(|info| info.by_addr().map(UnifiedMemoryInfo::Info));
2758 let maps = self
2759 .maps()
2760 .into_iter()
2761 .flat_map(|maps| maps.by_addr().map(UnifiedMemoryInfo::Map));
2762
2763 info.chain(maps)
2764 }
2765
2766 /// Write a human-readable description of this `MinidumpMemoryList` to `f`.
2767 ///
2768 /// This is very verbose, it is the format used by `minidump_dump`.
2769 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
2770 match self {
2771 Self::Info(info) => info.print(f),
2772 Self::Maps(maps) => maps.print(f),
2773 }
2774 }
2775
2776 /// Get the [`MinidumpLinuxMaps`] contained inside, if it exists.
2777 ///
2778 /// Potentially useful for doing a more refined analysis in specific places.
2779 pub fn maps(&self) -> Option<&MinidumpLinuxMaps<'a>> {
2780 match &self {
2781 Self::Maps(maps) => Some(maps),
2782 Self::Info(_) => None,
2783 }
2784 }
2785
2786 /// Get the [`MinidumpMemoryInfoList`] contained inside, if it exists.
2787 ///
2788 /// Potentially useful for doing a more refined analysis in specific places.
2789 pub fn info(&self) -> Option<&MinidumpMemoryInfoList<'a>> {
2790 match &self {
2791 Self::Maps(_) => None,
2792 Self::Info(info) => Some(info),
2793 }
2794 }
2795 }
2796
2797 /// Declares functions which will forward to functions of the same name on the inner
2798 /// `UnifiedMemoryInfo` members.
2799 macro_rules! unified_memory_forward {
2800 () => {};
2801 ( $(#[$attr:meta])* $vis:vis fn $name:ident $(< $($t_param:ident : $t_type:path),* >)? ( &self $(, $param:ident : $type:ty)* ) -> $ret:ty ; $($rest:tt)* ) => {
2802 $(#[$attr])*
2803 $vis fn $name $(< $($t_param : $t_type),* >)? (&self $(, $param : $type)*) -> $ret {
2804 match self {
2805 Self::Info(info) => info.$name($($param),*),
2806 Self::Map(map) => map.$name($($param),*),
2807 }
2808 }
2809
2810 unified_memory_forward!($($rest)*);
2811 };
2812 }
2813
2814 impl UnifiedMemoryInfo<'_> {
2815 unified_memory_forward! {
2816 /// Write a human-readable description.
2817 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()>;
2818
2819 /// The range of memory this info applies to.
2820 pub fn memory_range(&self) -> Option<Range<u64>>;
2821
2822 /// Whether this memory range was readable.
2823 pub fn is_readable(&self) -> bool;
2824
2825 /// Whether this memory range was writable.
2826 pub fn is_writable(&self) -> bool;
2827
2828 /// Whether this memory range was executable.
2829 pub fn is_executable(&self) -> bool;
2830 }
2831 }
2832
2833 impl<'a> MinidumpThread<'a> {
2834 pub fn context(
2835 &self,
2836 system_info: &MinidumpSystemInfo,
2837 misc: Option<&MinidumpMiscInfo>,
2838 ) -> Option<Cow<MinidumpContext>> {
2839 MinidumpContext::read(self.context?, self.endian, system_info, misc)
2840 .ok()
2841 .map(Cow::Owned)
2842 }
2843
2844 pub fn stack_memory<'mem>(
2845 &'mem self,
2846 memory_list: &'mem UnifiedMemoryList<'a>,
2847 ) -> Option<UnifiedMemory<'mem, 'a>> {
2848 self.stack.as_ref().map(UnifiedMemory::Memory).or_else(|| {
2849 // Sometimes the raw.stack RVA is null/busted, but the start_of_memory_range
2850 // value is correct. So if the `read` fails, try resolving start_of_memory_range
2851 // with the MinidumpMemoryList. (This seems to specifically be a problem with
2852 // Windows minidumps.)
2853 let stack_addr = self.raw.stack.start_of_memory_range;
2854 let memory = memory_list.memory_at_address(stack_addr)?;
2855 Some(memory)
2856 })
2857 }
2858
2859 /// Write a human-readable description of this `MinidumpThread` to `f`.
2860 ///
2861 /// This is very verbose, it is the format used by `minidump_dump`.
2862 pub fn print<T: Write>(
2863 &self,
2864 f: &mut T,
2865 memory: Option<&UnifiedMemoryList<'a>>,
2866 system: Option<&MinidumpSystemInfo>,
2867 misc: Option<&MinidumpMiscInfo>,
2868 brief: bool,
2869 ) -> io::Result<()> {
2870 write!(
2871 f,
2872 r#"MINIDUMP_THREAD
2873 thread_id = {:#x}
2874 suspend_count = {}
2875 priority_class = {:#x}
2876 priority = {:#x}
2877 teb = {:#x}
2878 stack.start_of_memory_range = {:#x}
2879 stack.memory.data_size = {:#x}
2880 stack.memory.rva = {:#x}
2881 thread_context.data_size = {:#x}
2882 thread_context.rva = {:#x}
2883
2884 "#,
2885 self.raw.thread_id,
2886 self.raw.suspend_count,
2887 self.raw.priority_class,
2888 self.raw.priority,
2889 self.raw.teb,
2890 self.raw.stack.start_of_memory_range,
2891 self.raw.stack.memory.data_size,
2892 self.raw.stack.memory.rva,
2893 self.raw.thread_context.data_size,
2894 self.raw.thread_context.rva,
2895 )?;
2896 if let Some(system_info) = system {
2897 if let Some(ctx) = self.context(system_info, misc) {
2898 ctx.print(f)?;
2899 } else {
2900 write!(f, " (no context)\n\n")?;
2901 }
2902 } else {
2903 write!(f, " (no context)\n\n")?;
2904 }
2905
2906 if brief {
2907 writeln!(f)?;
2908 return Ok(());
2909 }
2910
2911 let pointer_width = system.map_or(PointerWidth::Unknown, |info| info.cpu.pointer_width());
2912
2913 // We might not need any memory, so try to limp forward with an empty
2914 // MemoryList if we don't have one.
2915 let dummy_memory = UnifiedMemoryList::default();
2916 let memory = memory.unwrap_or(&dummy_memory);
2917 if let Some(ref stack) = self.stack_memory(memory) {
2918 writeln!(f, "Stack")?;
2919
2920 // For printing purposes, we'll treat any unknown CPU type as 64-bit
2921 let chunk_size: usize = pointer_width.size_in_bytes().unwrap_or(8).into();
2922 let mut offset = 0;
2923 for chunk in stack.bytes().chunks_exact(chunk_size) {
2924 write!(f, " {offset:#010x}: ")?;
2925
2926 match pointer_width {
2927 PointerWidth::Bits32 => {
2928 let value = match self.endian {
2929 scroll::Endian::Little => u32::from_le_bytes(chunk.try_into().unwrap()),
2930 scroll::Endian::Big => u32::from_be_bytes(chunk.try_into().unwrap()),
2931 };
2932 write!(f, "{value:#010x}")?;
2933 }
2934 PointerWidth::Unknown | PointerWidth::Bits64 => {
2935 let value = match self.endian {
2936 scroll::Endian::Little => u64::from_le_bytes(chunk.try_into().unwrap()),
2937 scroll::Endian::Big => u64::from_be_bytes(chunk.try_into().unwrap()),
2938 };
2939 write!(f, "{value:#018x}")?;
2940 }
2941 }
2942
2943 writeln!(f)?;
2944
2945 offset += chunk_size;
2946 }
2947 } else {
2948 writeln!(f, "No stack")?;
2949 }
2950 writeln!(f)?;
2951 Ok(())
2952 }
2953
2954 /// Gets the last error code the thread recorded, just like win32's GetLastError.
2955 ///
2956 /// The value is heuristically converted into a CrashReason because that's our
2957 /// general error code handling machinery, even though this may not actually be
2958 /// the reason for the crash!
2959 pub fn last_error(&self, cpu: Cpu, memory: &UnifiedMemoryList) -> Option<CrashReason> {
2960 // Early hacky implementation: rather than implementing all the TEB layouts,
2961 // just use the fact that we know the value we want is a 13-pointers offset
2962 // from the start of the TEB.
2963 let teb = self.raw.teb;
2964 let pointer_width = cpu.pointer_width().size_in_bytes()? as u64;
2965 let offset = pointer_width.checked_mul(13)?;
2966 let addr = teb.checked_add(offset)?;
2967 let val: u32 = memory
2968 .memory_at_address(addr)?
2969 .get_memory_at_address(addr)?;
2970
2971 Some(CrashReason::from_windows_error(val))
2972 }
2973 }
2974
2975 impl<'a> MinidumpStream<'a> for MinidumpThreadList<'a> {
2976 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::ThreadListStream as u32;
2977
2978 fn read(
2979 bytes: &'a [u8],
2980 all: &'a [u8],
2981 endian: scroll::Endian,
2982 _system_info: Option<&MinidumpSystemInfo>,
2983 ) -> Result<MinidumpThreadList<'a>, Error> {
2984 let mut offset = 0;
2985 let raw_threads: Vec<md::MINIDUMP_THREAD> = read_stream_list(&mut offset, bytes, endian)?;
2986 let mut threads = Vec::with_capacity(raw_threads.len());
2987 let mut thread_ids = HashMap::with_capacity(raw_threads.len());
2988 for raw in raw_threads.into_iter() {
2989 thread_ids.insert(raw.thread_id, threads.len());
2990
2991 // Defer parsing of this to the `context` method, where we will have access
2992 // to other streams that are required to parse a context properly.
2993 let context = location_slice(all, &raw.thread_context).ok();
2994
2995 // Try to get the stack memory here, but the `stack_memory` method will
2996 // attempt a fallback method with access to other streams.
2997 let stack = MinidumpMemory::read(&raw.stack, all, endian).ok();
2998 threads.push(MinidumpThread {
2999 raw,
3000 context,
3001 stack,
3002 endian,
3003 });
3004 }
3005 Ok(MinidumpThreadList {
3006 threads,
3007 thread_ids,
3008 })
3009 }
3010 }
3011
3012 impl<'a> MinidumpThreadList<'a> {
3013 /// Get the thread with id `id` from this thread list if it exists.
3014 pub fn get_thread(&self, id: u32) -> Option<&MinidumpThread<'a>> {
3015 self.thread_ids.get(&id).map(|&index| &self.threads[index])
3016 }
3017
3018 /// Write a human-readable description of this `MinidumpThreadList` to `f`.
3019 ///
3020 /// This is very verbose, it is the format used by `minidump_dump`.
3021 pub fn print<T: Write>(
3022 &self,
3023 f: &mut T,
3024 memory: Option<&UnifiedMemoryList<'a>>,
3025 system: Option<&MinidumpSystemInfo>,
3026 misc: Option<&MinidumpMiscInfo>,
3027 brief: bool,
3028 ) -> io::Result<()> {
3029 write!(
3030 f,
3031 r#"MinidumpThreadList
3032 thread_count = {}
3033
3034 "#,
3035 self.threads.len()
3036 )?;
3037
3038 for (i, thread) in self.threads.iter().enumerate() {
3039 writeln!(f, "thread[{i}]")?;
3040 thread.print(f, memory, system, misc, brief)?;
3041 }
3042 Ok(())
3043 }
3044 }
3045
3046 // implement print for MinidumpThreadInfo
3047 impl MinidumpThreadInfo {
3048 /// Write a human-readable description of this `MinidumpThreadInfo` to `f`.
3049 ///
3050 /// This is very verbose, it is the format used by `minidump_dump`.
3051 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
3052 write!(
3053 f,
3054 r#"MINIDUMP_THREAD_INFO
3055 thread_id = {:#x}
3056 dump_flags = {:#x}
3057 dump_error = {:#x}
3058 exit_status = {:#x}
3059 create_time = {:#x}
3060 exit_time = {:#x}
3061 kernel_time = {:#x}
3062 user_time = {:#x}
3063 start_address = {:#x}
3064 affinity = {:#x}
3065
3066 "#,
3067 self.raw.thread_id,
3068 self.raw.dump_flags,
3069 self.raw.dump_error,
3070 self.raw.exit_status,
3071 self.raw.create_time,
3072 self.raw.exit_time,
3073 self.raw.kernel_time,
3074 self.raw.user_time,
3075 self.raw.start_address,
3076 self.raw.affinity,
3077 )?;
3078 Ok(())
3079 }
3080 }
3081
3082 impl Default for MinidumpThreadInfoList {
3083 fn default() -> Self {
3084 Self::new()
3085 }
3086 }
3087
3088 impl MinidumpThreadInfoList {
3089 /// Return an empty `MinidumpThreadInfoList`.
3090 pub fn new() -> MinidumpThreadInfoList {
3091 MinidumpThreadInfoList {
3092 thread_infos: vec![],
3093 thread_ids: HashMap::new(),
3094 }
3095 }
3096
3097 /// Get the thread info with id `id` from this thread info list if it exists.
3098 pub fn get_thread_info(&self, id: u32) -> Option<&MinidumpThreadInfo> {
3099 self.thread_ids
3100 .get(&id)
3101 .map(|&index| &self.thread_infos[index])
3102 }
3103
3104 /// Write a human-readable description of this `MinidumpModuleList` to `f`.
3105 ///
3106 /// This is very verbose, it is the format used by `minidump_dump`.
3107 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
3108 write!(
3109 f,
3110 "MinidumpThreadInfoList
3111 thread_info_count = {}
3112
3113 ",
3114 self.thread_infos.len()
3115 )?;
3116 for (i, thread_info) in self.thread_infos.iter().enumerate() {
3117 writeln!(f, "thread info[{}]", i)?;
3118 thread_info.print(f)?;
3119 }
3120 Ok(())
3121 }
3122 }
3123
3124 impl<'a> MinidumpStream<'a> for MinidumpThreadInfoList {
3125 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::ThreadInfoListStream as u32;
3126
3127 fn read(
3128 bytes: &'a [u8],
3129 _all: &'a [u8],
3130 endian: scroll::Endian,
3131 _system_info: Option<&MinidumpSystemInfo>,
3132 ) -> Result<Self, Error> {
3133 let mut offset = 0;
3134 let raw_thread_infos: Vec<md::MINIDUMP_THREAD_INFO> =
3135 read_ex_stream_list(&mut offset, bytes, endian)?;
3136
3137 let mut thread_infos = Vec::with_capacity(raw_thread_infos.len());
3138 let mut thread_ids = HashMap::with_capacity(raw_thread_infos.len());
3139 for raw in raw_thread_infos.into_iter() {
3140 thread_ids.insert(raw.thread_id, thread_infos.len());
3141 thread_infos.push(MinidumpThreadInfo { raw });
3142 }
3143
3144 Ok(MinidumpThreadInfoList {
3145 thread_infos,
3146 thread_ids,
3147 })
3148 }
3149 }
3150
3151 impl MinidumpStream<'_> for MinidumpSystemInfo {
3152 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::SystemInfoStream as u32;
3153
3154 fn read(
3155 bytes: &[u8],
3156 all: &[u8],
3157 endian: scroll::Endian,
3158 system_info: Option<&MinidumpSystemInfo>,
3159 ) -> Result<MinidumpSystemInfo, Error> {
3160 if let Some(system_info) = system_info {
3161 return Ok(system_info.clone());
3162 }
3163
3164 use std::fmt::Write;
3165
3166 let raw: md::MINIDUMP_SYSTEM_INFO = bytes
3167 .pread_with(0, endian)
3168 .or(Err(Error::StreamReadFailure))?;
3169 let os = Os::from_platform_id(raw.platform_id);
3170 let cpu = Cpu::from_processor_architecture(raw.processor_architecture);
3171
3172 let mut csd_offset = raw.csd_version_rva as usize;
3173 let csd_version = read_string_utf16(&mut csd_offset, all, endian);
3174
3175 // self.raw.cpu.data is actually a union which we resolve here.
3176 let cpu_info = match cpu {
3177 Cpu::X86 | Cpu::X86_64 => {
3178 let mut cpu_info = String::new();
3179
3180 if let Cpu::X86 = cpu {
3181 // The vendor's ID is an ascii string but we need to flatten out the u32's into u8's
3182 let x86_info: md::X86CpuInfo = raw
3183 .cpu
3184 .data
3185 .pread_with(0, endian)
3186 .or(Err(Error::StreamReadFailure))?;
3187
3188 cpu_info.extend(
3189 x86_info
3190 .vendor_id
3191 .iter()
3192 .flat_map(|i| IntoIterator::into_iter(i.to_le_bytes()))
3193 .map(char::from),
3194 );
3195 cpu_info.push(' ');
3196 }
3197
3198 write!(
3199 &mut cpu_info,
3200 "family {} model {} stepping {}",
3201 raw.processor_level,
3202 (raw.processor_revision >> 8) & 0xff,
3203 raw.processor_revision & 0xff
3204 )
3205 .unwrap();
3206
3207 Some(cpu_info)
3208 }
3209 Cpu::Arm => {
3210 let arm_info: md::ARMCpuInfo = raw
3211 .cpu
3212 .data
3213 .pread_with(0, endian)
3214 .or(Err(Error::StreamReadFailure))?;
3215
3216 // There is no good list of implementer id values, but the following
3217 // pages provide some help:
3218 // http://comments.gmane.org/gmane.linux.linaro.devel/6903
3219 // http://forum.xda-developers.com/archive/index.php/t-480226.html
3220 let vendors = [
3221 (0x41, "ARM"),
3222 (0x51, "Qualcomm"),
3223 (0x56, "Marvell"),
3224 (0x69, "Intel/Marvell"),
3225 ];
3226 let parts = [
3227 (0x4100c050, "Cortex-A5"),
3228 (0x4100c080, "Cortex-A8"),
3229 (0x4100c090, "Cortex-A9"),
3230 (0x4100c0f0, "Cortex-A15"),
3231 (0x4100c140, "Cortex-R4"),
3232 (0x4100c150, "Cortex-R5"),
3233 (0x4100b360, "ARM1136"),
3234 (0x4100b560, "ARM1156"),
3235 (0x4100b760, "ARM1176"),
3236 (0x4100b020, "ARM11-MPCore"),
3237 (0x41009260, "ARM926"),
3238 (0x41009460, "ARM946"),
3239 (0x41009660, "ARM966"),
3240 (0x510006f0, "Krait"),
3241 (0x510000f0, "Scorpion"),
3242 ];
3243 let features = [
3244 (md::ArmElfHwCaps::HWCAP_SWP, "swp"),
3245 (md::ArmElfHwCaps::HWCAP_HALF, "half"),
3246 (md::ArmElfHwCaps::HWCAP_THUMB, "thumb"),
3247 (md::ArmElfHwCaps::HWCAP_26BIT, "26bit"),
3248 (md::ArmElfHwCaps::HWCAP_FAST_MULT, "fastmult"),
3249 (md::ArmElfHwCaps::HWCAP_FPA, "fpa"),
3250 (md::ArmElfHwCaps::HWCAP_VFP, "vfpv2"),
3251 (md::ArmElfHwCaps::HWCAP_EDSP, "edsp"),
3252 (md::ArmElfHwCaps::HWCAP_JAVA, "java"),
3253 (md::ArmElfHwCaps::HWCAP_IWMMXT, "iwmmxt"),
3254 (md::ArmElfHwCaps::HWCAP_CRUNCH, "crunch"),
3255 (md::ArmElfHwCaps::HWCAP_THUMBEE, "thumbee"),
3256 (md::ArmElfHwCaps::HWCAP_NEON, "neon"),
3257 (md::ArmElfHwCaps::HWCAP_VFPv3, "vfpv3"),
3258 (md::ArmElfHwCaps::HWCAP_VFPv3D16, "vfpv3d16"),
3259 (md::ArmElfHwCaps::HWCAP_TLS, "tls"),
3260 (md::ArmElfHwCaps::HWCAP_VFPv4, "vfpv4"),
3261 (md::ArmElfHwCaps::HWCAP_IDIVA, "idiva"),
3262 (md::ArmElfHwCaps::HWCAP_IDIVT, "idivt"),
3263 ];
3264
3265 let mut cpu_info = format!("ARMv{}", raw.processor_level);
3266
3267 // Try to extract out known vendor/part names from the cpuid,
3268 // falling back to just reporting the raw value.
3269 let cpuid = arm_info.cpuid;
3270 if cpuid != 0 {
3271 let vendor_id = (cpuid >> 24) & 0xff;
3272 let part_id = cpuid & 0xff00fff0;
3273
3274 if let Some(&(_, vendor)) = vendors.iter().find(|&&(id, _)| id == vendor_id) {
3275 write!(&mut cpu_info, " {vendor}").unwrap();
3276 } else {
3277 write!(&mut cpu_info, " vendor({vendor_id:#x})").unwrap();
3278 }
3279
3280 if let Some(&(_, part)) = parts.iter().find(|&&(id, _)| id == part_id) {
3281 write!(&mut cpu_info, " {part}").unwrap();
3282 } else {
3283 write!(&mut cpu_info, " part({part_id:#x})").unwrap();
3284 }
3285 }
3286
3287 // Report all the known hardware features.
3288 let elf_hwcaps = md::ArmElfHwCaps::from_bits_truncate(arm_info.elf_hwcaps);
3289 if !elf_hwcaps.is_empty() {
3290 cpu_info.push_str(" features: ");
3291
3292 // Iterator::intersperse is still unstable, so do it manually
3293 let mut comma = "";
3294 for &(_, feature) in features
3295 .iter()
3296 .filter(|&&(feature, _)| elf_hwcaps.contains(feature))
3297 {
3298 cpu_info.push_str(comma);
3299 cpu_info.push_str(feature);
3300 comma = ",";
3301 }
3302 }
3303
3304 Some(cpu_info)
3305 }
3306 _ => None,
3307 };
3308
3309 Ok(MinidumpSystemInfo {
3310 raw,
3311 os,
3312 cpu,
3313 csd_version,
3314 cpu_info,
3315 })
3316 }
3317 }
3318
3319 impl MinidumpSystemInfo {
3320 /// Write a human-readable description of this `MinidumpSystemInfo` to `f`.
3321 ///
3322 /// This is very verbose, it is the format used by `minidump_dump`.
3323 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
3324 write!(
3325 f,
3326 "MINIDUMP_SYSTEM_INFO
3327 processor_architecture = {:#x}
3328 processor_level = {}
3329 processor_revision = {:#x}
3330 number_of_processors = {}
3331 product_type = {}
3332 major_version = {}
3333 minor_version = {}
3334 build_number = {}
3335 platform_id = {:#x}
3336 csd_version_rva = {:#x}
3337 suite_mask = {:#x}
3338 (version) = {}.{}.{} {}
3339 (cpu_info) = {}
3340
3341 ",
3342 self.raw.processor_architecture,
3343 self.raw.processor_level,
3344 self.raw.processor_revision,
3345 self.raw.number_of_processors,
3346 self.raw.product_type,
3347 self.raw.major_version,
3348 self.raw.minor_version,
3349 self.raw.build_number,
3350 self.raw.platform_id,
3351 self.raw.csd_version_rva,
3352 self.raw.suite_mask,
3353 self.raw.major_version,
3354 self.raw.minor_version,
3355 self.raw.build_number,
3356 self.csd_version().as_deref().unwrap_or(""),
3357 self.cpu_info().as_deref().unwrap_or(""),
3358 )?;
3359 // TODO: cpu info etc
3360 Ok(())
3361 }
3362
3363 /// If the minidump was generated on:
3364 /// - Windows: Returns the the name of the Service Pack.
3365 /// - macOS: Returns the product build number.
3366 /// - Linux: Returns the contents of `uname -srvmo`.
3367 pub fn csd_version(&self) -> Option<Cow<str>> {
3368 self.csd_version.as_deref().map(Cow::Borrowed)
3369 }
3370
3371 /// Returns a string describing the cpu's vendor and model.
3372 pub fn cpu_info(&self) -> Option<Cow<str>> {
3373 self.cpu_info.as_deref().map(Cow::Borrowed)
3374 }
3375
3376 /// Strings identifying the version and build number of the operating
3377 /// system. Returns a tuple in the format of (version, build number). This
3378 /// may be useful to use if the minidump was created on a Linux machine and
3379 /// is an producing empty-ish version number (0.0.0).
3380 ///
3381 /// Tries to parse the version number from the build if it cannot be found
3382 /// in the version string. If the stream already contains a valid version
3383 /// number or parsing from the build string fails, this will return what's
3384 /// directly stored in the stream.
3385 pub fn os_parts(&self) -> (String, Option<String>) {
3386 let os_version = format!(
3387 "{}.{}.{}",
3388 self.raw.major_version, self.raw.minor_version, self.raw.build_number
3389 );
3390
3391 let os_build = self
3392 .csd_version()
3393 .map(|v| v.trim().to_owned())
3394 .filter(|v| !v.is_empty());
3395
3396 if md::PlatformId::from_u32(self.raw.platform_id) != Some(md::PlatformId::Linux)
3397 || os_version != "0.0.0"
3398 {
3399 return (os_version, os_build);
3400 }
3401
3402 // Try to parse the Linux build string. Breakpad and Crashpad run
3403 // `uname -srvmo` to generate it. The string follows this structure:
3404 // "Linux [version] [build...] [arch] Linux/GNU" where the Linux/GNU
3405 // bit may not always be present.
3406 let raw_build = self.csd_version().unwrap_or(Cow::Borrowed(""));
3407 let mut parts = raw_build.split(' ');
3408 let version = parts.nth(1).unwrap_or("0.0.0");
3409 let _arch_or_os = parts.next_back().unwrap_or_default();
3410 if _arch_or_os == "Linux/GNU" {
3411 let _arch = parts.next_back();
3412 }
3413 let build = parts.collect::<Vec<&str>>().join(" ");
3414
3415 if version == "0.0.0" {
3416 (os_version, os_build)
3417 } else {
3418 (version.into(), Some(build))
3419 }
3420 }
3421 }
3422
3423 // Generates an accessor for a MISC_INFO field with two possible syntaxes:
3424 //
3425 // * VERSION_NUMBER: FIELD_NAME -> FIELD_TYPE
3426 // * VERSION_NUMBER: FIELD_NAME if FLAG -> FIELD_TYPE
3427 //
3428 // With the following definitions:
3429 //
3430 // * VERSION_NUMBER: The MISC_INFO version this field was introduced in
3431 // * FIELD_NAME: The name of the field to read
3432 // * FLAG: A MiscInfoFlag that defines if this field contains valid data
3433 // * FIELD_TYPE: The type of the field
3434 macro_rules! misc_accessors {
3435 () => {};
3436 (@defnoflag $name:ident $t:ty [$($variant:ident)+]) => {
3437 #[allow(unreachable_patterns)]
3438 pub fn $name(&self) -> Option<&$t> {
3439 match self {
3440 $(
3441 RawMiscInfo::$variant(ref raw) => Some(&raw.$name),
3442 )+
3443 _ => None,
3444 }
3445 }
3446 };
3447 (@def $name:ident $flag:ident $t:ty [$($variant:ident)+]) => {
3448 #[allow(unreachable_patterns)]
3449 pub fn $name(&self) -> Option<&$t> {
3450 match self {
3451 $(
3452 RawMiscInfo::$variant(ref raw) => if md::MiscInfoFlags::from_bits_truncate(raw.flags1).contains(md::MiscInfoFlags::$flag) { Some(&raw.$name) } else { None },
3453 )+
3454 _ => None,
3455 }
3456 }
3457 };
3458 (1: $name:ident -> $t:ty, $($rest:tt)*) => {
3459 misc_accessors!(@defnoflag $name $t [MiscInfo MiscInfo2 MiscInfo3 MiscInfo4 MiscInfo5]);
3460 misc_accessors!($($rest)*);
3461 };
3462 (1: $name:ident if $flag:ident -> $t:ty, $($rest:tt)*) => {
3463 misc_accessors!(@def $name $flag $t [MiscInfo MiscInfo2 MiscInfo3 MiscInfo4 MiscInfo5]);
3464 misc_accessors!($($rest)*);
3465 };
3466
3467 (2: $name:ident -> $t:ty, $($rest:tt)*) => {
3468 misc_accessors!(@defnoflag $name $t [MiscInfo2 MiscInfo3 MiscInfo4 MiscInfo5]);
3469 misc_accessors!($($rest)*);
3470 };
3471 (2: $name:ident if $flag:ident -> $t:ty, $($rest:tt)*) => {
3472 misc_accessors!(@def $name $flag $t [MiscInfo2 MiscInfo3 MiscInfo4 MiscInfo5]);
3473 misc_accessors!($($rest)*);
3474 };
3475
3476 (3: $name:ident -> $t:ty, $($rest:tt)*) => {
3477 misc_accessors!(@defnoflag $name $t [MiscInfo3 MiscInfo4 MiscInfo5]);
3478 misc_accessors!($($rest)*);
3479 };
3480 (3: $name:ident if $flag:ident -> $t:ty, $($rest:tt)*) => {
3481 misc_accessors!(@def $name $flag $t [MiscInfo3 MiscInfo4 MiscInfo5]);
3482 misc_accessors!($($rest)*);
3483 };
3484
3485 (4: $name:ident -> $t:ty, $($rest:tt)*) => {
3486 misc_accessors!(@defnoflag $name $t [MiscInfo4 MiscInfo5]);
3487 misc_accessors!($($rest)*);
3488 };
3489 (4: $name:ident if $flag:ident -> $t:ty, $($rest:tt)*) => {
3490 misc_accessors!(@def $name $flag $t [MiscInfo4 MiscInfo5]);
3491 misc_accessors!($($rest)*);
3492 };
3493
3494 (5: $name:ident -> $t:ty, $($rest:tt)*) => {
3495 misc_accessors!(@defnoflag $name $t [MiscInfo5]);
3496 misc_accessors!($($rest)*);
3497 };
3498 (5: $name:ident if $flag:ident -> $t:ty, $($rest:tt)*) => {
3499 misc_accessors!(@def $name $flag $t [MiscInfo5]);
3500 misc_accessors!($($rest)*);
3501 };
3502 }
3503
3504 impl RawMiscInfo {
3505 // Fields are grouped by the flag that guards them.
3506 misc_accessors!(
3507 1: size_of_info -> u32,
3508 1: flags1 -> u32,
3509
3510 1: process_id if MINIDUMP_MISC1_PROCESS_ID -> u32,
3511
3512 1: process_create_time if MINIDUMP_MISC1_PROCESS_TIMES -> u32,
3513 1: process_user_time if MINIDUMP_MISC1_PROCESS_TIMES -> u32,
3514 1: process_kernel_time if MINIDUMP_MISC1_PROCESS_TIMES -> u32,
3515
3516 2: processor_max_mhz if MINIDUMP_MISC1_PROCESSOR_POWER_INFO -> u32,
3517 2: processor_current_mhz if MINIDUMP_MISC1_PROCESSOR_POWER_INFO -> u32,
3518 2: processor_mhz_limit if MINIDUMP_MISC1_PROCESSOR_POWER_INFO -> u32,
3519 2: processor_max_idle_state if MINIDUMP_MISC1_PROCESSOR_POWER_INFO -> u32,
3520 2: processor_current_idle_state if MINIDUMP_MISC1_PROCESSOR_POWER_INFO -> u32,
3521
3522 3: process_integrity_level if MINIDUMP_MISC3_PROCESS_INTEGRITY -> u32,
3523
3524 3: process_execute_flags if MINIDUMP_MISC3_PROCESS_EXECUTE_FLAGS -> u32,
3525
3526 3: protected_process if MINIDUMP_MISC3_PROTECTED_PROCESS -> u32,
3527
3528 3: time_zone_id if MINIDUMP_MISC3_TIMEZONE -> u32,
3529 3: time_zone if MINIDUMP_MISC3_TIMEZONE -> md::TIME_ZONE_INFORMATION,
3530
3531 4: build_string if MINIDUMP_MISC4_BUILDSTRING -> [u16; 260],
3532 4: dbg_bld_str if MINIDUMP_MISC4_BUILDSTRING -> [u16; 40],
3533
3534 5: xstate_data -> md::XSTATE_CONFIG_FEATURE_MSC_INFO,
3535
3536 5: process_cookie if MINIDUMP_MISC5_PROCESS_COOKIE -> u32,
3537 );
3538 }
3539
3540 impl MinidumpStream<'_> for MinidumpMiscInfo {
3541 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::MiscInfoStream as u32;
3542
3543 fn read(
3544 bytes: &[u8],
3545 _all: &[u8],
3546 endian: scroll::Endian,
3547 _system_info: Option<&MinidumpSystemInfo>,
3548 ) -> Result<MinidumpMiscInfo, Error> {
3549 // The misc info has gone through several revisions, so try to read the largest known
3550 // struct possible.
3551 macro_rules! do_read {
3552 ($(($t:ty, $variant:ident),)+) => {
3553 $(
3554 if bytes.len() >= <$t>::size_with(&endian) {
3555 return Ok(MinidumpMiscInfo {
3556 raw: RawMiscInfo::$variant(bytes.pread_with(0, endian).or(Err(Error::StreamReadFailure))?),
3557 });
3558 }
3559 )+
3560 }
3561 }
3562
3563 do_read!(
3564 (md::MINIDUMP_MISC_INFO_5, MiscInfo5),
3565 (md::MINIDUMP_MISC_INFO_4, MiscInfo4),
3566 (md::MINIDUMP_MISC_INFO_3, MiscInfo3),
3567 (md::MINIDUMP_MISC_INFO_2, MiscInfo2),
3568 (md::MINIDUMP_MISC_INFO, MiscInfo),
3569 );
3570 Err(Error::StreamReadFailure)
3571 }
3572 }
3573
3574 // Generates an accessor for a MAC_CRASH_INFO field with two possible syntaxes:
3575 //
3576 // * VERSION_NUMBER: FIELD_NAME -> FIELD_TYPE
3577 // * VERSION_NUMBER: string FIELD_NAME -> FIELD_TYPE
3578 //
3579 // With the following definitions:
3580 //
3581 // * VERSION_NUMBER: The MAC_CRASH_INFO version this field was introduced in
3582 // * FIELD_NAME: The name of the field to read
3583 // * FIELD_TYPE: The type of the field
3584 //
3585 // The "string" mode will retrieve the field from the variant's _RECORD_STRINGS
3586 // struct, while the other mode will retrieve it from the variant's _RECORD
3587 // struct.
3588 //
3589 // In both cases, None will be yielded if the value is null/empty.
3590 macro_rules! mac_crash_accessors {
3591 () => {};
3592 (@deffixed $name:ident $t:ty [$($variant:ident)+]) => {
3593 #[allow(unreachable_patterns)]
3594 pub fn $name(&self) -> Option<&$t> {
3595 match self {
3596 $(
3597 RawMacCrashInfo::$variant(ref fixed, _) => {
3598 if fixed.$name == 0 {
3599 None
3600 } else {
3601 Some(&fixed.$name)
3602 }
3603 },
3604 )+
3605 _ => None,
3606 }
3607 }
3608 };
3609 (@defstrings $name:ident $t:ty [$($variant:ident)+]) => {
3610 #[allow(unreachable_patterns)]
3611 pub fn $name(&self) -> Option<&$t> {
3612 match self {
3613 $(
3614 RawMacCrashInfo::$variant(_, ref strings) => {
3615 if strings.$name.is_empty() {
3616 None
3617 } else {
3618 Some(&*strings.$name)
3619 }
3620 }
3621 )+
3622 _ => None,
3623 }
3624 }
3625 };
3626 (1: $name:ident -> $t:ty, $($rest:tt)*) => {
3627 mac_crash_accessors!(@deffixed $name $t [V1 V4 V5]);
3628 mac_crash_accessors!($($rest)*);
3629 };
3630 (1: string $name:ident -> $t:ty, $($rest:tt)*) => {
3631 mac_crash_accessors!(@defstrings $name $t [V1 V4 V5]);
3632 mac_crash_accessors!($($rest)*);
3633 };
3634 (4: $name:ident -> $t:ty, $($rest:tt)*) => {
3635 mac_crash_accessors!(@deffixed $name $t [V4 V5]);
3636 mac_crash_accessors!($($rest)*);
3637 };
3638 (4: string $name:ident -> $t:ty, $($rest:tt)*) => {
3639 mac_crash_accessors!(@defstrings $name $t [V4 V5]);
3640 mac_crash_accessors!($($rest)*);
3641 };
3642 (5: $name:ident -> $t:ty, $($rest:tt)*) => {
3643 mac_crash_accessors!(@deffixed $name $t [V5]);
3644 mac_crash_accessors!($($rest)*);
3645 };
3646 (5: string $name:ident -> $t:ty, $($rest:tt)*) => {
3647 mac_crash_accessors!(@defstrings $name $t [V5]);
3648 mac_crash_accessors!($($rest)*);
3649 };
3650 }
3651
3652 impl RawMacCrashInfo {
3653 // Fields are grouped by the flag that guards them.
3654 mac_crash_accessors!(
3655 1: version -> u64,
3656
3657 4: thread -> u64,
3658 4: dialog_mode -> u64,
3659
3660 4: string module_path -> str,
3661 4: string message -> str,
3662 4: string signature_string -> str,
3663 4: string backtrace -> str,
3664 4: string message2 -> str,
3665
3666 5: abort_cause -> u64,
3667 );
3668 }
3669
3670 impl MinidumpStream<'_> for MinidumpMacCrashInfo {
3671 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::MozMacosCrashInfoStream as u32;
3672
3673 fn read(
3674 bytes: &[u8],
3675 all: &[u8],
3676 endian: scroll::Endian,
3677 _system_info: Option<&MinidumpSystemInfo>,
3678 ) -> Result<MinidumpMacCrashInfo, Error> {
3679 // Get the main header of the stream
3680 let header: md::MINIDUMP_MAC_CRASH_INFO = bytes
3681 .pread_with(0, endian)
3682 .or(Err(Error::StreamReadFailure))?;
3683
3684 let strings_offset = header.record_start_size as usize;
3685 let mut prev_version = None;
3686 let mut infos = Vec::new();
3687
3688 // We use `take` here to better handle a corrupt record_count that is larger than the
3689 // maximum supported size.
3690 let records = header.records.iter().take(header.record_count as usize);
3691
3692 for record_location in records {
3693 // Peek the V1 version to get the `version` field
3694 let record_slice = location_slice(all, record_location)?;
3695 let base: md::MINIDUMP_MAC_CRASH_INFO_RECORD = record_slice
3696 .pread_with(0, endian)
3697 .or(Err(Error::StreamReadFailure))?;
3698
3699 // The V1 version also includes the stream type again, but that's
3700 // not really important, so just warn about it and keep going.
3701 if base.stream_type != header.stream_type as u64 {
3702 warn!(
3703 "MozMacosCrashInfoStream records don't have the right stream type? {}",
3704 base.stream_type
3705 );
3706 }
3707
3708 // Make sure every record has the same version, because they have to
3709 // share their strings_offset which make heterogeneous records impossible.
3710 if let Some(prev_version) = prev_version {
3711 if prev_version != base.version {
3712 warn!(
3713 "MozMacosCrashInfoStream had two different versions ({} != {})",
3714 prev_version, base.version
3715 );
3716 return Err(Error::VersionMismatch);
3717 }
3718 }
3719 prev_version = Some(base.version);
3720
3721 // Now actually read the full record and its strings for the version
3722 macro_rules! do_read {
3723 ($base_version:expr, $strings_offset:expr, $infos:ident,
3724 $(($version:expr, $fixed:ty, $strings:ty, $variant:ident),)+) => {$(
3725 if $base_version >= $version {
3726 let offset = &mut 0;
3727 let fixed: $fixed = record_slice
3728 .gread_with(offset, endian)
3729 .or(Err(Error::StreamReadFailure))?;
3730
3731 // Sanity check that we haven't blown past where the strings start.
3732 if *offset > $strings_offset {
3733 warn!("MozMacosCrashInfoStream's record_start_size was too small! ({})",
3734 $strings_offset);
3735 return Err(Error::StreamReadFailure);
3736 }
3737
3738 // We could be handling a newer version of the format than we know
3739 // how to support, so jump to where the strings start, potentially
3740 // skipping over some unknown fields.
3741 *offset = $strings_offset;
3742 let num_strings = <$strings>::num_strings();
3743 let mut strings = <$strings>::default();
3744
3745 // Read out all the strings we know about
3746 for i in 0..num_strings {
3747 let string = read_cstring_utf8(offset, record_slice)
3748 .ok_or(Error::StreamReadFailure)?;
3749 strings.set_string(i, string);
3750 }
3751 // If this is a newer version, there may be some extra variable length
3752 // data in this record, but we don't know what it is, so don't try to parse it.
3753
3754 infos.push(RawMacCrashInfo::$variant(fixed, strings));
3755 continue;
3756 }
3757 )+}
3758 }
3759
3760 do_read!(
3761 base.version,
3762 strings_offset,
3763 infos,
3764 (
3765 5,
3766 md::MINIDUMP_MAC_CRASH_INFO_RECORD_5,
3767 md::MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS_5,
3768 V5
3769 ),
3770 (
3771 4,
3772 md::MINIDUMP_MAC_CRASH_INFO_RECORD_4,
3773 md::MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS_4,
3774 V4
3775 ),
3776 (
3777 1,
3778 md::MINIDUMP_MAC_CRASH_INFO_RECORD,
3779 md::MINIDUMP_MAC_CRASH_INFO_RECORD_STRINGS,
3780 V1
3781 ),
3782 );
3783 }
3784 Ok(MinidumpMacCrashInfo { raw: infos })
3785 }
3786 }
3787
3788 impl MinidumpMacCrashInfo {
3789 /// Write a human-readable description of this `MinidumpMacCrashInfo` to `f`.
3790 ///
3791 /// This is very verbose, it is the format used by `minidump_dump`.
3792 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
3793 macro_rules! write_simple_field {
3794 ($stream:ident, $field:ident, $idx:ident, $format:literal) => {
3795 write!(f, " {:18}= ", stringify!($field))?;
3796 match self.raw[$idx].$field() {
3797 Some($field) => {
3798 writeln!(f, $format, $field)?;
3799 }
3800 None => writeln!(f)?,
3801 }
3802 };
3803 ($stream:ident, $field:ident, $idx:ident) => {
3804 write_simple_field!($stream, $field, $idx, "{}");
3805 };
3806 }
3807 writeln!(f, "MINIDUMP_MAC_CRASH_INFO")?;
3808 writeln!(f, " num_records = {}", self.raw.len())?;
3809
3810 for i in 0..self.raw.len() {
3811 writeln!(f)?;
3812 writeln!(f, " RECORD[{i}] ")?;
3813 write_simple_field!(f, version, i);
3814 write_simple_field!(f, thread, i);
3815 write_simple_field!(f, dialog_mode, i, "{:x}");
3816 write_simple_field!(f, module_path, i);
3817 write_simple_field!(f, message, i);
3818 write_simple_field!(f, signature_string, i);
3819 write_simple_field!(f, backtrace, i);
3820 write_simple_field!(f, message2, i);
3821 write_simple_field!(f, abort_cause, i, "{:x}");
3822 }
3823
3824 writeln!(f)?;
3825 Ok(())
3826 }
3827 }
3828
3829 impl MinidumpStream<'_> for MinidumpMacBootargs {
3830 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::MozMacosBootargsStream as u32;
3831
3832 fn read(
3833 bytes: &[u8],
3834 all: &[u8],
3835 endian: scroll::Endian,
3836 _system_info: Option<&MinidumpSystemInfo>,
3837 ) -> Result<MinidumpMacBootargs, Error> {
3838 let raw: md::MINIDUMP_MAC_BOOTARGS = bytes
3839 .pread_with(0, endian)
3840 .or(Err(Error::StreamReadFailure))?;
3841
3842 let stream_type = raw.stream_type;
3843 if stream_type != Self::STREAM_TYPE {
3844 warn!(
3845 "MozMacosBootargsStream record doesn't have the right stream type? {}",
3846 Self::STREAM_TYPE
3847 );
3848 }
3849 let mut bootargs_offset = raw.bootargs as usize;
3850 let bootargs = read_string_utf16(&mut bootargs_offset, all, endian);
3851
3852 Ok(MinidumpMacBootargs { raw, bootargs })
3853 }
3854 }
3855
3856 impl MinidumpMacBootargs {
3857 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
3858 writeln!(
3859 f,
3860 "mac_boot_args = {}",
3861 self.bootargs.as_deref().unwrap_or("")
3862 )?;
3863 writeln!(f)?;
3864 Ok(())
3865 }
3866 }
3867
3868 impl<'a> MinidumpStream<'a> for MinidumpLinuxLsbRelease<'a> {
3869 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::LinuxLsbRelease as u32;
3870
3871 fn read(
3872 bytes: &'a [u8],
3873 _all: &'a [u8],
3874 _endian: scroll::Endian,
3875 _system_info: Option<&MinidumpSystemInfo>,
3876 ) -> Result<MinidumpLinuxLsbRelease<'a>, Error> {
3877 Ok(Self { data: bytes })
3878 }
3879 }
3880
3881 impl<'a> MinidumpStream<'a> for MinidumpLinuxEnviron<'a> {
3882 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::LinuxEnviron as u32;
3883
3884 fn read(
3885 bytes: &'a [u8],
3886 _all: &'a [u8],
3887 _endian: scroll::Endian,
3888 _system_info: Option<&MinidumpSystemInfo>,
3889 ) -> Result<MinidumpLinuxEnviron<'a>, Error> {
3890 Ok(Self { data: bytes })
3891 }
3892 }
3893
3894 impl<'a> MinidumpStream<'a> for MinidumpLinuxProcStatus<'a> {
3895 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::LinuxProcStatus as u32;
3896
3897 fn read(
3898 bytes: &'a [u8],
3899 _all: &'a [u8],
3900 _endian: scroll::Endian,
3901 _system_info: Option<&MinidumpSystemInfo>,
3902 ) -> Result<MinidumpLinuxProcStatus<'a>, Error> {
3903 Ok(Self { data: bytes })
3904 }
3905 }
3906
3907 impl<'a> MinidumpStream<'a> for MinidumpLinuxProcLimits<'a> {
3908 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::MozLinuxLimits as u32;
3909
3910 fn read(
3911 bytes: &'a [u8],
3912 _all: &'a [u8],
3913 _endian: scroll::Endian,
3914 _system_info: Option<&MinidumpSystemInfo>,
3915 ) -> Result<MinidumpLinuxProcLimits<'a>, Error> {
3916 Ok(Self { data: bytes })
3917 }
3918 }
3919
3920 impl<'a> MinidumpStream<'a> for MinidumpLinuxCpuInfo<'a> {
3921 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::LinuxCpuInfo as u32;
3922
3923 fn read(
3924 bytes: &'a [u8],
3925 _all: &'a [u8],
3926 _endian: scroll::Endian,
3927 _system_info: Option<&MinidumpSystemInfo>,
3928 ) -> Result<MinidumpLinuxCpuInfo<'a>, Error> {
3929 Ok(Self { data: bytes })
3930 }
3931 }
3932
3933 impl<'a> MinidumpLinuxCpuInfo<'a> {
3934 /// Get an iterator over the key-value pairs stored in the `/proc/cpuinfo` dump.
3935 ///
3936 /// Keys and values are `trim`ed of leading/trailing spaces, and if a key
3937 /// or value was surrounded by quotes ("like this"), the quotes will be
3938 /// stripped.
3939 pub fn iter(&self) -> impl Iterator<Item = (&'a LinuxOsStr, &'a LinuxOsStr)> {
3940 linux_list_iter(self.data, b':')
3941 }
3942
3943 /// Get the raw bytes of the `/proc/cpuinfo` dump.
3944 pub fn raw_bytes(&self) -> Cow<'a, [u8]> {
3945 Cow::Borrowed(self.data)
3946 }
3947 }
3948
3949 impl<'a> MinidumpLinuxEnviron<'a> {
3950 /// Get an iterator over the key-value pairs stored in the `/proc/self/environ` dump.
3951 ///
3952 /// Keys and values are `trim`ed of leading/trailing spaces, and if a key
3953 /// or value was surrounded by quotes ("like this"), the quotes will be
3954 /// stripped.
3955 pub fn iter(&self) -> impl Iterator<Item = (&'a LinuxOsStr, &'a LinuxOsStr)> {
3956 linux_list_iter(self.data, b'=')
3957 }
3958
3959 /// Get the raw bytes of the `/proc/self/environ` dump.
3960 pub fn raw_bytes(&self) -> Cow<'a, [u8]> {
3961 Cow::Borrowed(self.data)
3962 }
3963 }
3964
3965 impl<'a> MinidumpLinuxProcStatus<'a> {
3966 /// Get an iterator over the key-value pairs stored in the `/proc/self/status` dump.
3967 ///
3968 /// Keys and values are `trim`ed of leading/trailing spaces, and if a key
3969 /// or value was surrounded by quotes ("like this"), the quotes will be
3970 /// stripped.
3971 pub fn iter(&self) -> impl Iterator<Item = (&'a LinuxOsStr, &'a LinuxOsStr)> {
3972 linux_list_iter(self.data, b':')
3973 }
3974
3975 /// Get the raw bytes of the `/proc/self/status` dump.
3976 pub fn raw_bytes(&self) -> Cow<'a, [u8]> {
3977 Cow::Borrowed(self.data)
3978 }
3979 }
3980
3981 impl<'a> MinidumpLinuxProcLimits<'a> {
3982 /// Get an iterator over the key-value pairs stored in the `/proc/self/limits` dump.
3983 ///
3984 /// Keys and values are `trim`ed of leading/trailing spaces, and if a key
3985 /// or value was surrounded by quotes ("like this"), the quotes will be
3986 /// stripped.
3987 pub fn iter(&self) -> impl Iterator<Item = &'a LinuxOsStr> {
3988 LinuxOsStr::from_bytes(self.data).lines()
3989 }
3990
3991 /// Get the raw bytes of the `/proc/self/limits` dump.
3992 pub fn raw_bytes(&self) -> Cow<'a, [u8]> {
3993 Cow::Borrowed(self.data)
3994 }
3995 }
3996
3997 impl<'a> MinidumpLinuxLsbRelease<'a> {
3998 /// Get an iterator over the key-value pairs stored in the `/etc/lsb-release` dump.
3999 ///
4000 /// Keys and values are `trim`ed of leading/trailing spaces, and if a key
4001 /// or value was surrounded by quotes ("like this"), the quotes will be
4002 /// stripped.
4003 pub fn iter(&self) -> impl Iterator<Item = (&'a LinuxOsStr, &'a LinuxOsStr)> {
4004 linux_list_iter(self.data, b'=')
4005 }
4006
4007 /// Get the raw bytes of the `/etc/lsb-release` dump.
4008 pub fn raw_bytes(&self) -> Cow<'a, [u8]> {
4009 Cow::Borrowed(self.data)
4010 }
4011 }
4012
4013 fn systemtime_from_timestamp(timestamp: u64) -> Option<SystemTime> {
4014 SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(timestamp))
4015 }
4016
4017 impl MinidumpMiscInfo {
4018 pub fn process_create_time(&self) -> Option<SystemTime> {
4019 self.raw
4020 .process_create_time()
4021 .and_then(|t| systemtime_from_timestamp(*t as u64))
4022 }
4023
4024 /// Write a human-readable description of this `MinidumpMiscInfo` to `f`.
4025 ///
4026 /// This is very verbose, it is the format used by `minidump_dump`.
4027 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
4028 macro_rules! write_simple_field {
4029 ($stream:ident, $field:ident, $format:literal) => {
4030 write!(f, " {:29}= ", stringify!($field))?;
4031 match self.raw.$field() {
4032 Some($field) => {
4033 writeln!(f, $format, $field)?;
4034 }
4035 None => writeln!(f, "(invalid)")?,
4036 }
4037 };
4038 ($stream:ident, $field:ident) => {
4039 write_simple_field!($stream, $field, "{}");
4040 };
4041 }
4042 writeln!(f, "MINIDUMP_MISC_INFO")?;
4043
4044 write_simple_field!(f, size_of_info);
4045 write_simple_field!(f, flags1, "{:x}");
4046 write_simple_field!(f, process_id);
4047 write!(f, " process_create_time = ")?;
4048 match self.raw.process_create_time() {
4049 Some(&process_create_time) => {
4050 writeln!(
4051 f,
4052 "{:#x} {}",
4053 process_create_time,
4054 format_time_t(process_create_time),
4055 )?;
4056 }
4057 None => writeln!(f, "(invalid)")?,
4058 }
4059 write_simple_field!(f, process_user_time);
4060 write_simple_field!(f, process_kernel_time);
4061
4062 write_simple_field!(f, processor_max_mhz);
4063 write_simple_field!(f, processor_current_mhz);
4064 write_simple_field!(f, processor_mhz_limit);
4065 write_simple_field!(f, processor_max_idle_state);
4066 write_simple_field!(f, processor_current_idle_state);
4067
4068 write_simple_field!(f, process_integrity_level);
4069 write_simple_field!(f, process_execute_flags, "{:x}");
4070 write_simple_field!(f, protected_process);
4071 write_simple_field!(f, time_zone_id);
4072
4073 write!(f, " time_zone = ")?;
4074 match self.raw.time_zone() {
4075 Some(time_zone) => {
4076 writeln!(f)?;
4077 writeln!(f, " bias = {}", time_zone.bias)?;
4078 writeln!(
4079 f,
4080 " standard_name = {}",
4081 utf16_to_string(&time_zone.standard_name[..])
4082 .unwrap_or_else(|| String::from("(invalid)"))
4083 )?;
4084 writeln!(
4085 f,
4086 " standard_date = {}",
4087 format_system_time(&time_zone.standard_date)
4088 )?;
4089 writeln!(f, " standard_bias = {}", time_zone.standard_bias)?;
4090 writeln!(
4091 f,
4092 " daylight_name = {}",
4093 utf16_to_string(&time_zone.daylight_name[..])
4094 .unwrap_or_else(|| String::from("(invalid)"))
4095 )?;
4096 writeln!(
4097 f,
4098 " daylight_date = {}",
4099 format_system_time(&time_zone.daylight_date)
4100 )?;
4101 writeln!(f, " daylight_bias = {}", time_zone.daylight_bias)?;
4102 }
4103 None => writeln!(f, "(invalid)")?,
4104 }
4105
4106 write!(f, " build_string = ")?;
4107 match self
4108 .raw
4109 .build_string()
4110 .and_then(|string| utf16_to_string(&string[..]))
4111 {
4112 Some(build_string) => writeln!(f, "{build_string}")?,
4113 None => writeln!(f, "(invalid)")?,
4114 }
4115 write!(f, " dbg_bld_str = ")?;
4116 match self
4117 .raw
4118 .dbg_bld_str()
4119 .and_then(|string| utf16_to_string(&string[..]))
4120 {
4121 Some(dbg_bld_str) => writeln!(f, "{dbg_bld_str}")?,
4122 None => writeln!(f, "(invalid)")?,
4123 }
4124
4125 write!(f, " xstate_data = ")?;
4126 match self.raw.xstate_data() {
4127 Some(xstate_data) => {
4128 writeln!(f)?;
4129 for (i, feature) in xstate_data.iter() {
4130 if let Some(feature) = md::XstateFeatureIndex::from_index(i) {
4131 let feature_name = format!("{feature:?}");
4132 write!(f, " feature {i:2} - {feature_name:22}: ")?;
4133 } else {
4134 write!(f, " feature {i:2} - (unknown) : ")?;
4135 }
4136 writeln!(f, " offset {:4}, size {:4}", feature.offset, feature.size)?;
4137 }
4138 }
4139 None => writeln!(f, "(invalid)")?,
4140 }
4141
4142 write_simple_field!(f, process_cookie);
4143 writeln!(f)?;
4144 Ok(())
4145 }
4146 }
4147
4148 impl MinidumpStream<'_> for MinidumpBreakpadInfo {
4149 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::BreakpadInfoStream as u32;
4150
4151 fn read(
4152 bytes: &[u8],
4153 _all: &[u8],
4154 endian: scroll::Endian,
4155 _system_info: Option<&MinidumpSystemInfo>,
4156 ) -> Result<MinidumpBreakpadInfo, Error> {
4157 let raw: md::MINIDUMP_BREAKPAD_INFO = bytes
4158 .pread_with(0, endian)
4159 .or(Err(Error::StreamReadFailure))?;
4160 let flags = md::BreakpadInfoValid::from_bits_truncate(raw.validity);
4161 let dump_thread_id = if flags.contains(md::BreakpadInfoValid::DumpThreadId) {
4162 Some(raw.dump_thread_id)
4163 } else {
4164 None
4165 };
4166 let requesting_thread_id = if flags.contains(md::BreakpadInfoValid::RequestingThreadId) {
4167 Some(raw.requesting_thread_id)
4168 } else {
4169 None
4170 };
4171 Ok(MinidumpBreakpadInfo {
4172 raw,
4173 dump_thread_id,
4174 requesting_thread_id,
4175 })
4176 }
4177 }
4178
4179 fn option_or_invalid<T: fmt::LowerHex>(what: &Option<T>) -> Cow<'_, str> {
4180 match *what {
4181 Some(ref val) => Cow::Owned(format!("{val:#x}")),
4182 None => Cow::Borrowed("(invalid)"),
4183 }
4184 }
4185
4186 impl MinidumpBreakpadInfo {
4187 /// Write a human-readable description of this `MinidumpBreakpadInfo` to `f`.
4188 ///
4189 /// This is very verbose, it is the format used by `minidump_dump`.
4190 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
4191 write!(
4192 f,
4193 "MINIDUMP_BREAKPAD_INFO
4194 validity = {:#x}
4195 dump_thread_id = {}
4196 requesting_thread_id = {}
4197
4198 ",
4199 self.raw.validity,
4200 option_or_invalid(&self.dump_thread_id),
4201 option_or_invalid(&self.requesting_thread_id),
4202 )?;
4203 Ok(())
4204 }
4205 }
4206
4207 impl CrashReason {
4208 /// Get a `CrashReason` from a `MINIDUMP_EXCEPTION_STREAM` for a given `Os`.
4209 fn from_exception(raw: &md::MINIDUMP_EXCEPTION_STREAM, os: Os, cpu: Cpu) -> CrashReason {
4210 let record = &raw.exception_record;
4211 let exception_code = record.exception_code;
4212 let exception_flags = record.exception_flags;
4213
4214 let reason = match os {
4215 Os::MacOs | Os::Ios => Self::from_mac_exception(raw, cpu),
4216 Os::Linux | Os::Android => Self::from_linux_exception(raw, cpu),
4217 Os::Windows => Self::from_windows_exception(raw, cpu),
4218 _ => None,
4219 };
4220
4221 // Default to a totally generic unknown error
4222 reason.unwrap_or(CrashReason::Unknown(exception_code, exception_flags))
4223 }
4224
4225 /// Heuristically identifies what kind of windows exception code this is.
4226 ///
4227 /// Augments [`CrashReason::from_windows_error`] by also including
4228 /// `ExceptionCodeWindows`. Appropriate for an actual crash reason.
4229 pub fn from_windows_code(exception_code: u32) -> CrashReason {
4230 if let Some(err) = err::ExceptionCodeWindows::from_u32(exception_code) {
4231 Self::WindowsGeneral(err)
4232 } else {
4233 Self::from_windows_error(exception_code)
4234 }
4235 }
4236
4237 /// Heuristically identifies what kind of windows error code this is.
4238 ///
4239 /// Appropriate for things like LastErrorValue() which may be non-fatal.
4240 pub fn from_windows_error(error_code: u32) -> CrashReason {
4241 if let Some(err) = err::WinErrorWindows::from_u32(error_code) {
4242 Self::WindowsWinError(err)
4243 } else if let Some(err) = err::NtStatusWindows::from_u32(error_code) {
4244 Self::WindowsNtStatus(err)
4245 } else if let Some(err) = Self::from_windows_error_with_facility(error_code) {
4246 err
4247 } else {
4248 Self::WindowsUnknown(error_code)
4249 }
4250 }
4251
4252 pub fn from_windows_error_with_facility(error_code: u32) -> Option<CrashReason> {
4253 static SEVERITY_MASK: u32 = 0xf0000000;
4254 static FACILITY_MASK: u32 = 0x0fff0000;
4255 static ERROR_MASK: u32 = 0x0000ffff;
4256
4257 if (error_code & SEVERITY_MASK) != 0 {
4258 // This could be an NTSTATUS or HRESULT code of a specific facility
4259 if let Some(facility) =
4260 err::WinErrorFacilityWindows::from_u32((error_code & FACILITY_MASK) >> 16)
4261 {
4262 if let Some(error) = err::WinErrorWindows::from_u32(error_code & ERROR_MASK) {
4263 return Some(Self::WindowsWinErrorWithFacility(facility, error));
4264 }
4265 }
4266 }
4267
4268 None
4269 }
4270
4271 pub fn from_windows_exception(
4272 raw: &md::MINIDUMP_EXCEPTION_STREAM,
4273 _cpu: Cpu,
4274 ) -> Option<CrashReason> {
4275 use err::ExceptionCodeWindows;
4276
4277 let record = &raw.exception_record;
4278 let info = &record.exception_information;
4279 let exception_code = record.exception_code;
4280
4281 let mut reason = CrashReason::from_windows_code(exception_code);
4282
4283 // Refine the output for error codes that have more info
4284 match reason {
4285 CrashReason::WindowsGeneral(ExceptionCodeWindows::EXCEPTION_ACCESS_VIOLATION) => {
4286 // For EXCEPTION_ACCESS_VIOLATION, Windows puts the address that
4287 // caused the fault in exception_information[1].
4288 // exception_information[0] is 0 if the violation was caused by
4289 // an attempt to read data, 1 if it was an attempt to write data,
4290 // and 8 if this was a data execution violation.
4291 // This information is useful in addition to the code address, which
4292 // will be present in the crash thread's instruction field anyway.
4293 if record.number_parameters >= 1 {
4294 // NOTE: address := info[1];
4295 if let Some(ty) = err::ExceptionCodeWindowsAccessType::from_u64(info[0]) {
4296 reason = CrashReason::WindowsAccessViolation(ty);
4297 }
4298 }
4299 }
4300 CrashReason::WindowsGeneral(ExceptionCodeWindows::EXCEPTION_IN_PAGE_ERROR) => {
4301 // For EXCEPTION_IN_PAGE_ERROR, Windows puts the address that
4302 // caused the fault in exception_information[1].
4303 // exception_information[0] is 0 if the violation was caused by
4304 // an attempt to read data, 1 if it was an attempt to write data,
4305 // and 8 if this was a data execution violation.
4306 // exception_information[2] contains the underlying NTSTATUS code,
4307 // which is the explanation for why this error occured.
4308 // This information is useful in addition to the code address, which
4309 // will be present in the crash thread's instruction field anyway.
4310 if record.number_parameters >= 3 {
4311 // NOTE: address := info[1];
4312 // The status code is 32-bits wide, ignore the upper 32 bits
4313 let nt_status = info[2] & 0xffff_ffff;
4314 if let Some(ty) = err::ExceptionCodeWindowsInPageErrorType::from_u64(info[0]) {
4315 reason = CrashReason::WindowsInPageError(ty, nt_status);
4316 }
4317 }
4318 }
4319 CrashReason::WindowsNtStatus(err::NtStatusWindows::STATUS_STACK_BUFFER_OVERRUN) => {
4320 // STATUS_STACK_BUFFER_OVERRUN are caused by __fastfail()
4321 // invocations and the fast-fail code is stored in
4322 // exception_information[0].
4323 if record.number_parameters >= 1 {
4324 // The status code is 32-bits wide, ignore the upper 32 bits
4325 let fast_fail = info[0] & 0xffff_ffff;
4326 reason = CrashReason::WindowsStackBufferOverrun(fast_fail);
4327 }
4328 }
4329 _ => {
4330 // Do nothing interesting
4331 }
4332 }
4333
4334 Some(reason)
4335 }
4336
4337 pub fn from_mac_exception(
4338 raw: &md::MINIDUMP_EXCEPTION_STREAM,
4339 cpu: Cpu,
4340 ) -> Option<CrashReason> {
4341 use err::ExceptionCodeMac;
4342
4343 let record = &raw.exception_record;
4344 let info = &record.exception_information;
4345 let exception_code = record.exception_code;
4346 let exception_flags = record.exception_flags;
4347
4348 // Default to just directly reporting this reason.
4349 let mac_reason = err::ExceptionCodeMac::from_u32(exception_code)?;
4350 let mut reason = CrashReason::MacGeneral(mac_reason, exception_flags);
4351
4352 // Refine the output for error codes that have more info
4353 match mac_reason {
4354 ExceptionCodeMac::EXC_BAD_ACCESS => {
4355 if let Some(ty) = err::ExceptionCodeMacBadAccessKernType::from_u32(exception_flags)
4356 {
4357 reason = CrashReason::MacBadAccessKern(ty);
4358 } else {
4359 match cpu {
4360 Cpu::Arm64 => {
4361 if let Some(ty) =
4362 err::ExceptionCodeMacBadAccessArmType::from_u32(exception_flags)
4363 {
4364 reason = CrashReason::MacBadAccessArm(ty);
4365 }
4366 }
4367 Cpu::Ppc => {
4368 if let Some(ty) =
4369 err::ExceptionCodeMacBadAccessPpcType::from_u32(exception_flags)
4370 {
4371 reason = CrashReason::MacBadAccessPpc(ty);
4372 }
4373 }
4374 Cpu::X86 | Cpu::X86_64 => {
4375 if let Some(ty) =
4376 err::ExceptionCodeMacBadAccessX86Type::from_u32(exception_flags)
4377 {
4378 reason = CrashReason::MacBadAccessX86(ty);
4379 }
4380 }
4381 _ => {
4382 // Do nothing
4383 }
4384 }
4385 }
4386 }
4387 ExceptionCodeMac::EXC_BAD_INSTRUCTION => match cpu {
4388 Cpu::Arm64 => {
4389 if let Some(ty) =
4390 err::ExceptionCodeMacBadInstructionArmType::from_u32(exception_flags)
4391 {
4392 reason = CrashReason::MacBadInstructionArm(ty);
4393 }
4394 }
4395 Cpu::Ppc => {
4396 if let Some(ty) =
4397 err::ExceptionCodeMacBadInstructionPpcType::from_u32(exception_flags)
4398 {
4399 reason = CrashReason::MacBadInstructionPpc(ty);
4400 }
4401 }
4402 Cpu::X86 | Cpu::X86_64 => {
4403 if let Some(ty) =
4404 err::ExceptionCodeMacBadInstructionX86Type::from_u32(exception_flags)
4405 {
4406 reason = CrashReason::MacBadInstructionX86(ty);
4407 }
4408 }
4409 _ => {
4410 // Do nothing
4411 }
4412 },
4413 ExceptionCodeMac::EXC_ARITHMETIC => match cpu {
4414 Cpu::Arm64 => {
4415 if let Some(ty) =
4416 err::ExceptionCodeMacArithmeticArmType::from_u32(exception_flags)
4417 {
4418 reason = CrashReason::MacArithmeticArm(ty);
4419 }
4420 }
4421 Cpu::Ppc => {
4422 if let Some(ty) =
4423 err::ExceptionCodeMacArithmeticPpcType::from_u32(exception_flags)
4424 {
4425 reason = CrashReason::MacArithmeticPpc(ty);
4426 }
4427 }
4428 Cpu::X86 | Cpu::X86_64 => {
4429 if let Some(ty) =
4430 err::ExceptionCodeMacArithmeticX86Type::from_u32(exception_flags)
4431 {
4432 reason = CrashReason::MacArithmeticX86(ty);
4433 }
4434 }
4435 _ => {
4436 // Do nothing
4437 }
4438 },
4439 ExceptionCodeMac::EXC_SOFTWARE => {
4440 if let Some(ty) = err::ExceptionCodeMacSoftwareType::from_u32(exception_flags) {
4441 reason = CrashReason::MacSoftware(ty);
4442 }
4443 }
4444 ExceptionCodeMac::EXC_BREAKPOINT => match cpu {
4445 Cpu::Arm64 => {
4446 if let Some(ty) =
4447 err::ExceptionCodeMacBreakpointArmType::from_u32(exception_flags)
4448 {
4449 reason = CrashReason::MacBreakpointArm(ty);
4450 }
4451 }
4452 Cpu::Ppc => {
4453 if let Some(ty) =
4454 err::ExceptionCodeMacBreakpointPpcType::from_u32(exception_flags)
4455 {
4456 reason = CrashReason::MacBreakpointPpc(ty);
4457 }
4458 }
4459 Cpu::X86 | Cpu::X86_64 => {
4460 if let Some(ty) =
4461 err::ExceptionCodeMacBreakpointX86Type::from_u32(exception_flags)
4462 {
4463 reason = CrashReason::MacBreakpointX86(ty);
4464 }
4465 }
4466 _ => {
4467 // Do nothing
4468 }
4469 },
4470 ExceptionCodeMac::EXC_RESOURCE => {
4471 if let Some(ty) =
4472 err::ExceptionCodeMacResourceType::from_u32((exception_flags >> 29) & 0x7)
4473 {
4474 reason = CrashReason::MacResource(ty, info[1], info[2]);
4475 }
4476 }
4477 ExceptionCodeMac::EXC_GUARD => {
4478 if let Some(ty) =
4479 err::ExceptionCodeMacGuardType::from_u32((exception_flags >> 29) & 0x7)
4480 {
4481 reason = CrashReason::MacGuard(ty, info[1], info[2]);
4482 }
4483 }
4484 _ => {
4485 // Do nothing
4486 }
4487 }
4488 Some(reason)
4489 }
4490
4491 pub fn from_linux_exception(
4492 raw: &md::MINIDUMP_EXCEPTION_STREAM,
4493 _cpu: Cpu,
4494 ) -> Option<CrashReason> {
4495 let record = &raw.exception_record;
4496 let exception_code = record.exception_code;
4497 let exception_flags = record.exception_flags;
4498
4499 let linux_reason = err::ExceptionCodeLinux::from_u32(exception_code)?;
4500 let mut reason = CrashReason::LinuxGeneral(linux_reason, exception_flags);
4501 // Refine the output for error codes that have more info
4502 match linux_reason {
4503 err::ExceptionCodeLinux::SIGILL => {
4504 if let Some(ty) = err::ExceptionCodeLinuxSigillKind::from_u32(exception_flags) {
4505 reason = CrashReason::LinuxSigill(ty);
4506 }
4507 }
4508 err::ExceptionCodeLinux::SIGTRAP => {
4509 if let Some(ty) = err::ExceptionCodeLinuxSigtrapKind::from_u32(exception_flags) {
4510 reason = CrashReason::LinuxSigtrap(ty);
4511 }
4512 }
4513 err::ExceptionCodeLinux::SIGFPE => {
4514 if let Some(ty) = err::ExceptionCodeLinuxSigfpeKind::from_u32(exception_flags) {
4515 reason = CrashReason::LinuxSigfpe(ty);
4516 }
4517 }
4518 err::ExceptionCodeLinux::SIGSEGV => {
4519 if let Some(ty) = err::ExceptionCodeLinuxSigsegvKind::from_u32(exception_flags) {
4520 reason = CrashReason::LinuxSigsegv(ty);
4521 }
4522 }
4523 err::ExceptionCodeLinux::SIGBUS => {
4524 if let Some(ty) = err::ExceptionCodeLinuxSigbusKind::from_u32(exception_flags) {
4525 reason = CrashReason::LinuxSigbus(ty);
4526 }
4527 }
4528 err::ExceptionCodeLinux::SIGSYS => {
4529 if let Some(ty) = err::ExceptionCodeLinuxSigsysKind::from_u32(exception_flags) {
4530 reason = CrashReason::LinuxSigsys(ty);
4531 }
4532 }
4533 _ => {
4534 // No refinements
4535 }
4536 }
4537 Some(reason)
4538 }
4539 }
4540
4541 impl fmt::Display for CrashReason {
4542 /// A string describing the crash reason.
4543 ///
4544 /// This is OS- and possibly CPU-specific.
4545 /// For example, "EXCEPTION_ACCESS_VIOLATION" (Windows),
4546 /// "EXC_BAD_ACCESS / KERN_INVALID_ADDRESS" (Mac OS X), "SIGSEGV"
4547 /// (other Unix).
4548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4549 use CrashReason::*;
4550
4551 fn write_nt_status(f: &mut fmt::Formatter<'_>, raw_nt_status: u64) -> fmt::Result {
4552 let nt_status = err::NtStatusWindows::from_u64(raw_nt_status);
4553 if let Some(nt_status) = nt_status {
4554 write!(f, "{nt_status:?}")
4555 } else {
4556 write!(f, "{raw_nt_status:#010x}")
4557 }
4558 }
4559
4560 fn write_fast_fail(f: &mut fmt::Formatter<'_>, raw_fast_fail: u64) -> fmt::Result {
4561 let fast_fail = err::FastFailCode::from_u64(raw_fast_fail);
4562 if let Some(fast_fail) = fast_fail {
4563 write!(f, "{fast_fail:?}")
4564 } else {
4565 write!(f, "{raw_fast_fail:#010x}")
4566 }
4567 }
4568
4569 fn write_exc_resource(
4570 f: &mut fmt::Formatter<'_>,
4571 ex: err::ExceptionCodeMacResourceType,
4572 code: u64,
4573 subcode: u64,
4574 ) -> fmt::Result {
4575 let flavor = (code >> 58) & 0x7;
4576 write!(f, "EXC_RESOURCE / {ex:?} / ")?;
4577 match ex {
4578 err::ExceptionCodeMacResourceType::RESOURCE_TYPE_CPU => {
4579 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_resource.h#L71-L99
4580 if let Some(cpu_flavor) =
4581 err::ExceptionCodeMacResourceCpuFlavor::from_u64(flavor)
4582 {
4583 let interval = (code >> 7) & 0x1ffffff;
4584 let cpu_limit = code & 0x7;
4585 let cpu_consumed = subcode & 0x7;
4586 write!(
4587 f,
4588 "{cpu_flavor:?} interval: {interval}s CPU limit: {cpu_limit}% CPU consumed: {cpu_consumed}%"
4589 )
4590 } else {
4591 write!(f, "{code:#018x} / {subcode:#018x}")
4592 }
4593 }
4594 err::ExceptionCodeMacResourceType::RESOURCE_TYPE_WAKEUPS => {
4595 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_resource.h#L105-L134
4596 if let Some(wakeups_flavor) =
4597 err::ExceptionCodeMacResourceWakeupsFlavor::from_u64(flavor)
4598 {
4599 let interval = (code >> 20) & 0xfffff;
4600 let wakeups_permitted = code & 0xfff;
4601 let wakeups_observed = subcode & 0xfff;
4602 write!(
4603 f,
4604 "{wakeups_flavor:?} interval: {interval}s wakeups permitted: {wakeups_permitted} wakeups observed: {wakeups_observed}"
4605 )
4606 } else {
4607 write!(f, "{code:#018x} / {subcode:#018x}")
4608 }
4609 }
4610 err::ExceptionCodeMacResourceType::RESOURCE_TYPE_MEMORY => {
4611 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_resource.h#L139-L162
4612 if let Some(memory_flavor) =
4613 err::ExceptionCodeMacResourceMemoryFlavor::from_u64(flavor)
4614 {
4615 let hwm_limit = code & 0x1fff;
4616 write!(f, "{memory_flavor:?} high watermark limit: {hwm_limit}MiB")
4617 } else {
4618 write!(f, "{code:#018x} / {subcode:#018x}")
4619 }
4620 }
4621 err::ExceptionCodeMacResourceType::RESOURCE_TYPE_IO => {
4622 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_resource.h#L168-L196
4623 if let Some(io_flavor) = err::ExceptionCodeMacResourceIOFlavor::from_u64(flavor)
4624 {
4625 let interval = (code >> 15) & 0x1ffff;
4626 let io_limit = code & 0x7fff;
4627 let io_observed = subcode & 0x7fff;
4628 write!(
4629 f,
4630 "{io_flavor:?} interval: {interval}s I/O limit: {io_limit}% I/O observed: {io_observed}%"
4631 )
4632 } else {
4633 write!(f, "{code:#018x} / {subcode:#018x}")
4634 }
4635 }
4636 err::ExceptionCodeMacResourceType::RESOURCE_TYPE_THREADS => {
4637 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_resource.h#L199-L207
4638 if let Some(threads_flavor) =
4639 err::ExceptionCodeMacResourceThreadsFlavor::from_u64(flavor)
4640 {
4641 let hwm_limit = code & 0x7fff;
4642 write!(f, "{threads_flavor:?} high watermark limit: {hwm_limit}")
4643 } else {
4644 write!(f, "{code:#018x} / {subcode:#018x}")
4645 }
4646 }
4647 }
4648 }
4649
4650 fn write_exc_guard(
4651 f: &mut fmt::Formatter<'_>,
4652 ex: err::ExceptionCodeMacGuardType,
4653 code: u64,
4654 subcode: u64,
4655 ) -> fmt::Result {
4656 let flavor = (code >> 32) & 0x1fffffff;
4657 write!(f, "EXC_GUARD / {ex:?}")?;
4658 match ex {
4659 err::ExceptionCodeMacGuardType::GUARD_TYPE_NONE => {
4660 write!(f, "")
4661 }
4662 err::ExceptionCodeMacGuardType::GUARD_TYPE_MACH_PORT => {
4663 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_guard.h#L69-L81
4664 if let Some(mach_port_flavor) =
4665 err::ExceptionCodeMacGuardMachPortFlavor::from_u64(flavor)
4666 {
4667 // FIXME: GUARD_EXC_STRICT_REPLY, GUARD_EXC_MOD_REFS and GUARD_EXC_IMMOVABLE have additional flags defined here:
4668 // https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/osfmk/mach/port.h#L518-L538
4669 // They also encode additional data in the subcode (a mach reply type or a kernel return value), one has to
4670 // check Apple's code to figure out each one. Since we haven't encountered them yet in the wild there's no
4671 // hurry to decode those.
4672 let port_name = code & 0xfffffff;
4673 if subcode != 0 {
4674 write!(
4675 f,
4676 " / {mach_port_flavor:?} port name: {port_name} subcode: {subcode}",
4677 )
4678 } else {
4679 write!(f, " / {mach_port_flavor:?} port name: {port_name}",)
4680 }
4681 } else {
4682 write!(f, " / {code:#018x} / {subcode:#018x}")
4683 }
4684 }
4685 err::ExceptionCodeMacGuardType::GUARD_TYPE_FD => {
4686 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_guard.h#L85-L97
4687 if let Some(fd_flavor) = err::ExceptionCodeMacGuardFDFlavor::from_u64(flavor) {
4688 let fd = code & 0xfffffff;
4689 write!(
4690 f,
4691 " / {fd_flavor:?} file descriptor: {fd} guard identifier: {subcode}",
4692 )
4693 } else {
4694 write!(f, " / {code:#018x} / {subcode:#018x}")
4695 }
4696 }
4697 err::ExceptionCodeMacGuardType::GUARD_TYPE_USER => {
4698 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_guard.h#L101-L113
4699 let namespace = code & 0xffffffff;
4700 write!(f, "/ namespace: {namespace} guard identifier: {subcode}",)
4701 }
4702 err::ExceptionCodeMacGuardType::GUARD_TYPE_VN => {
4703 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_guard.h#L117-L129
4704 if let Some(vn_flavor) = err::ExceptionCodeMacGuardVNFlavor::from_u64(flavor) {
4705 let pid = code & 0xfffffff;
4706 write!(f, " / {vn_flavor:?} pid: {pid} guard identifier: {subcode}",)
4707 } else {
4708 write!(f, " / {code:#018x} / {subcode:#018x}")
4709 }
4710 }
4711 err::ExceptionCodeMacGuardType::GUARD_TYPE_VIRT_MEMORY => {
4712 // See https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/osfmk/kern/exc_guard.h#L133-L145
4713 if let Some(virt_memory_flavor) =
4714 err::ExceptionCodeMacGuardVirtMemoryFlavor::from_u64(flavor)
4715 {
4716 write!(f, " / {virt_memory_flavor:?} offset: {subcode}")
4717 } else {
4718 write!(f, " / {code:#018x} / {subcode:#018x}")
4719 }
4720 }
4721 err::ExceptionCodeMacGuardType::GUARD_TYPE_REJECTED_SC => {
4722 // See https://github.com/apple-oss-distributions/xnu/blob/1031c584a5e37aff177559b9f69dbd3c8c3fd30a/osfmk/kern/exc_guard.h#L149-L163
4723 if let Some(rejected_sc_flavor) =
4724 err::ExceptionCodeMacGuardRejecteSysCallFlavor::from_u64(flavor)
4725 {
4726 let syscall = subcode;
4727 write!(f, " / {rejected_sc_flavor:?} syscall: {syscall}",)
4728 } else {
4729 write!(f, " / {code:#018x} / {subcode:#018x}")
4730 }
4731 }
4732 }
4733 }
4734
4735 fn write_signal(
4736 f: &mut fmt::Formatter<'_>,
4737 ex: err::ExceptionCodeLinux,
4738 flags: u32,
4739 ) -> fmt::Result {
4740 if let Some(si_code) = err::ExceptionCodeLinuxSicode::from_i32(flags as i32) {
4741 if si_code == err::ExceptionCodeLinuxSicode::SI_USER {
4742 write!(f, "{ex:?}")
4743 } else {
4744 write!(f, "{ex:?} / {si_code:?}")
4745 }
4746 } else {
4747 write!(f, "{ex:?} / {flags:#010x}")
4748 }
4749 }
4750
4751 // OK this is kinda a gross hack but I *really* don't want
4752 // to write out all these strings again, so let's just lean on Debug
4753 // repeating the name of the enum variant!
4754 match *self {
4755 // ======================== Mac/iOS ============================
4756
4757 // These codes get special messages
4758 MacGeneral(err::ExceptionCodeMac::SIMULATED, _) => write!(f, "Simulated Exception"),
4759
4760 // Thse codes just repeat their names
4761 MacGeneral(ex, flags) => write!(f, "{ex:?} / {flags:#010x}"),
4762 MacBadAccessKern(ex) => write!(f, "EXC_BAD_ACCESS / {ex:?}"),
4763 MacBadAccessArm(ex) => write!(f, "EXC_BAD_ACCESS / {ex:?}"),
4764 MacBadAccessPpc(ex) => write!(f, "EXC_BAD_ACCESS / {ex:?}"),
4765 MacBadAccessX86(ex) => write!(f, "EXC_BAD_ACCESS / {ex:?}"),
4766 MacBadInstructionArm(ex) => write!(f, "EXC_BAD_INSTRUCTION / {ex:?}"),
4767 MacBadInstructionPpc(ex) => write!(f, "EXC_BAD_INSTRUCTION / {ex:?}"),
4768 MacBadInstructionX86(ex) => write!(f, "EXC_BAD_INSTRUCTION / {ex:?}"),
4769 MacArithmeticArm(ex) => write!(f, "EXC_ARITHMETIC / {ex:?}"),
4770 MacArithmeticPpc(ex) => write!(f, "EXC_ARITHMETIC / {ex:?}"),
4771 MacArithmeticX86(ex) => write!(f, "EXC_ARITHMETIC / {ex:?}"),
4772 MacSoftware(ex) => write!(f, "EXC_SOFTWARE / {ex:?}"),
4773 MacBreakpointArm(ex) => write!(f, "EXC_BREAKPOINT / {ex:?}"),
4774 MacBreakpointPpc(ex) => write!(f, "EXC_BREAKPOINT / {ex:?}"),
4775 MacBreakpointX86(ex) => write!(f, "EXC_BREAKPOINT / {ex:?}"),
4776 MacResource(ex, code, subcode) => write_exc_resource(f, ex, code, subcode),
4777 MacGuard(ex, code, subcode) => write_exc_guard(f, ex, code, subcode),
4778
4779 // ===================== Linux/Android =========================
4780
4781 // These codes just repeat their names
4782 LinuxGeneral(ex, flags) => write_signal(f, ex, flags),
4783 LinuxSigill(ex) => write!(f, "SIGILL / {ex:?}"),
4784 LinuxSigtrap(ex) => write!(f, "SIGTRAP / {ex:?}"),
4785 LinuxSigbus(ex) => write!(f, "SIGBUS / {ex:?}"),
4786 LinuxSigfpe(ex) => write!(f, "SIGFPE / {ex:?}"),
4787 LinuxSigsegv(ex) => write!(f, "SIGSEGV / {ex:?}"),
4788 LinuxSigsys(ex) => write!(f, "SIGSYS / {ex:?}"),
4789
4790 // ======================== Windows =============================
4791
4792 // These codes get special messages
4793 WindowsGeneral(err::ExceptionCodeWindows::OUT_OF_MEMORY) => write!(f, "Out of Memory"),
4794 WindowsGeneral(err::ExceptionCodeWindows::UNHANDLED_CPP_EXCEPTION) => {
4795 write!(f, "Unhandled C++ Exception")
4796 }
4797 WindowsGeneral(err::ExceptionCodeWindows::SIMULATED) => {
4798 write!(f, "Simulated Exception")
4799 }
4800 // These codes just repeat their names
4801 WindowsGeneral(ex) => write!(f, "{ex:?}"),
4802 WindowsWinError(winerror) => write!(f, "{winerror:?}"),
4803 WindowsWinErrorWithFacility(facility, winerror) => {
4804 write!(f, "{facility:?} / {winerror:?}")
4805 }
4806 WindowsNtStatus(nt_status) => write_nt_status(f, nt_status as _),
4807 WindowsAccessViolation(ex) => write!(f, "EXCEPTION_ACCESS_VIOLATION_{ex:?}"),
4808 WindowsInPageError(ex, nt_status) => {
4809 write!(f, "EXCEPTION_IN_PAGE_ERROR_{ex:?} / ")?;
4810 write_nt_status(f, nt_status)
4811 }
4812 WindowsStackBufferOverrun(fast_fail) => {
4813 write!(f, "EXCEPTION_STACK_BUFFER_OVERRUN / ")?;
4814 write_fast_fail(f, fast_fail)
4815 }
4816 WindowsUnknown(code) => write!(f, "unknown {code:#010x}"),
4817
4818 Unknown(code, flags) => write!(f, "unknown {code:#010x} / {flags:#010x}"),
4819 }
4820 }
4821 }
4822
4823 impl<'a> MinidumpStream<'a> for MinidumpException<'a> {
4824 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::ExceptionStream as u32;
4825
4826 fn read(
4827 bytes: &'a [u8],
4828 all: &'a [u8],
4829 endian: scroll::Endian,
4830 _system_info: Option<&MinidumpSystemInfo>,
4831 ) -> Result<Self, Error> {
4832 let raw: md::MINIDUMP_EXCEPTION_STREAM = bytes
4833 .pread_with(0, endian)
4834 .or(Err(Error::StreamReadFailure))?;
4835 let context = location_slice(all, &raw.thread_context).ok();
4836 let thread_id = raw.thread_id;
4837 Ok(MinidumpException {
4838 raw,
4839 thread_id,
4840 context,
4841 endian,
4842 })
4843 }
4844 }
4845
4846 impl<'a> MinidumpException<'a> {
4847 /// Get the cpu context of the crashing (or otherwise minidump-requesting) thread.
4848 ///
4849 /// CPU contexts are a platform-specific format, so SystemInfo is required
4850 /// to reliably parse them. We used to use heuristics to avoid this requirement,
4851 /// but this made us too brittle to otherwise-backwards-compatible additions
4852 /// to the format.
4853 ///
4854 /// MiscInfo can contain additional details on the cpu context's format, but
4855 /// is optional because those details can be safely ignored (at the cost of
4856 /// being unable to parse some very obscure cpu state).
4857 pub fn context(
4858 &self,
4859 system_info: &MinidumpSystemInfo,
4860 misc: Option<&MinidumpMiscInfo>,
4861 ) -> Option<Cow<'a, MinidumpContext>> {
4862 MinidumpContext::read(self.context?, self.endian, system_info, misc)
4863 .ok()
4864 .map(Cow::Owned)
4865 }
4866
4867 /// Get the address that "caused" the crash.
4868 ///
4869 /// The meaning of this value depends on the kind of crash this was.
4870 ///
4871 /// By default, it's the instruction pointer at the time of the crash.
4872 /// However, if the crash was caused by an illegal memory access, the
4873 /// the address would be the memory address.
4874 ///
4875 /// So for instance, if you crashed from dereferencing a null pointer,
4876 /// the crash_address will be 0 (or close to it, due to offsets).
4877 pub fn get_crash_address(&self, os: Os, cpu: Cpu) -> u64 {
4878 let addr = match (
4879 os,
4880 err::ExceptionCodeWindows::from_u32(self.raw.exception_record.exception_code),
4881 ) {
4882 (Os::Windows, Some(err::ExceptionCodeWindows::EXCEPTION_ACCESS_VIOLATION))
4883 | (Os::Windows, Some(err::ExceptionCodeWindows::EXCEPTION_IN_PAGE_ERROR))
4884 if self.raw.exception_record.number_parameters >= 2 =>
4885 {
4886 self.raw.exception_record.exception_information[1]
4887 }
4888 _ => self.raw.exception_record.exception_address,
4889 };
4890
4891 // Sometimes on 32-bit these values can be incorrectly sign-extended,
4892 // so mask and zero-extend them here.
4893 match cpu.pointer_width() {
4894 PointerWidth::Bits32 => addr as u32 as u64,
4895 _ => addr,
4896 }
4897 }
4898
4899 /// Get the crash reason for an exception.
4900 ///
4901 /// The returned value reflects our best attempt to recover a
4902 /// "native" error for the crashing system based on the OS and
4903 /// things like raw error codes.
4904 ///
4905 /// This is an imperfect process, because OSes may have overlapping
4906 /// error types (e.g. WinError and NTSTATUS overlap, so we have to
4907 /// pick one arbirarily).
4908 ///
4909 /// The raw error codes can be extracted from [MinidumpException::raw][].
4910 pub fn get_crash_reason(&self, os: Os, cpu: Cpu) -> CrashReason {
4911 CrashReason::from_exception(&self.raw, os, cpu)
4912 }
4913
4914 /// The id of the thread that caused the crash (or otherwise requested
4915 /// the minidump, even if there wasn't actually a crash).
4916 pub fn get_crashing_thread_id(&self) -> u32 {
4917 self.thread_id
4918 }
4919
4920 /// Write a human-readable description of this `MinidumpException` to `f`.
4921 ///
4922 /// This is very verbose, it is the format used by `minidump_dump`.
4923 pub fn print<T: Write>(
4924 &self,
4925 f: &mut T,
4926 system: Option<&MinidumpSystemInfo>,
4927 misc: Option<&MinidumpMiscInfo>,
4928 ) -> io::Result<()> {
4929 write!(
4930 f,
4931 "MINIDUMP_EXCEPTION
4932 thread_id = {:#x}
4933 exception_record.exception_code = {:#x}
4934 exception_record.exception_flags = {:#x}
4935 exception_record.exception_record = {:#x}
4936 exception_record.exception_address = {:#x}
4937 exception_record.number_parameters = {}
4938 ",
4939 self.thread_id,
4940 self.raw.exception_record.exception_code,
4941 self.raw.exception_record.exception_flags,
4942 self.raw.exception_record.exception_record,
4943 self.raw.exception_record.exception_address,
4944 self.raw.exception_record.number_parameters,
4945 )?;
4946 for i in 0..self.raw.exception_record.number_parameters as usize {
4947 writeln!(
4948 f,
4949 " exception_record.exception_information[{:2}] = {:#x}",
4950 i, self.raw.exception_record.exception_information[i]
4951 )?;
4952 }
4953 write!(
4954 f,
4955 " thread_context.data_size = {}
4956 thread_context.rva = {:#x}
4957 ",
4958 self.raw.thread_context.data_size, self.raw.thread_context.rva
4959 )?;
4960 if let Some(system_info) = system {
4961 if let Some(context) = self.context(system_info, misc) {
4962 writeln!(f)?;
4963 context.print(f)?;
4964 } else {
4965 write!(
4966 f,
4967 " (no context)
4968
4969 "
4970 )?;
4971 }
4972 } else {
4973 write!(
4974 f,
4975 " (no context)
4976
4977 "
4978 )?;
4979 }
4980 Ok(())
4981 }
4982 }
4983
4984 impl<'a> MinidumpStream<'a> for MinidumpAssertion {
4985 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::AssertionInfoStream as u32;
4986
4987 fn read(
4988 bytes: &'a [u8],
4989 _all: &'a [u8],
4990 endian: scroll::Endian,
4991 _system_info: Option<&MinidumpSystemInfo>,
4992 ) -> Result<MinidumpAssertion, Error> {
4993 let raw: md::MINIDUMP_ASSERTION_INFO = bytes
4994 .pread_with(0, endian)
4995 .or(Err(Error::StreamReadFailure))?;
4996 Ok(MinidumpAssertion { raw })
4997 }
4998 }
4999
5000 fn utf16_to_string(data: &[u16]) -> Option<String> {
5001 use std::slice;
5002
5003 let len = data.iter().take_while(|c| **c != 0).count();
5004 let s16 = &data[..len];
5005 let bytes = unsafe { slice::from_raw_parts(s16.as_ptr() as *const u8, s16.len() * 2) };
5006 encoding_rs::UTF_16LE
5007 .decode_without_bom_handling_and_without_replacement(bytes)
5008 .map(String::from)
5009 }
5010
5011 impl MinidumpAssertion {
5012 /// Get the assertion expression as a `String` if one exists.
5013 pub fn expression(&self) -> Option<String> {
5014 utf16_to_string(&self.raw.expression)
5015 }
5016 /// Get the function name where the assertion happened as a `String` if it exists.
5017 pub fn function(&self) -> Option<String> {
5018 utf16_to_string(&self.raw.function)
5019 }
5020 /// Get the source file name where the assertion happened as a `String` if it exists.
5021 pub fn file(&self) -> Option<String> {
5022 utf16_to_string(&self.raw.file)
5023 }
5024
5025 /// Write a human-readable description of this `MinidumpAssertion` to `f`.
5026 ///
5027 /// This is very verbose, it is the format used by `minidump_dump`.
5028 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
5029 write!(
5030 f,
5031 "MDAssertion
5032 expression = {}
5033 function = {}
5034 file = {}
5035 line = {}
5036 type = {}
5037
5038 ",
5039 self.expression().unwrap_or_default(),
5040 self.function().unwrap_or_default(),
5041 self.file().unwrap_or_default(),
5042 self.raw.line,
5043 self.raw._type,
5044 )?;
5045 Ok(())
5046 }
5047 }
5048
5049 fn read_string_list(
5050 all: &[u8],
5051 location: &md::MINIDUMP_LOCATION_DESCRIPTOR,
5052 endian: scroll::Endian,
5053 ) -> Result<Vec<String>, Error> {
5054 let data = location_slice(all, location).or(Err(Error::StreamReadFailure))?;
5055 if data.is_empty() {
5056 return Ok(Vec::new());
5057 }
5058
5059 let mut offset = 0;
5060
5061 let count: u32 = data
5062 .gread_with(&mut offset, endian)
5063 .or(Err(Error::StreamReadFailure))?;
5064
5065 let (count, _) = ensure_count_in_bound(all, count as usize, <md::RVA>::size_with(&endian), 0)?;
5066
5067 let mut strings = Vec::with_capacity(count);
5068 for _ in 0..count {
5069 let rva: md::RVA = data
5070 .gread_with(&mut offset, endian)
5071 .or(Err(Error::StreamReadFailure))?;
5072
5073 let string = read_string_utf8(&mut (rva as usize), all, endian)
5074 .ok_or(Error::StreamReadFailure)?
5075 .to_owned();
5076
5077 strings.push(string);
5078 }
5079
5080 Ok(strings)
5081 }
5082
5083 fn read_simple_string_dictionary(
5084 all: &[u8],
5085 location: &md::MINIDUMP_LOCATION_DESCRIPTOR,
5086 endian: scroll::Endian,
5087 ) -> Result<BTreeMap<String, String>, Error> {
5088 let mut dictionary = BTreeMap::new();
5089
5090 let data = location_slice(all, location).or(Err(Error::StreamReadFailure))?;
5091 if data.is_empty() {
5092 return Ok(dictionary);
5093 }
5094
5095 let mut offset = 0;
5096
5097 let count: u32 = data
5098 .gread_with(&mut offset, endian)
5099 .or(Err(Error::StreamReadFailure))?;
5100
5101 for _ in 0..count {
5102 let entry: md::MINIDUMP_SIMPLE_STRING_DICTIONARY_ENTRY = data
5103 .gread_with(&mut offset, endian)
5104 .or(Err(Error::StreamReadFailure))?;
5105
5106 let key = read_string_utf8(&mut (entry.key as usize), all, endian)
5107 .ok_or(Error::StreamReadFailure)?;
5108 let value = read_string_utf8(&mut (entry.value as usize), all, endian)
5109 .ok_or(Error::StreamReadFailure)?;
5110
5111 dictionary.insert(key.to_owned(), value.to_owned());
5112 }
5113
5114 Ok(dictionary)
5115 }
5116
5117 fn read_annotation_objects(
5118 all: &[u8],
5119 location: &md::MINIDUMP_LOCATION_DESCRIPTOR,
5120 endian: scroll::Endian,
5121 ) -> Result<BTreeMap<String, MinidumpAnnotation>, Error> {
5122 let mut dictionary = BTreeMap::new();
5123
5124 let data = location_slice(all, location).or(Err(Error::StreamReadFailure))?;
5125 if data.is_empty() {
5126 return Ok(dictionary);
5127 }
5128
5129 let mut offset = 0;
5130
5131 let count: u32 = data
5132 .gread_with(&mut offset, endian)
5133 .or(Err(Error::StreamReadFailure))?;
5134
5135 for _ in 0..count {
5136 let raw: md::MINIDUMP_ANNOTATION = data
5137 .gread_with(&mut offset, endian)
5138 .or(Err(Error::StreamReadFailure))?;
5139
5140 let key = read_string_utf8(&mut (raw.name as usize), all, endian)
5141 .ok_or(Error::StreamReadFailure)?;
5142
5143 let value = match raw.ty {
5144 md::MINIDUMP_ANNOTATION::TYPE_INVALID => MinidumpAnnotation::Invalid,
5145 md::MINIDUMP_ANNOTATION::TYPE_STRING => {
5146 let string = read_string_utf8_unterminated(&mut (raw.value as usize), all, endian)
5147 .ok_or(Error::StreamReadFailure)?
5148 .to_owned();
5149
5150 MinidumpAnnotation::String(string)
5151 }
5152 _ if raw.ty >= md::MINIDUMP_ANNOTATION::TYPE_USER_DEFINED => {
5153 MinidumpAnnotation::UserDefined(raw)
5154 }
5155 _ => MinidumpAnnotation::Unsupported(raw),
5156 };
5157
5158 dictionary.insert(key.to_owned(), value);
5159 }
5160
5161 Ok(dictionary)
5162 }
5163
5164 impl MinidumpModuleCrashpadInfo {
5165 pub fn read(
5166 link: md::MINIDUMP_MODULE_CRASHPAD_INFO_LINK,
5167 all: &[u8],
5168 endian: scroll::Endian,
5169 ) -> Result<Self, Error> {
5170 let raw: md::MINIDUMP_MODULE_CRASHPAD_INFO = all
5171 .pread_with(link.location.rva as usize, endian)
5172 .or(Err(Error::StreamReadFailure))?;
5173
5174 let list_annotations = read_string_list(all, &raw.list_annotations, endian)?;
5175 let simple_annotations =
5176 read_simple_string_dictionary(all, &raw.simple_annotations, endian)?;
5177 let annotation_objects = read_annotation_objects(all, &raw.annotation_objects, endian)?;
5178
5179 Ok(Self {
5180 raw,
5181 module_index: link.minidump_module_list_index as usize,
5182 list_annotations,
5183 simple_annotations,
5184 annotation_objects,
5185 })
5186 }
5187 }
5188
5189 fn read_crashpad_module_links(
5190 all: &[u8],
5191 location: &md::MINIDUMP_LOCATION_DESCRIPTOR,
5192 endian: scroll::Endian,
5193 ) -> Result<Vec<MinidumpModuleCrashpadInfo>, Error> {
5194 let data = location_slice(all, location).or(Err(Error::StreamReadFailure))?;
5195 if data.is_empty() {
5196 return Ok(Vec::new());
5197 }
5198
5199 let mut offset = 0;
5200
5201 let count: u32 = data
5202 .gread_with(&mut offset, endian)
5203 .or(Err(Error::StreamReadFailure))?;
5204
5205 let (count, _) = ensure_count_in_bound(
5206 all,
5207 count as usize,
5208 <md::MINIDUMP_MODULE_CRASHPAD_INFO_LINK>::size_with(&endian),
5209 0,
5210 )?;
5211
5212 let mut module_links = Vec::with_capacity(count);
5213 for _ in 0..count {
5214 let link: md::MINIDUMP_MODULE_CRASHPAD_INFO_LINK = data
5215 .gread_with(&mut offset, endian)
5216 .or(Err(Error::StreamReadFailure))?;
5217
5218 let info = MinidumpModuleCrashpadInfo::read(link, all, endian)?;
5219 module_links.push(info);
5220 }
5221
5222 Ok(module_links)
5223 }
5224
5225 impl<'a> MinidumpStream<'a> for MinidumpCrashpadInfo {
5226 const STREAM_TYPE: u32 = MINIDUMP_STREAM_TYPE::CrashpadInfoStream as u32;
5227
5228 fn read(
5229 bytes: &'a [u8],
5230 all: &'a [u8],
5231 endian: scroll::Endian,
5232 _system_info: Option<&MinidumpSystemInfo>,
5233 ) -> Result<Self, Error> {
5234 let raw: md::MINIDUMP_CRASHPAD_INFO = bytes
5235 .pread_with(0, endian)
5236 .or(Err(Error::StreamReadFailure))?;
5237
5238 if raw.version == 0 {
5239 // 0 is an invalid version, but all future versions are compatible with v1.
5240 return Err(Error::VersionMismatch);
5241 }
5242
5243 let simple_annotations =
5244 read_simple_string_dictionary(all, &raw.simple_annotations, endian)?;
5245
5246 let module_list = read_crashpad_module_links(all, &raw.module_list, endian)?;
5247
5248 Ok(Self {
5249 raw,
5250 simple_annotations,
5251 module_list,
5252 })
5253 }
5254 }
5255
5256 impl MinidumpCrashpadInfo {
5257 /// Write a human-readable description of this `MinidumpCrashpadInfo` to `f`.
5258 ///
5259 /// This is very verbose, it is the format used by `minidump_dump`.
5260 pub fn print<T: Write>(&self, f: &mut T) -> io::Result<()> {
5261 write!(
5262 f,
5263 "MDRawCrashpadInfo
5264 version = {}
5265 report_id = {}
5266 client_id = {}
5267 ",
5268 self.raw.version, self.raw.report_id, self.raw.client_id,
5269 )?;
5270
5271 for (name, value) in &self.simple_annotations {
5272 writeln!(f, " simple_annotations[\"{name}\"] = {value}")?;
5273 }
5274
5275 for (index, module) in self.module_list.iter().enumerate() {
5276 writeln!(
5277 f,
5278 " module_list[{}].minidump_module_list_index = {}",
5279 index, module.module_index,
5280 )?;
5281 writeln!(
5282 f,
5283 " module_list[{}].version = {}",
5284 index, module.raw.version,
5285 )?;
5286
5287 for (annotation_index, annotation) in module.list_annotations.iter().enumerate() {
5288 writeln!(
5289 f,
5290 " module_list[{index}].list_annotations[{annotation_index}] = {annotation}",
5291 )?;
5292 }
5293
5294 for (name, value) in &module.simple_annotations {
5295 writeln!(
5296 f,
5297 " module_list[{index}].simple_annotations[\"{name}\"] = {value}",
5298 )?;
5299 }
5300
5301 for (name, value) in &module.annotation_objects {
5302 write!(
5303 f,
5304 " module_list[{index}].annotation_objects[\"{name}\"] = ",
5305 )?;
5306
5307 match value {
5308 MinidumpAnnotation::Invalid => writeln!(f, "<invalid>"),
5309 MinidumpAnnotation::String(string) => writeln!(f, "{string}"),
5310 MinidumpAnnotation::UserDefined(_) => writeln!(f, "<user defined>"),
5311 MinidumpAnnotation::Unsupported(_) => writeln!(f, "<unsupported>"),
5312 }?;
5313 }
5314 }
5315
5316 writeln!(f)?;
5317
5318 Ok(())
5319 }
5320 }
5321
5322 /// An index into the contents of a memory-mapped minidump.
5323 pub type MmapMinidump = Minidump<'static, Mmap>;
5324
5325 impl MmapMinidump {
5326 /// Read a `Minidump` from a `Path` to a file on disk.
5327 ///
5328 /// See [the type definition](Minidump.html) for an example.
5329 pub fn read_path<P>(path: P) -> Result<MmapMinidump, Error>
5330 where
5331 P: AsRef<Path>,
5332 {
5333 let f = File::open(path).or(Err(Error::FileNotFound))?;
5334 let mmap = unsafe { Mmap::map(&f).or(Err(Error::IoError))? };
5335 Minidump::read(mmap)
5336 }
5337 }
5338
5339 /// A stream in the minidump that this implementation can interpret,
5340 #[derive(Debug)]
5341 pub struct MinidumpImplementedStream {
5342 pub stream_type: MINIDUMP_STREAM_TYPE,
5343 pub location: md::MINIDUMP_LOCATION_DESCRIPTOR,
5344 pub vendor: &'static str,
5345 }
5346
5347 /// A stream in the minidump that this implementation has no knowledge of.
5348 #[derive(Debug, Clone)]
5349 pub struct MinidumpUnknownStream {
5350 pub stream_type: u32,
5351 pub location: md::MINIDUMP_LOCATION_DESCRIPTOR,
5352 pub vendor: &'static str,
5353 }
5354
5355 /// A stream in the minidump that this implementation is aware of but doesn't
5356 /// yet support.
5357 #[derive(Debug, Clone)]
5358 pub struct MinidumpUnimplementedStream {
5359 pub stream_type: MINIDUMP_STREAM_TYPE,
5360 pub location: md::MINIDUMP_LOCATION_DESCRIPTOR,
5361 pub vendor: &'static str,
5362 }
5363
5364 impl<'a, T> Minidump<'a, T>
5365 where
5366 T: Deref<Target = [u8]> + 'a,
5367 {
5368 /// Read a `Minidump` from the provided `data`.
5369 ///
5370 /// Typically this will be a `Vec<u8>` or `&[u8]` with the full contents of the minidump,
5371 /// but you can also use something like `memmap::Mmap`.
5372 pub fn read(data: T) -> Result<Minidump<'a, T>, Error> {
5373 let mut offset = 0;
5374 let mut endian = LE;
5375 let mut header: md::MINIDUMP_HEADER = data
5376 .gread_with(&mut offset, endian)
5377 .or(Err(Error::MissingHeader))?;
5378 if header.signature != md::MINIDUMP_SIGNATURE {
5379 if header.signature.swap_bytes() != md::MINIDUMP_SIGNATURE {
5380 return Err(Error::HeaderMismatch);
5381 }
5382 // Try again with big-endian.
5383 endian = BE;
5384 offset = 0;
5385 header = data
5386 .gread_with(&mut offset, endian)
5387 .or(Err(Error::MissingHeader))?;
5388 if header.signature != md::MINIDUMP_SIGNATURE {
5389 return Err(Error::HeaderMismatch);
5390 }
5391 }
5392 if (header.version & 0x0000ffff) != md::MINIDUMP_VERSION {
5393 return Err(Error::VersionMismatch);
5394 }
5395
5396 offset = header.stream_directory_rva as usize;
5397
5398 let mut streams = BTreeMap::new();
5399 for i in 0..header.stream_count {
5400 let dir: md::MINIDUMP_DIRECTORY = data
5401 .gread_with(&mut offset, endian)
5402 .or(Err(Error::MissingDirectory))?;
5403 if let Some((old_idx, old_dir)) = streams.insert(dir.stream_type, (i, dir.clone())) {
5404 if let Some(known_stream_type) = MINIDUMP_STREAM_TYPE::from_u32(dir.stream_type) {
5405 if !(known_stream_type == MINIDUMP_STREAM_TYPE::UnusedStream
5406 && old_dir.location.data_size == 0
5407 && dir.location.data_size == 0)
5408 {
5409 warn!("Minidump contains multiple streams of type {} ({:?}) at indices {} ({} bytes) and {} ({} bytes) (using {})",
5410 dir.stream_type,
5411 known_stream_type,
5412 old_idx,
5413 old_dir.location.data_size,
5414 i,
5415 dir.location.data_size,
5416 i,
5417 );
5418 }
5419 } else {
5420 warn!("Minidump contains multiple streams of unknown type {} at indices {} ({} bytes) and {} ({} bytes) (using {})",
5421 dir.stream_type,
5422 old_idx,
5423 old_dir.location.data_size,
5424 i,
5425 dir.location.data_size,
5426 i,
5427 );
5428 }
5429 }
5430 }
5431 let system_info = streams
5432 .get(&MinidumpSystemInfo::STREAM_TYPE)
5433 .and_then(|(_, dir)| {
5434 location_slice(data.deref(), &dir.location)
5435 .ok()
5436 .and_then(|bytes| {
5437 let all_bytes = data.deref();
5438 MinidumpSystemInfo::read(bytes, all_bytes, endian, None).ok()
5439 })
5440 });
5441
5442 Ok(Minidump {
5443 data,
5444 header,
5445 streams,
5446 endian,
5447 system_info,
5448 _phantom: PhantomData,
5449 })
5450 }
5451
5452 /// Read and parse the specified [`MinidumpStream`][] `S` from the Minidump, if it exists.
5453 ///
5454 /// Because Minidump Streams can have totally different formats and meanings, the only
5455 /// way to coherently access one is by specifying a static type that provides an
5456 /// interpretation and interface of that format.
5457 ///
5458 /// As such, typical usage of this interface is to just statically request every
5459 /// stream your care about. Depending on what analysis you're trying to perform, you may:
5460 ///
5461 /// * Consider it an error for a stream to be missing (using `?` or `unwrap`)
5462 /// * Branch on the presence of stream to conditionally refine your analysis
5463 /// * Use a stream's `Default` implementation to make progress (with `unwrap_or_default`)
5464 ///
5465 /// ```
5466 /// use minidump::*;
5467 ///
5468 /// fn main() -> Result<(), Error> {
5469 /// // Read the minidump from a file
5470 /// let mut dump = minidump::Minidump::read_path("../testdata/test.dmp")?;
5471 ///
5472 /// // Statically request (and require) several streams we care about:
5473 /// let system_info = dump.get_stream::<MinidumpSystemInfo>()?;
5474 /// let exception = dump.get_stream::<MinidumpException>()?;
5475 ///
5476 /// // Combine the contents of the streams to perform more refined analysis
5477 /// let crash_reason = exception.get_crash_reason(system_info.os, system_info.cpu);
5478 ///
5479 /// // Conditionally analyze a stream
5480 /// if let Ok(threads) = dump.get_stream::<MinidumpThreadList>() {
5481 /// // Use `Default` to try to make some progress when a stream is missing.
5482 /// // This is especially natural for MinidumpMemoryList because
5483 /// // everything needs to handle memory lookups failing anyway.
5484 /// let mem = dump.get_memory().unwrap_or_default();
5485 ///
5486 /// for thread in &threads.threads {
5487 /// let stack = thread.stack_memory(&mem);
5488 /// // ...
5489 /// }
5490 /// }
5491 ///
5492 /// Ok(())
5493 /// }
5494 /// ```
5495 ///
5496 /// Some streams are impossible to fully parse/interpret without the contents
5497 /// of other streams (for instance, many things require [`MinidumpSystemInfo`][] to interpret
5498 /// hardware-specific details). As a result, some parsing of the stream may be
5499 /// further deferred to methods on the Stream type where those dependencies can be provided
5500 /// (e.g. [`MinidumpException::get_crash_reason`][]).
5501 ///
5502 /// Note that the lifetime of the returned stream is bound to the lifetime of the
5503 /// `Minidump` struct itself and not to the lifetime of the data backing this minidump.
5504 /// This is a consequence of how this struct relies on [`Deref`][] to access the data.
5505 ///
5506 /// ## Currently Supported Streams
5507 ///
5508 /// * [`MinidumpAssertion`][]
5509 /// * [`MinidumpBreakpadInfo`][]
5510 /// * [`MinidumpCrashpadInfo`][]
5511 /// * [`MinidumpException`][]
5512 /// * [`MinidumpLinuxCpuInfo`][]
5513 /// * [`MinidumpLinuxEnviron`][]
5514 /// * [`MinidumpLinuxLsbRelease`][]
5515 /// * [`MinidumpLinuxMaps`][]
5516 /// * [`MinidumpLinuxProcStatus`][]
5517 /// * [`MinidumpMacCrashInfo`][]
5518 /// * [`MinidumpMacBootargs`][]
5519 /// * [`MinidumpMemoryList`][]
5520 /// * [`MinidumpMemory64List`][]
5521 /// * [`MinidumpMemoryInfoList`][]
5522 /// * [`MinidumpMiscInfo`][]
5523 /// * [`MinidumpModuleList`][]
5524 /// * [`MinidumpSystemInfo`][]
5525 /// * [`MinidumpThreadList`][]
5526 /// * [`MinidumpThreadNames`][]
5527 /// * [`MinidumpUnloadedModuleList`][]
5528 /// * [`MinidumpHandleDataStream`][]
5529 ///
5530 pub fn get_stream<S>(&'a self) -> Result<S, Error>
5531 where
5532 S: MinidumpStream<'a>,
5533 {
5534 match self.get_raw_stream(S::STREAM_TYPE) {
5535 Err(e) => Err(e),
5536 Ok(bytes) => {
5537 let all_bytes = self.data.deref();
5538 S::read(bytes, all_bytes, self.endian, self.system_info.as_ref())
5539 }
5540 }
5541 }
5542
5543 /// Get a stream of raw data from the minidump.
5544 ///
5545 /// This can be used to get the contents of arbitrary minidump streams.
5546 /// For streams of known types you almost certainly want to use
5547 /// [`Minidump::get_stream`][] instead.
5548 ///
5549 /// Note that the lifetime of the returned stream is bound to the lifetime of the this
5550 /// `Minidump` struct itself and not to the lifetime of the data backing this minidump.
5551 /// This is a consequence of how this struct relies on [Deref] to access the data.
5552 pub fn get_raw_stream(&'a self, stream_type: u32) -> Result<&'a [u8], Error> {
5553 match self.streams.get(&stream_type) {
5554 None => Err(Error::StreamNotFound),
5555 Some((_, dir)) => {
5556 let bytes = self.data.deref();
5557 location_slice(bytes, &dir.location)
5558 }
5559 }
5560 }
5561
5562 /// Get whichever of the two MemoryLists are available in the minidump,
5563 /// preferring [`MinidumpMemory64List`][].
5564 pub fn get_memory(&'a self) -> Option<UnifiedMemoryList<'a>> {
5565 self.get_stream::<MinidumpMemory64List>()
5566 .map(UnifiedMemoryList::Memory64)
5567 .or_else(|_| {
5568 self.get_stream::<MinidumpMemoryList>()
5569 .map(UnifiedMemoryList::Memory)
5570 })
5571 .ok()
5572 }
5573
5574 /// A listing of all the streams in the Minidump that this library is *aware* of,
5575 /// but has no further analysis for.
5576 ///
5577 /// If there are multiple copies of the same stream type (which should not happen for
5578 /// well-formed Minidumps), then only one of them will be yielded, arbitrarily.
5579 pub fn unimplemented_streams(&self) -> impl Iterator<Item = MinidumpUnimplementedStream> + '_ {
5580 static UNIMPLEMENTED_STREAMS: [MINIDUMP_STREAM_TYPE; 30] = [
5581 // Presumably will never have an implementation:
5582 MINIDUMP_STREAM_TYPE::UnusedStream,
5583 MINIDUMP_STREAM_TYPE::ReservedStream0,
5584 MINIDUMP_STREAM_TYPE::ReservedStream1,
5585 MINIDUMP_STREAM_TYPE::LastReservedStream,
5586 // Presumably should be implemented:
5587 MINIDUMP_STREAM_TYPE::ThreadExListStream,
5588 MINIDUMP_STREAM_TYPE::CommentStreamA,
5589 MINIDUMP_STREAM_TYPE::CommentStreamW,
5590 MINIDUMP_STREAM_TYPE::FunctionTable,
5591 MINIDUMP_STREAM_TYPE::HandleOperationListStream,
5592 MINIDUMP_STREAM_TYPE::TokenStream,
5593 MINIDUMP_STREAM_TYPE::JavaScriptDataStream,
5594 MINIDUMP_STREAM_TYPE::SystemMemoryInfoStream,
5595 MINIDUMP_STREAM_TYPE::ProcessVmCountersStream,
5596 MINIDUMP_STREAM_TYPE::IptTraceStream,
5597 // Windows CE streams, very unlikely to be found in the wild.
5598 // Their contents are documented here: https://docs.microsoft.com/en-us/previous-versions/windows/embedded/ms939618(v=msdn.10)
5599 MINIDUMP_STREAM_TYPE::ceStreamNull,
5600 MINIDUMP_STREAM_TYPE::ceStreamSystemInfo,
5601 MINIDUMP_STREAM_TYPE::ceStreamException,
5602 MINIDUMP_STREAM_TYPE::ceStreamModuleList,
5603 MINIDUMP_STREAM_TYPE::ceStreamProcessList,
5604 MINIDUMP_STREAM_TYPE::ceStreamThreadList,
5605 MINIDUMP_STREAM_TYPE::ceStreamThreadContextList,
5606 MINIDUMP_STREAM_TYPE::ceStreamThreadCallStackList,
5607 MINIDUMP_STREAM_TYPE::ceStreamMemoryVirtualList,
5608 MINIDUMP_STREAM_TYPE::ceStreamMemoryPhysicalList,
5609 MINIDUMP_STREAM_TYPE::ceStreamBucketParameters,
5610 MINIDUMP_STREAM_TYPE::ceStreamProcessModuleMap,
5611 MINIDUMP_STREAM_TYPE::ceStreamDiagnosisList,
5612 // non-standard streams (should also be implemented):
5613 MINIDUMP_STREAM_TYPE::LinuxCmdLine,
5614 MINIDUMP_STREAM_TYPE::LinuxAuxv,
5615 MINIDUMP_STREAM_TYPE::LinuxDsoDebug,
5616 ];
5617 self.streams.iter().filter_map(|(_, (_, stream))| {
5618 MINIDUMP_STREAM_TYPE::from_u32(stream.stream_type).and_then(|stream_type| {
5619 if UNIMPLEMENTED_STREAMS.contains(&stream_type) {
5620 return Some(MinidumpUnimplementedStream {
5621 stream_type,
5622 location: stream.location,
5623 vendor: stream_vendor(stream.stream_type),
5624 });
5625 }
5626 None
5627 })
5628 })
5629 }
5630
5631 /// A listing of all the streams in the Minidump that this library has no knowledge of.
5632 ///
5633 /// If there are multiple copies of the same stream (which should not happen for
5634 /// well-formed Minidumps), then only one of them will be yielded, arbitrarily.
5635 pub fn unknown_streams(&self) -> impl Iterator<Item = MinidumpUnknownStream> + '_ {
5636 self.streams.iter().filter_map(|(_, (_, stream))| {
5637 if MINIDUMP_STREAM_TYPE::from_u32(stream.stream_type).is_none() {
5638 return Some(MinidumpUnknownStream {
5639 stream_type: stream.stream_type,
5640 location: stream.location,
5641 vendor: stream_vendor(stream.stream_type),
5642 });
5643 }
5644 None
5645 })
5646 }
5647
5648 /// A listing of all the streams in the Minidump.
5649 ///
5650 /// If there are multiple copies of the same stream (which should not happen for
5651 /// well-formed Minidumps), then only one of them will be yielded, arbitrarily.
5652 pub fn all_streams(&self) -> impl Iterator<Item = &md::MINIDUMP_DIRECTORY> + '_ {
5653 self.streams.iter().map(|(_, (_, stream))| stream)
5654 }
5655
5656 /// Write a verbose description of the `Minidump` to `f`.
5657 pub fn print<W: Write>(&self, f: &mut W) -> io::Result<()> {
5658 fn get_stream_name(stream_type: u32) -> Cow<'static, str> {
5659 if let Some(stream) = MINIDUMP_STREAM_TYPE::from_u32(stream_type) {
5660 Cow::Owned(format!("{stream:?}"))
5661 } else {
5662 Cow::Borrowed("unknown")
5663 }
5664 }
5665
5666 write!(
5667 f,
5668 r#"MDRawHeader
5669 signature = {:#x}
5670 version = {:#x}
5671 stream_count = {}
5672 stream_directory_rva = {:#x}
5673 checksum = {:#x}
5674 time_date_stamp = {:#x} {}
5675 flags = {:#x}
5676
5677 "#,
5678 self.header.signature,
5679 self.header.version,
5680 self.header.stream_count,
5681 self.header.stream_directory_rva,
5682 self.header.checksum,
5683 self.header.time_date_stamp,
5684 format_time_t(self.header.time_date_stamp),
5685 self.header.flags,
5686 )?;
5687 let mut streams = self.streams.iter().collect::<Vec<_>>();
5688 streams.sort_by(|&(&_, &(a, _)), &(&_, &(b, _))| a.cmp(&b));
5689 for &(_, &(i, ref stream)) in streams.iter() {
5690 write!(
5691 f,
5692 r#"mDirectory[{}]
5693 MDRawDirectory
5694 stream_type = {:#x} ({})
5695 location.data_size = {}
5696 location.rva = {:#x}
5697
5698 "#,
5699 i,
5700 stream.stream_type,
5701 get_stream_name(stream.stream_type),
5702 stream.location.data_size,
5703 stream.location.rva
5704 )?;
5705 }
5706 writeln!(f, "Streams:")?;
5707 streams.sort_by(|&(&a, &(_, _)), &(&b, &(_, _))| a.cmp(&b));
5708 for (_, &(i, ref stream)) in streams {
5709 writeln!(
5710 f,
5711 " stream type {:#x} ({}) at index {}",
5712 stream.stream_type,
5713 get_stream_name(stream.stream_type),
5714 i
5715 )?;
5716 }
5717 writeln!(f)?;
5718 Ok(())
5719 }
5720 }
5721
5722 fn stream_vendor(stream_type: u32) -> &'static str {
5723 if stream_type <= MINIDUMP_STREAM_TYPE::LastReservedStream as u32 {
5724 "Official"
5725 } else {
5726 match stream_type & 0xFFFF0000 {
5727 0x4767_0000 => "Google Extension",
5728 0x4d7a_0000 => "Mozilla Extension",
5729 _ => "Unknown Extension",
5730 }
5731 }
5732 }
5733
5734 #[cfg(test)]
5735 mod test {
5736 use super::*;
5737 use md::GUID;
5738 use minidump_common::{
5739 errors::NtStatusWindows,
5740 format::{PlatformId, ProcessorArchitecture},
5741 };
5742 use minidump_synth::{
5743 AnnotationValue, CrashpadInfo, DumpString, Exception,
5744 HandleDescriptor as SynthHandleDescriptor, Memory, MemoryInfo as SynthMemoryInfo,
5745 MiscFieldsBuildString, MiscFieldsPowerInfo, MiscFieldsProcessTimes, MiscFieldsTimeZone,
5746 MiscInfo5Fields, MiscStream, Module as SynthModule, ModuleCrashpadInfo, SimpleStream,
5747 SynthMinidump, SystemInfo, Thread, ThreadName, UnloadedModule as SynthUnloadedModule,
5748 STOCK_VERSION_INFO,
5749 };
5750 use test_assembler::*;
5751
5752 fn read_synth_dump<'a>(dump: SynthMinidump) -> Result<Minidump<'a, Vec<u8>>, Error> {
5753 Minidump::read(dump.finish().unwrap())
5754 }
5755
5756 #[ctor::ctor]
5757 fn init_logger() {
5758 env_logger::builder().is_test(true).init();
5759 }
5760
5761 #[test]
5762 fn test_simple_synth_dump() {
5763 const STREAM_TYPE: u32 = 0x11223344;
5764 let dump = SynthMinidump::with_endian(Endian::Little).add_stream(SimpleStream {
5765 stream_type: STREAM_TYPE,
5766 section: Section::with_endian(Endian::Little).D32(0x55667788),
5767 });
5768 let dump = read_synth_dump(dump).unwrap();
5769 assert_eq!(dump.endian, LE);
5770 assert_eq!(
5771 dump.get_raw_stream(STREAM_TYPE).unwrap(),
5772 &[0x88, 0x77, 0x66, 0x55]
5773 );
5774
5775 assert_eq!(
5776 dump.get_raw_stream(0xaabbccddu32),
5777 Err(Error::StreamNotFound)
5778 );
5779 }
5780
5781 #[test]
5782 fn test_simple_synth_dump_bigendian() {
5783 const STREAM_TYPE: u32 = 0x11223344;
5784 let dump = SynthMinidump::with_endian(Endian::Big).add_stream(SimpleStream {
5785 stream_type: STREAM_TYPE,
5786 section: Section::with_endian(Endian::Big).D32(0x55667788),
5787 });
5788 let dump = read_synth_dump(dump).unwrap();
5789 assert_eq!(dump.endian, BE);
5790 assert_eq!(
5791 dump.get_raw_stream(STREAM_TYPE).unwrap(),
5792 &[0x55, 0x66, 0x77, 0x88]
5793 );
5794
5795 assert_eq!(
5796 dump.get_raw_stream(0xaabbccddu32),
5797 Err(Error::StreamNotFound)
5798 );
5799 }
5800
5801 #[test]
5802 fn test_thread_names() {
5803 let good_thread_id = 17;
5804 let corrupt_thread_id = 123;
5805
5806 let good_name = DumpString::new("MyCoolThread", Endian::Little);
5807 // No corrupt name, will dangle
5808
5809 let good_thread_name_entry =
5810 ThreadName::new(Endian::Little, good_thread_id, Some(&good_name));
5811 let corrupt_thread_name_entry = ThreadName::new(Endian::Little, corrupt_thread_id, None);
5812
5813 let dump = SynthMinidump::with_endian(Endian::Little)
5814 .add_thread_name(good_thread_name_entry)
5815 .add_thread_name(corrupt_thread_name_entry)
5816 .add(good_name);
5817
5818 let dump = read_synth_dump(dump).unwrap();
5819 let thread_names = dump.get_stream::<MinidumpThreadNames>().unwrap();
5820 assert_eq!(thread_names.names.len(), 1);
5821 assert_eq!(
5822 &*thread_names.get_name(good_thread_id).unwrap(),
5823 "MyCoolThread"
5824 );
5825 assert_eq!(thread_names.get_name(corrupt_thread_id), None);
5826 }
5827
5828 #[test]
5829 fn test_module_list() {
5830 let name = DumpString::new("single module", Endian::Little);
5831 let cv_record = Section::with_endian(Endian::Little)
5832 .D32(md::CvSignature::Pdb70 as u32) // signature
5833 // signature, a GUID
5834 .D32(0xabcd1234)
5835 .D16(0xf00d)
5836 .D16(0xbeef)
5837 .append_bytes(b"\x01\x02\x03\x04\x05\x06\x07\x08")
5838 .D32(1) // age
5839 .append_bytes(b"c:\\foo\\file.pdb\0"); // pdb_file_name
5840 let module = SynthModule::new(
5841 Endian::Little,
5842 0xa90206ca83eb2852,
5843 0xada542bd,
5844 &name,
5845 0xb1054d2a,
5846 0x34571371,
5847 Some(&STOCK_VERSION_INFO),
5848 )
5849 .cv_record(&cv_record);
5850 let dump = SynthMinidump::with_endian(Endian::Little)
5851 .add_module(module)
5852 .add(name)
5853 .add(cv_record);
5854 let dump = read_synth_dump(dump).unwrap();
5855 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
5856 let modules = module_list.iter().collect::<Vec<_>>();
5857 assert_eq!(modules.len(), 1);
5858 assert_eq!(modules[0].base_address(), 0xa90206ca83eb2852);
5859 assert_eq!(modules[0].size(), 0xada542bd);
5860 assert_eq!(modules[0].code_file(), "single module");
5861 // time_date_stamp and size_of_image concatenated
5862 assert_eq!(
5863 modules[0].code_identifier().unwrap(),
5864 CodeId::new("B1054D2Aada542bd".to_string())
5865 );
5866 assert_eq!(modules[0].debug_file().unwrap(), "c:\\foo\\file.pdb");
5867 assert_eq!(
5868 modules[0].debug_identifier().unwrap(),
5869 DebugId::from_breakpad("ABCD1234F00DBEEF01020304050607081").unwrap()
5870 );
5871 }
5872
5873 #[test]
5874 fn test_module_list_pdb20() {
5875 let name = DumpString::new("single module", Endian::Little);
5876 let cv_record = Section::with_endian(Endian::Little)
5877 .D32(md::CvSignature::Pdb20 as u32) // cv_signature
5878 .D32(0x0) // cv_offset
5879 .D32(0xabcd1234) // signature
5880 .D32(1) // age
5881 .append_bytes(b"c:\\foo\\file.pdb\0"); // pdb_file_name
5882 let module = SynthModule::new(
5883 Endian::Little,
5884 0xa90206ca83eb2852,
5885 0xada542bd,
5886 &name,
5887 0xb1054d2a,
5888 0x34571371,
5889 Some(&STOCK_VERSION_INFO),
5890 )
5891 .cv_record(&cv_record);
5892 let dump = SynthMinidump::with_endian(Endian::Little)
5893 .add_module(module)
5894 .add(name)
5895 .add(cv_record);
5896 let dump = read_synth_dump(dump).unwrap();
5897 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
5898 let modules = module_list.iter().collect::<Vec<_>>();
5899 assert_eq!(modules.len(), 1);
5900 assert_eq!(modules[0].base_address(), 0xa90206ca83eb2852);
5901 assert_eq!(modules[0].size(), 0xada542bd);
5902 assert_eq!(modules[0].code_file(), "single module");
5903 // time_date_stamp and size_of_image concatenated
5904 assert_eq!(
5905 modules[0].code_identifier().unwrap(),
5906 CodeId::new("B1054D2Aada542bd".to_string())
5907 );
5908 assert_eq!(modules[0].debug_file().unwrap(), "c:\\foo\\file.pdb");
5909 assert_eq!(
5910 modules[0].debug_identifier().unwrap(),
5911 DebugId::from_pdb20(0xabcd1234, 1)
5912 );
5913 }
5914
5915 #[test]
5916 fn test_unloaded_module_list() {
5917 let name = DumpString::new("single module", Endian::Little);
5918 let module = SynthUnloadedModule::new(
5919 Endian::Little,
5920 0xa90206ca83eb2852,
5921 0xada542bd,
5922 &name,
5923 0xb1054d2a,
5924 0x34571371,
5925 );
5926 let dump = SynthMinidump::with_endian(Endian::Little)
5927 .add_unloaded_module(module)
5928 .add(name);
5929 let dump = read_synth_dump(dump).unwrap();
5930 let module_list = dump.get_stream::<MinidumpUnloadedModuleList>().unwrap();
5931 let modules = module_list.iter().collect::<Vec<_>>();
5932 assert_eq!(modules.len(), 1);
5933 assert_eq!(modules[0].base_address(), 0xa90206ca83eb2852);
5934 assert_eq!(modules[0].size(), 0xada542bd);
5935 assert_eq!(modules[0].code_file(), "single module");
5936 // time_date_stamp and size_of_image concatenated
5937 assert_eq!(
5938 modules[0].code_identifier().unwrap(),
5939 CodeId::new("B1054D2Aada542bd".to_string())
5940 );
5941 }
5942
5943 #[test]
5944 fn test_memory_info() {
5945 let info1_alloc_protection = md::MemoryProtection::PAGE_GUARD;
5946 let info1_protection = md::MemoryProtection::PAGE_EXECUTE_READ;
5947 let info1_state = md::MemoryState::MEM_FREE;
5948 let info1_ty = md::MemoryType::MEM_MAPPED;
5949 let info1 = SynthMemoryInfo::new(
5950 Endian::Little,
5951 0xa90206ca83eb2852,
5952 0xa802064a83eb2752,
5953 info1_alloc_protection.bits(),
5954 0xf80e064a93eb2356,
5955 info1_state.bits(),
5956 info1_protection.bits(),
5957 info1_ty.bits(),
5958 );
5959
5960 let info2_alloc_protection = md::MemoryProtection::PAGE_EXECUTE_READ;
5961 let info2_protection = md::MemoryProtection::PAGE_READONLY;
5962 let info2_state = md::MemoryState::MEM_COMMIT;
5963 let info2_ty = md::MemoryType::MEM_PRIVATE;
5964 let info2 = SynthMemoryInfo::new(
5965 Endian::Little,
5966 0xd70206ca83eb2852,
5967 0xb802064383eb2752,
5968 info2_alloc_protection.bits(),
5969 0xe80e064a93eb2356,
5970 info2_state.bits(),
5971 info2_protection.bits(),
5972 info2_ty.bits(),
5973 );
5974 let dump = SynthMinidump::with_endian(Endian::Little)
5975 .add_memory_info(info1)
5976 .add_memory_info(info2);
5977
5978 let dump = read_synth_dump(dump).unwrap();
5979
5980 // Read both kinds of info to test this path on UnifiedMemoryInfo
5981 let info_list = dump.get_stream::<MinidumpMemoryInfoList>().ok();
5982 let maps = dump.get_stream::<MinidumpLinuxMaps>().ok();
5983 assert!(info_list.is_some());
5984 assert!(maps.is_none());
5985
5986 let unified_info = UnifiedMemoryInfoList::new(info_list, maps).unwrap();
5987 let info_list = unified_info.info().unwrap();
5988 assert!(unified_info.maps().is_none());
5989
5990 // Assert that unified and the info_list agree
5991 for (info, unified) in info_list.iter().zip(unified_info.iter()) {
5992 if let UnifiedMemoryInfo::Info(info2) = unified {
5993 assert_eq!(info, info2);
5994 } else {
5995 unreachable!();
5996 }
5997 }
5998
5999 let infos = info_list.iter().collect::<Vec<_>>();
6000
6001 assert_eq!(infos.len(), 2);
6002
6003 assert_eq!(infos[0].raw.base_address, 0xa90206ca83eb2852);
6004 assert_eq!(infos[0].raw.allocation_base, 0xa802064a83eb2752);
6005 assert_eq!(
6006 infos[0].raw.allocation_protection,
6007 info1_alloc_protection.bits()
6008 );
6009 assert_eq!(infos[0].raw.region_size, 0xf80e064a93eb2356);
6010 assert_eq!(infos[0].raw.state, info1_state.bits());
6011 assert_eq!(infos[0].raw.protection, info1_protection.bits());
6012 assert_eq!(infos[0].raw._type, info1_ty.bits());
6013
6014 assert_eq!(infos[0].allocation_protection, info1_alloc_protection);
6015 assert_eq!(infos[0].protection, info1_protection);
6016 assert_eq!(infos[0].state, info1_state);
6017 assert_eq!(infos[0].ty, info1_ty);
6018 assert!(infos[0].is_executable());
6019
6020 assert_eq!(infos[1].raw.base_address, 0xd70206ca83eb2852);
6021 assert_eq!(infos[1].raw.allocation_base, 0xb802064383eb2752);
6022 assert_eq!(
6023 infos[1].raw.allocation_protection,
6024 info2_alloc_protection.bits()
6025 );
6026 assert_eq!(infos[1].raw.region_size, 0xe80e064a93eb2356);
6027 assert_eq!(infos[1].raw.state, info2_state.bits());
6028 assert_eq!(infos[1].raw.protection, info2_protection.bits());
6029 assert_eq!(infos[1].raw._type, info2_ty.bits());
6030
6031 assert_eq!(infos[1].allocation_protection, info2_alloc_protection);
6032 assert_eq!(infos[1].protection, info2_protection);
6033 assert_eq!(infos[1].state, info2_state);
6034 assert_eq!(infos[1].ty, info2_ty);
6035 assert!(!infos[1].is_executable());
6036 }
6037
6038 #[test]
6039 fn test_linux_maps() {
6040 use procfs_core::process::{MMPermissions, MMapPath};
6041
6042 // TODO: is it okay to give up wonky whitespace support?
6043 let input =
6044 b"a90206ca83eb2852-b90206ca83eb3852 r-xp 10bac9000 fd:05 1196511 /usr/lib64/libtdb1.so\n\
6045 c70206ca83eb2852-de0206ca83eb2852 -w-s 10bac9000 fd:05 1196511 /usr/lib64/libtdb2.so (deleted)";
6046
6047 let dump = SynthMinidump::with_endian(Endian::Little).set_linux_maps(input);
6048 let dump = read_synth_dump(dump).unwrap();
6049
6050 // Read both kinds of info to test this path on UnifiedMemoryInfo
6051 let info_list = dump.get_stream::<MinidumpMemoryInfoList>().ok();
6052 let maps = dump.get_stream::<MinidumpLinuxMaps>().unwrap();
6053 assert!(info_list.is_none());
6054
6055 let unified_info = UnifiedMemoryInfoList::new(info_list, Some(maps)).unwrap();
6056 let maps = unified_info.maps().unwrap();
6057 assert!(unified_info.info().is_none());
6058
6059 // Assert that unified and the maps agree
6060 for (info, unified) in maps.iter().zip(unified_info.iter()) {
6061 if let UnifiedMemoryInfo::Map(info2) = unified {
6062 assert_eq!(info, info2);
6063 } else {
6064 unreachable!();
6065 }
6066 }
6067
6068 let maps = maps.iter().collect::<Vec<_>>();
6069 assert_eq!(maps.len(), 2);
6070
6071 assert_eq!(maps[0].map.address.0, 0xa90206ca83eb2852);
6072 assert_eq!(maps[0].map.address.1, 0xb90206ca83eb3852);
6073 assert_eq!(
6074 maps[0].map.pathname,
6075 MMapPath::Path("/usr/lib64/libtdb1.so".into())
6076 );
6077 assert!(
6078 maps[0].map.perms
6079 == MMPermissions::READ | MMPermissions::EXECUTE | MMPermissions::PRIVATE
6080 );
6081
6082 assert_eq!(maps[1].map.address.0, 0xc70206ca83eb2852);
6083 assert_eq!(maps[1].map.address.1, 0xde0206ca83eb2852);
6084 assert_eq!(
6085 maps[1].map.pathname,
6086 MMapPath::Path("/usr/lib64/libtdb2.so (deleted)".into())
6087 );
6088 assert!(maps[1].map.perms == MMPermissions::WRITE | MMPermissions::SHARED);
6089
6090 let mut unified_infos = unified_info.by_addr();
6091
6092 assert!(matches!(unified_infos.next(), Some(UnifiedMemoryInfo::Map(m)) if m == maps[0]));
6093 assert!(matches!(unified_infos.next(), Some(UnifiedMemoryInfo::Map(m)) if m == maps[1]));
6094 }
6095
6096 #[test]
6097 fn test_linux_map_parse() {
6098 use procfs_core::process::{MMPermissions, MMapPath::*};
6099 let parse = |input| MinidumpLinuxMapInfo::from_line(input).unwrap();
6100 let maybe_parse = MinidumpLinuxMapInfo::from_line;
6101
6102 // TODO: is it okay to give up wonky whitespace support?
6103
6104 {
6105 // Normal file
6106 let map = parse(b"10a00-10b00 r-xp 10bac9000 fd:05 1196511 /usr/lib64/libtdb1.so");
6107
6108 assert_eq!(map.map.address.0, 0x10a00);
6109 assert_eq!(map.map.address.1, 0x10b00);
6110 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6111 assert_eq!(map.map.pathname, Path("/usr/lib64/libtdb1.so".into()));
6112
6113 assert!(
6114 map.map.perms
6115 == MMPermissions::READ | MMPermissions::EXECUTE | MMPermissions::PRIVATE
6116 );
6117 assert!(map.is_readable());
6118 assert!(map.is_executable());
6119 }
6120
6121 {
6122 // Deleted file (also some whitespace in the file name)
6123 let map = parse(b"ffffffffff600000-ffffffffff601000 -wxs 10bac9000 fd:05 1196511 /usr/lib64/ libtdb1.so (deleted)");
6124
6125 assert_eq!(map.map.address.0, 0xffffffffff600000);
6126 assert_eq!(map.map.address.1, 0xffffffffff601000);
6127 assert_eq!(
6128 map.memory_range(),
6129 Some(Range::new(0xffffffffff600000, 0xffffffffff601000))
6130 );
6131 assert_eq!(
6132 map.map.pathname,
6133 Path("/usr/lib64/ libtdb1.so (deleted)".into())
6134 );
6135 assert!(
6136 map.map.perms
6137 == MMPermissions::WRITE | MMPermissions::EXECUTE | MMPermissions::SHARED
6138 );
6139 assert!(map.is_writable());
6140 assert!(map.is_executable());
6141 }
6142
6143 {
6144 // Stack
6145 let map = parse(b"10a00-10b00 ------- 10bac9000 fd:05 1196511 [stack]");
6146
6147 assert_eq!(map.map.address.0, 0x10a00);
6148 assert_eq!(map.map.address.1, 0x10b00);
6149 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6150 assert_eq!(map.map.pathname, Stack);
6151 assert!(map.map.perms == MMPermissions::NONE);
6152 }
6153
6154 {
6155 // Stack with tid
6156 let map = parse(b"10a00-10b00 ------- 10bac9000 fd:05 1196511 [stack:1234567]");
6157
6158 assert_eq!(map.map.address.0, 0x10a00);
6159 assert_eq!(map.map.address.1, 0x10b00);
6160 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6161 assert_eq!(map.map.pathname, TStack(1234567));
6162 assert!(map.map.perms == MMPermissions::NONE);
6163 }
6164
6165 {
6166 // Heap
6167 let map = parse(b"10a00-10b00 -- 10bac9000 fd:05 1196511 [heap]");
6168
6169 assert_eq!(map.map.address.0, 0x10a00);
6170 assert_eq!(map.map.address.1, 0x10b00);
6171 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6172 assert_eq!(map.map.pathname, Heap);
6173 assert!(map.map.perms == MMPermissions::NONE);
6174 }
6175
6176 {
6177 // Vdso
6178 let map = parse(b"10a00-10b00 r-wx- 10bac9000 fd:05 1196511 [vdso]");
6179
6180 assert_eq!(map.map.address.0, 0x10a00);
6181 assert_eq!(map.map.address.1, 0x10b00);
6182 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6183 assert_eq!(map.map.pathname, Vdso);
6184 assert!(
6185 map.map.perms
6186 == MMPermissions::READ | MMPermissions::WRITE | MMPermissions::EXECUTE
6187 );
6188 }
6189
6190 {
6191 // Unknown Special
6192 let map = parse(b"10a00-10b00 r-wx- 10bac9000 fd:05 1196511 [asdfasd]");
6193
6194 assert_eq!(map.map.address.0, 0x10a00);
6195 assert_eq!(map.map.address.1, 0x10b00);
6196 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6197 assert_eq!(map.map.pathname, Other("asdfasd".into()));
6198 assert!(
6199 map.map.perms
6200 == MMPermissions::READ | MMPermissions::WRITE | MMPermissions::EXECUTE
6201 );
6202 }
6203
6204 {
6205 // Anonymous
6206 let map = parse(b"10a00-10b00 -r- 10bac9000 fd:05 1196511 ");
6207
6208 assert_eq!(map.map.address.0, 0x10a00);
6209 assert_eq!(map.map.address.1, 0x10b00);
6210 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6211 assert_eq!(map.map.pathname, Anonymous);
6212 assert!(map.map.perms == MMPermissions::READ);
6213 }
6214
6215 /*
6216 {
6217 // Truncated defaults to anonymous
6218 let map = parse(b"10a00-10b00");
6219
6220 assert_eq!(map.map.address.0, 0x10a00);
6221 assert_eq!(map.map.address.1, 0x10b00);
6222 assert_eq!(map.memory_range(), Some(Range::new(0x10a00, 0x10b00)));
6223 assert_eq!(map.map.pathname, Anonymous);
6224 assert!(map.map.perms == MMPermissions::NONE);
6225 }
6226 */
6227
6228 {
6229 // Reversed ranges result in None for memory_range()
6230 let map = parse(b"fffff-10000 -r- 10bac9000 fd:05 1196511 ");
6231
6232 assert_eq!(map.map.address.0, 0xfffff);
6233 assert_eq!(map.map.address.1, 0x10000);
6234 assert_eq!(map.memory_range(), None);
6235 }
6236
6237 {
6238 // Equal ranges are valid
6239 let map = parse(b"fffff-fffff --- 10bac9000 fd:05 1196511 ");
6240
6241 assert_eq!(map.map.address.0, 0xfffff);
6242 assert_eq!(map.map.address.1, 0xfffff);
6243 assert_eq!(map.memory_range(), Some(Range::new(0xfffff, 0xfffff)));
6244 }
6245
6246 {
6247 // blank line
6248 assert!(maybe_parse(b"").is_none());
6249 assert!(maybe_parse(b" ").is_none());
6250 }
6251
6252 {
6253 // bad addresses
6254 let map = maybe_parse(b"-10b00 r-xp 10bac9000 fd:05 1196511 /usr/lib64/libtdb1.so");
6255 assert!(map.is_none());
6256
6257 let map = maybe_parse(b"10b00- r-xp 10bac9000 fd:05 1196511 /usr/lib64/libtdb1.so");
6258 assert!(map.is_none());
6259
6260 let map = maybe_parse(b"10b00 r-xp 10bac9000 fd:05 1196511 /usr/lib64/libtdb1.so");
6261 assert!(map.is_none());
6262 }
6263
6264 {
6265 // bad [stack:<tid>]
6266 let map = maybe_parse(b"10a00-10b00 r-xp 10bac9000 fd:05 1196511 [stack:]");
6267 assert!(map.is_none());
6268
6269 let map = maybe_parse(b"10a00-10b00 r-xp 10bac9000 fd:05 1196511 [stack:a10]");
6270 assert!(map.is_none());
6271 }
6272 }
6273
6274 #[test]
6275 fn test_module_list_overlap() {
6276 let name1 = DumpString::new("module 1", Endian::Little);
6277 let name2 = DumpString::new("module 2", Endian::Little);
6278 let name3 = DumpString::new("module 3", Endian::Little);
6279 let name4 = DumpString::new("module 4", Endian::Little);
6280 let name5 = DumpString::new("module 5", Endian::Little);
6281 let cv_record = Section::with_endian(Endian::Little)
6282 .D32(md::CvSignature::Pdb70 as u32) // signature
6283 // signature, a GUID
6284 .D32(0xabcd1234)
6285 .D16(0xf00d)
6286 .D16(0xbeef)
6287 .append_bytes(b"\x01\x02\x03\x04\x05\x06\x07\x08")
6288 .D32(1) // age
6289 .append_bytes(b"c:\\foo\\file.pdb\0"); // pdb_file_name
6290 let module1 = SynthModule::new(
6291 Endian::Little,
6292 0x100000000,
6293 0x4000,
6294 &name1,
6295 0xb1054d2a,
6296 0x34571371,
6297 Some(&STOCK_VERSION_INFO),
6298 )
6299 .cv_record(&cv_record);
6300 // module2 overlaps module1 exactly
6301 let module2 = SynthModule::new(
6302 Endian::Little,
6303 0x100000000,
6304 0x4000,
6305 &name2,
6306 0xb1054d2a,
6307 0x34571371,
6308 Some(&STOCK_VERSION_INFO),
6309 )
6310 .cv_record(&cv_record);
6311 // module3 overlaps module1 partially
6312 let module3 = SynthModule::new(
6313 Endian::Little,
6314 0x100000001,
6315 0x4000,
6316 &name3,
6317 0xb1054d2a,
6318 0x34571371,
6319 Some(&STOCK_VERSION_INFO),
6320 )
6321 .cv_record(&cv_record);
6322 // module4 is fully contained within module1
6323 let module4 = SynthModule::new(
6324 Endian::Little,
6325 0x100000001,
6326 0x3000,
6327 &name4,
6328 0xb1054d2a,
6329 0x34571371,
6330 Some(&STOCK_VERSION_INFO),
6331 )
6332 .cv_record(&cv_record);
6333 // module5 is cool, though.
6334 let module5 = SynthModule::new(
6335 Endian::Little,
6336 0x100004000,
6337 0x4000,
6338 &name5,
6339 0xb1054d2a,
6340 0x34571371,
6341 Some(&STOCK_VERSION_INFO),
6342 )
6343 .cv_record(&cv_record);
6344 let dump = SynthMinidump::with_endian(Endian::Little)
6345 .add_module(module1)
6346 .add_module(module2)
6347 .add_module(module3)
6348 .add_module(module4)
6349 .add_module(module5)
6350 .add(name1)
6351 .add(name2)
6352 .add(name3)
6353 .add(name4)
6354 .add(name5)
6355 .add(cv_record);
6356 let dump = read_synth_dump(dump).unwrap();
6357 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
6358 let modules = module_list.iter().collect::<Vec<_>>();
6359 assert_eq!(modules.len(), 5);
6360 assert_eq!(modules[0].base_address(), 0x100000000);
6361 assert_eq!(modules[0].size(), 0x4000);
6362 assert_eq!(modules[0].code_file(), "module 1");
6363 assert_eq!(modules[1].base_address(), 0x100000000);
6364 assert_eq!(modules[1].size(), 0x4000);
6365 assert_eq!(modules[1].code_file(), "module 2");
6366 assert_eq!(modules[2].base_address(), 0x100000001);
6367 assert_eq!(modules[2].size(), 0x4000);
6368 assert_eq!(modules[2].code_file(), "module 3");
6369 assert_eq!(modules[3].base_address(), 0x100000001);
6370 assert_eq!(modules[3].size(), 0x3000);
6371 assert_eq!(modules[3].code_file(), "module 4");
6372 assert_eq!(modules[4].base_address(), 0x100004000);
6373 assert_eq!(modules[4].size(), 0x4000);
6374 assert_eq!(modules[4].code_file(), "module 5");
6375
6376 // module_at_address should discard overlapping modules.
6377 assert_eq!(module_list.by_addr().count(), 2);
6378 assert_eq!(
6379 module_list
6380 .module_at_address(0x100001000)
6381 .unwrap()
6382 .code_file(),
6383 "module 1"
6384 );
6385 assert_eq!(
6386 module_list
6387 .module_at_address(0x100005000)
6388 .unwrap()
6389 .code_file(),
6390 "module 5"
6391 );
6392 }
6393
6394 #[test]
6395 fn test_memory_list() {
6396 const CONTENTS: &[u8] = b"memory_contents";
6397 let memory = Memory::with_section(
6398 Section::with_endian(Endian::Little).append_bytes(CONTENTS),
6399 0x309d68010bd21b2c,
6400 );
6401 let dump = SynthMinidump::with_endian(Endian::Little).add_memory(memory);
6402 let dump = read_synth_dump(dump).unwrap();
6403 let memory_list = dump.get_stream::<MinidumpMemoryList<'_>>().unwrap();
6404 let regions = memory_list.iter().collect::<Vec<_>>();
6405 assert_eq!(regions.len(), 1);
6406 assert_eq!(regions[0].base_address, 0x309d68010bd21b2c);
6407 assert_eq!(regions[0].size, CONTENTS.len() as u64);
6408 assert_eq!(&regions[0].bytes, &CONTENTS);
6409 }
6410
6411 #[test]
6412 fn test_memory64_list() {
6413 const CONTENTS0: &[u8] = b"memory_contents";
6414 const CONTENTS1: &[u8] = b"another_block";
6415 let memory0 = Memory::with_section(
6416 Section::with_endian(Endian::Little).append_bytes(CONTENTS0),
6417 0x309d68010bd21b2c,
6418 );
6419 let memory1 = Memory::with_section(
6420 Section::with_endian(Endian::Little).append_bytes(CONTENTS1),
6421 0x1234,
6422 );
6423 let dump = SynthMinidump::with_endian(Endian::Little)
6424 .add_memory64(memory0)
6425 .add_memory64(memory1);
6426 let dump = read_synth_dump(dump).unwrap();
6427 let memory_list = dump.get_stream::<MinidumpMemory64List<'_>>().unwrap();
6428 let regions = memory_list.iter().collect::<Vec<_>>();
6429 assert_eq!(regions.len(), 2);
6430 assert_eq!(regions[0].base_address, 0x309d68010bd21b2c);
6431 assert_eq!(regions[0].size, CONTENTS0.len() as u64);
6432 assert_eq!(&regions[0].bytes, &CONTENTS0);
6433
6434 assert_eq!(regions[1].base_address, 0x1234);
6435 assert_eq!(regions[1].size, CONTENTS1.len() as u64);
6436 assert_eq!(&regions[1].bytes, &CONTENTS1);
6437 }
6438
6439 #[test]
6440 fn test_memory_list_lifetimes() {
6441 // A memory list should not own any of the minidump data.
6442 const CONTENTS: &[u8] = b"memory_contents";
6443 let memory = Memory::with_section(
6444 Section::with_endian(Endian::Little).append_bytes(CONTENTS),
6445 0x309d68010bd21b2c,
6446 );
6447 let dump = SynthMinidump::with_endian(Endian::Little).add_memory(memory);
6448 let dump = read_synth_dump(dump).unwrap();
6449 let mem_slices: Vec<&[u8]> = {
6450 let mem_list: MinidumpMemoryList<'_> = dump.get_stream().unwrap();
6451 mem_list.iter().map(|mem| mem.bytes).collect()
6452 };
6453 assert_eq!(mem_slices[0], CONTENTS);
6454 }
6455
6456 #[test]
6457 fn test_memory_overflow() {
6458 let memory1 = Memory::with_section(
6459 Section::with_endian(Endian::Little).append_repeated(0, 2),
6460 u64::MAX,
6461 );
6462 let dump = SynthMinidump::with_endian(Endian::Little).add_memory(memory1);
6463 let dump = read_synth_dump(dump).unwrap();
6464 let memory_list = dump.get_stream::<MinidumpMemoryList<'_>>().unwrap();
6465
6466 assert!(memory_list.memory_at_address(u64::MAX).is_none());
6467 assert_eq!(memory_list.regions.len(), 1);
6468 assert!(memory_list.regions[0].memory_range().is_none());
6469 }
6470
6471 #[test]
6472 fn test_memory_list_overlap() {
6473 let memory1 = Memory::with_section(
6474 Section::with_endian(Endian::Little).append_repeated(0, 0x1000),
6475 0x1000,
6476 );
6477 // memory2 overlaps memory1 exactly
6478 let memory2 = Memory::with_section(
6479 Section::with_endian(Endian::Little).append_repeated(1, 0x1000),
6480 0x1000,
6481 );
6482 // memory3 overlaps memory1 partially
6483 let memory3 = Memory::with_section(
6484 Section::with_endian(Endian::Little).append_repeated(2, 0x1000),
6485 0x1001,
6486 );
6487 // memory4 is fully contained within memory1
6488 let memory4 = Memory::with_section(
6489 Section::with_endian(Endian::Little).append_repeated(3, 0x100),
6490 0x1001,
6491 );
6492 // memory5 is cool, though.
6493 let memory5 = Memory::with_section(
6494 Section::with_endian(Endian::Little).append_repeated(4, 0x1000),
6495 0x2000,
6496 );
6497 let dump = SynthMinidump::with_endian(Endian::Little)
6498 .add_memory(memory1)
6499 .add_memory(memory2)
6500 .add_memory(memory3)
6501 .add_memory(memory4)
6502 .add_memory(memory5);
6503 let dump = read_synth_dump(dump).unwrap();
6504 let memory_list = dump.get_stream::<MinidumpMemoryList<'_>>().unwrap();
6505 let regions = memory_list.iter().collect::<Vec<_>>();
6506 assert_eq!(regions.len(), 5);
6507 assert_eq!(regions[0].base_address, 0x1000);
6508 assert_eq!(regions[0].size, 0x1000);
6509 assert_eq!(regions[1].base_address, 0x1000);
6510 assert_eq!(regions[1].size, 0x1000);
6511 assert_eq!(regions[2].base_address, 0x1001);
6512 assert_eq!(regions[2].size, 0x1000);
6513 assert_eq!(regions[3].base_address, 0x1001);
6514 assert_eq!(regions[3].size, 0x100);
6515 assert_eq!(regions[4].base_address, 0x2000);
6516 assert_eq!(regions[4].size, 0x1000);
6517
6518 // memory_at_address should discard overlapping regions.
6519 assert_eq!(memory_list.by_addr().count(), 2);
6520 let m1 = memory_list.memory_at_address(0x1a00).unwrap();
6521 assert_eq!(m1.base_address, 0x1000);
6522 assert_eq!(m1.size, 0x1000);
6523 assert_eq!(m1.bytes, &[0u8; 0x1000][..]);
6524 let m2 = memory_list.memory_at_address(0x2a00).unwrap();
6525 assert_eq!(m2.base_address, 0x2000);
6526 assert_eq!(m2.size, 0x1000);
6527 assert_eq!(m2.bytes, &[4u8; 0x1000][..]);
6528 }
6529
6530 #[test]
6531 fn test_misc_info() {
6532 const PID: u32 = 0x1234abcd;
6533 const PROCESS_TIMES: MiscFieldsProcessTimes = MiscFieldsProcessTimes {
6534 process_create_time: 0xf0f0b0b0,
6535 process_user_time: 0xf030a020,
6536 process_kernel_time: 0xa010b420,
6537 };
6538
6539 let mut misc = MiscStream::new(Endian::Little);
6540 misc.process_id = Some(PID);
6541 misc.process_times = Some(PROCESS_TIMES);
6542 let dump = SynthMinidump::with_endian(Endian::Little).add_stream(misc);
6543 let dump = read_synth_dump(dump).unwrap();
6544 let misc = dump.get_stream::<MinidumpMiscInfo>().unwrap();
6545 assert_eq!(misc.raw.process_id(), Some(&PID));
6546 assert_eq!(
6547 misc.process_create_time().unwrap(),
6548 systemtime_from_timestamp(PROCESS_TIMES.process_create_time as u64).unwrap()
6549 );
6550 assert_eq!(
6551 *misc.raw.process_user_time().unwrap(),
6552 PROCESS_TIMES.process_user_time
6553 );
6554 assert_eq!(
6555 *misc.raw.process_kernel_time().unwrap(),
6556 PROCESS_TIMES.process_kernel_time
6557 );
6558 }
6559
6560 #[test]
6561 fn test_misc_info_large() {
6562 const PID: u32 = 0x1234abcd;
6563 const PROCESS_TIMES: MiscFieldsProcessTimes = MiscFieldsProcessTimes {
6564 process_create_time: 0xf0f0b0b0,
6565 process_user_time: 0xf030a020,
6566 process_kernel_time: 0xa010b420,
6567 };
6568 let mut misc = MiscStream::new(Endian::Little);
6569 misc.process_id = Some(PID);
6570 misc.process_times = Some(PROCESS_TIMES);
6571 // Make it larger.
6572 misc.pad_to_size = Some(mem::size_of::<md::MINIDUMP_MISC_INFO>() + 32);
6573 let dump = SynthMinidump::with_endian(Endian::Little).add_stream(misc);
6574 let dump = read_synth_dump(dump).unwrap();
6575 let misc = dump.get_stream::<MinidumpMiscInfo>().unwrap();
6576 assert_eq!(misc.raw.process_id(), Some(&PID));
6577 assert_eq!(
6578 misc.process_create_time().unwrap(),
6579 systemtime_from_timestamp(PROCESS_TIMES.process_create_time as u64).unwrap(),
6580 );
6581 assert_eq!(
6582 *misc.raw.process_user_time().unwrap(),
6583 PROCESS_TIMES.process_user_time
6584 );
6585 assert_eq!(
6586 *misc.raw.process_kernel_time().unwrap(),
6587 PROCESS_TIMES.process_kernel_time
6588 );
6589 }
6590
6591 fn ascii_string_to_utf16(input: &str) -> Vec<u16> {
6592 input.chars().map(|c| c as u16).collect()
6593 }
6594
6595 #[test]
6596 fn test_misc_info_5() {
6597 // MISC_INFO fields
6598 const PID: u32 = 0x1234abcd;
6599 const PROCESS_TIMES: MiscFieldsProcessTimes = MiscFieldsProcessTimes {
6600 process_create_time: 0xf0f0b0b0,
6601 process_user_time: 0xf030a020,
6602 process_kernel_time: 0xa010b420,
6603 };
6604
6605 // MISC_INFO_2 fields
6606 const POWER_INFO: MiscFieldsPowerInfo = MiscFieldsPowerInfo {
6607 processor_max_mhz: 0x45873234,
6608 processor_current_mhz: 0x2134018a,
6609 processor_mhz_limit: 0x3423aead,
6610 processor_max_idle_state: 0x123aef12,
6611 processor_current_idle_state: 0x1205af3a,
6612 };
6613
6614 // MISC_INFO_3 fields
6615 const PROCESS_INTEGRITY_LEVEL: u32 = 0x35603403;
6616 const PROCESS_EXECUTE_FLAGS: u32 = 0xa4e09da1;
6617 const PROTECTED_PROCESS: u32 = 0x12345678;
6618
6619 let mut standard_name = [0; 32];
6620 let mut daylight_name = [0; 32];
6621 let bare_standard_name = ascii_string_to_utf16("Pacific Standard Time");
6622 let bare_daylight_name = ascii_string_to_utf16("Pacific Daylight Time");
6623 standard_name[..bare_standard_name.len()].copy_from_slice(&bare_standard_name);
6624 daylight_name[..bare_daylight_name.len()].copy_from_slice(&bare_daylight_name);
6625
6626 const TIME_ZONE_ID: u32 = 2;
6627 const BIAS: i32 = 2;
6628 const STANDARD_BIAS: i32 = 1;
6629 const DAYLIGHT_BIAS: i32 = -60;
6630 const STANDARD_DATE: md::SYSTEMTIME = md::SYSTEMTIME {
6631 year: 0,
6632 month: 11,
6633 day_of_week: 2,
6634 day: 1,
6635 hour: 2,
6636 minute: 33,
6637 second: 51,
6638 milliseconds: 123,
6639 };
6640 const DAYLIGHT_DATE: md::SYSTEMTIME = md::SYSTEMTIME {
6641 year: 0,
6642 month: 3,
6643 day_of_week: 4,
6644 day: 2,
6645 hour: 3,
6646 minute: 41,
6647 second: 19,
6648 milliseconds: 512,
6649 };
6650
6651 let time_zone = MiscFieldsTimeZone {
6652 time_zone_id: TIME_ZONE_ID,
6653 time_zone: md::TIME_ZONE_INFORMATION {
6654 bias: BIAS,
6655 standard_bias: STANDARD_BIAS,
6656 daylight_bias: DAYLIGHT_BIAS,
6657 daylight_name,
6658 standard_name,
6659 standard_date: STANDARD_DATE.clone(),
6660 daylight_date: DAYLIGHT_DATE.clone(),
6661 },
6662 };
6663
6664 // MISC_INFO_4 fields
6665 let mut build_string = [0; 260];
6666 let mut dbg_bld_str = [0; 40];
6667 let bare_build_string = ascii_string_to_utf16("hello");
6668 let bare_dbg_bld_str = ascii_string_to_utf16("world");
6669 build_string[..bare_build_string.len()].copy_from_slice(&bare_build_string);
6670 dbg_bld_str[..bare_dbg_bld_str.len()].copy_from_slice(&bare_dbg_bld_str);
6671
6672 let build_strings = MiscFieldsBuildString {
6673 build_string,
6674 dbg_bld_str,
6675 };
6676
6677 // MISC_INFO_5 fields
6678 const SIZE_OF_INFO: u32 = mem::size_of::<md::XSTATE_CONFIG_FEATURE_MSC_INFO>() as u32;
6679 const CONTEXT_SIZE: u32 = 0x1234523f;
6680 const PROCESS_COOKIE: u32 = 0x1234dfe0;
6681 const KNOWN_FEATURE_IDX: usize = md::XstateFeatureIndex::LEGACY_SSE as usize;
6682 const UNKNOWN_FEATURE_IDX: usize = 39;
6683 let mut enabled_features = 0;
6684 let mut features = [md::XSTATE_FEATURE::default(); 64];
6685 // One known feature and one unknown feature.
6686 enabled_features |= 1 << KNOWN_FEATURE_IDX;
6687 features[KNOWN_FEATURE_IDX] = md::XSTATE_FEATURE {
6688 offset: 0,
6689 size: 140,
6690 };
6691 enabled_features |= 1 << UNKNOWN_FEATURE_IDX;
6692 features[UNKNOWN_FEATURE_IDX] = md::XSTATE_FEATURE {
6693 offset: 320,
6694 size: 1100,
6695 };
6696 let misc_5 = MiscInfo5Fields {
6697 xstate_data: md::XSTATE_CONFIG_FEATURE_MSC_INFO {
6698 size_of_info: SIZE_OF_INFO,
6699 context_size: CONTEXT_SIZE,
6700 enabled_features,
6701 features,
6702 },
6703 process_cookie: Some(PROCESS_COOKIE),
6704 };
6705
6706 let mut misc = MiscStream::new(Endian::Little);
6707 misc.process_id = Some(PID);
6708 misc.process_times = Some(PROCESS_TIMES);
6709 misc.power_info = Some(POWER_INFO);
6710 misc.process_integrity_level = Some(PROCESS_INTEGRITY_LEVEL);
6711 misc.protected_process = Some(PROTECTED_PROCESS);
6712 misc.process_execute_flags = Some(PROCESS_EXECUTE_FLAGS);
6713 misc.time_zone = Some(time_zone);
6714 misc.build_strings = Some(build_strings);
6715 misc.misc_5 = Some(misc_5);
6716
6717 let dump = SynthMinidump::with_endian(Endian::Little).add_stream(misc);
6718 let dump = read_synth_dump(dump).unwrap();
6719 let misc = dump.get_stream::<MinidumpMiscInfo>().unwrap();
6720
6721 // MISC_INFO fields
6722 assert_eq!(misc.raw.process_id(), Some(&PID));
6723 assert_eq!(
6724 misc.process_create_time().unwrap(),
6725 systemtime_from_timestamp(PROCESS_TIMES.process_create_time as u64).unwrap()
6726 );
6727 assert_eq!(
6728 *misc.raw.process_user_time().unwrap(),
6729 PROCESS_TIMES.process_user_time
6730 );
6731 assert_eq!(
6732 *misc.raw.process_kernel_time().unwrap(),
6733 PROCESS_TIMES.process_kernel_time
6734 );
6735
6736 // MISC_INFO_2 fields
6737 assert_eq!(
6738 *misc.raw.processor_max_mhz().unwrap(),
6739 POWER_INFO.processor_max_mhz,
6740 );
6741 assert_eq!(
6742 *misc.raw.processor_current_mhz().unwrap(),
6743 POWER_INFO.processor_current_mhz,
6744 );
6745 assert_eq!(
6746 *misc.raw.processor_mhz_limit().unwrap(),
6747 POWER_INFO.processor_mhz_limit,
6748 );
6749 assert_eq!(
6750 *misc.raw.processor_max_idle_state().unwrap(),
6751 POWER_INFO.processor_max_idle_state,
6752 );
6753 assert_eq!(
6754 *misc.raw.processor_current_idle_state().unwrap(),
6755 POWER_INFO.processor_current_idle_state,
6756 );
6757
6758 // MISC_INFO_3 fields
6759 assert_eq!(*misc.raw.time_zone_id().unwrap(), TIME_ZONE_ID);
6760 let time_zone = misc.raw.time_zone().unwrap();
6761 assert_eq!(time_zone.bias, BIAS);
6762 assert_eq!(time_zone.standard_bias, STANDARD_BIAS);
6763 assert_eq!(time_zone.daylight_bias, DAYLIGHT_BIAS);
6764 assert_eq!(time_zone.standard_date, STANDARD_DATE);
6765 assert_eq!(time_zone.daylight_date, DAYLIGHT_DATE);
6766 assert_eq!(time_zone.standard_name, standard_name);
6767 assert_eq!(time_zone.daylight_name, daylight_name);
6768
6769 // MISC_INFO_4 fields
6770 assert_eq!(*misc.raw.build_string().unwrap(), build_string,);
6771 assert_eq!(*misc.raw.dbg_bld_str().unwrap(), dbg_bld_str,);
6772
6773 // MISC_INFO_5 fields
6774 assert_eq!(*misc.raw.process_cookie().unwrap(), PROCESS_COOKIE,);
6775
6776 let xstate = misc.raw.xstate_data().unwrap();
6777 assert_eq!(xstate.size_of_info, SIZE_OF_INFO);
6778 assert_eq!(xstate.context_size, CONTEXT_SIZE);
6779 assert_eq!(xstate.enabled_features, enabled_features);
6780 assert_eq!(xstate.features, features);
6781
6782 let mut xstate_iter = xstate.iter();
6783 assert_eq!(
6784 xstate_iter.next().unwrap(),
6785 (KNOWN_FEATURE_IDX, features[KNOWN_FEATURE_IDX]),
6786 );
6787 assert_eq!(
6788 xstate_iter.next().unwrap(),
6789 (UNKNOWN_FEATURE_IDX, features[UNKNOWN_FEATURE_IDX]),
6790 );
6791 assert_eq!(xstate_iter.next(), None);
6792 assert_eq!(xstate_iter.next(), None);
6793 }
6794
6795 #[test]
6796 fn test_elf_build_id() {
6797 // Add a module with a long ELF build id
6798 let name1 = DumpString::new("module 1", Endian::Little);
6799 const MODULE1_BUILD_ID: &[u8] = &[
6800 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
6801 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
6802 ];
6803 let cv_record1 = Section::with_endian(Endian::Little)
6804 .D32(md::CvSignature::Elf as u32) // signature
6805 .append_bytes(MODULE1_BUILD_ID);
6806 let module1 = SynthModule::new(
6807 Endian::Little,
6808 0x100000000,
6809 0x4000,
6810 &name1,
6811 0xb1054d2a,
6812 0x34571371,
6813 Some(&STOCK_VERSION_INFO),
6814 )
6815 .cv_record(&cv_record1);
6816 // Add a module with a short ELF build id
6817 let name2 = DumpString::new("module 2", Endian::Little);
6818 const MODULE2_BUILD_ID: &[u8] = &[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
6819 let cv_record2 = Section::with_endian(Endian::Little)
6820 .D32(md::CvSignature::Elf as u32) // signature
6821 .append_bytes(MODULE2_BUILD_ID);
6822 let module2 = SynthModule::new(
6823 Endian::Little,
6824 0x200000000,
6825 0x4000,
6826 &name2,
6827 0xb1054d2a,
6828 0x34571371,
6829 Some(&STOCK_VERSION_INFO),
6830 )
6831 .cv_record(&cv_record2);
6832 let dump = SynthMinidump::with_endian(Endian::Little)
6833 .add_module(module1)
6834 .add_module(module2)
6835 .add(name1)
6836 .add(cv_record1)
6837 .add(name2)
6838 .add(cv_record2);
6839 let dump = read_synth_dump(dump).unwrap();
6840 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
6841 let modules = module_list.iter().collect::<Vec<_>>();
6842 assert_eq!(modules.len(), 2);
6843 assert_eq!(modules[0].base_address(), 0x100000000);
6844 assert_eq!(modules[0].code_file(), "module 1");
6845 // The full build ID.
6846 assert_eq!(
6847 modules[0].code_identifier().unwrap(),
6848 CodeId::new("000102030405060708090a0b0c0d0e0f1011121314151617".to_string())
6849 );
6850 assert_eq!(modules[0].debug_file().unwrap(), "module 1");
6851 // The first 16 bytes of the build ID interpreted as a GUID.
6852 assert_eq!(
6853 modules[0].debug_identifier().unwrap(),
6854 DebugId::from_breakpad("030201000504070608090A0B0C0D0E0F0").unwrap()
6855 );
6856
6857 assert_eq!(modules[1].base_address(), 0x200000000);
6858 assert_eq!(modules[1].code_file(), "module 2");
6859 // The full build ID.
6860 assert_eq!(
6861 modules[1].code_identifier().unwrap(),
6862 CodeId::new("0001020304050607".to_string())
6863 );
6864 assert_eq!(modules[1].debug_file().unwrap(), "module 2");
6865 // The first 16 bytes of the build ID interpreted as a GUID, padded with
6866 // zeroes in this case.
6867 assert_eq!(
6868 modules[1].debug_identifier().unwrap(),
6869 DebugId::from_breakpad("030201000504070600000000000000000").unwrap()
6870 );
6871 }
6872
6873 #[test]
6874 fn test_os() {
6875 let dump = SynthMinidump::with_endian(Endian::Little).add_system_info(
6876 SystemInfo::new(Endian::Little).set_platform_id(PlatformId::MacOs as u32),
6877 );
6878
6879 let dump = read_synth_dump(dump).unwrap();
6880 let system_info = dump.get_stream::<MinidumpSystemInfo>().unwrap();
6881 assert_eq!(system_info.os, Os::MacOs);
6882 }
6883
6884 #[test]
6885 fn test_macos_ids() {
6886 let name = DumpString::new("macos module", Endian::Little);
6887 let cv_record = Section::with_endian(Endian::Little)
6888 // signature
6889 .D32(md::CvSignature::Pdb70 as u32)
6890 // signature, a GUID
6891 .D32(0xaabbccdd)
6892 .D16(0xeeff)
6893 .D16(0x0011)
6894 .append_bytes(b"\x22\x33\x44\x55\x66\x77\x88\x99")
6895 // age, breakpad writes 0
6896 .D32(0)
6897 // pdb_file_name
6898 .append_bytes(b"helpivecrashed.dylib\0");
6899 let module = SynthModule::new(
6900 Endian::Little,
6901 0x100000000,
6902 0x4000,
6903 &name,
6904 0xb1054d2a,
6905 0x34571371,
6906 Some(&STOCK_VERSION_INFO),
6907 )
6908 .cv_record(&cv_record);
6909 let dump = SynthMinidump::with_endian(Endian::Little)
6910 .add_system_info(
6911 SystemInfo::new(Endian::Little).set_platform_id(PlatformId::MacOs as u32),
6912 )
6913 .add_module(module)
6914 .add(name)
6915 .add(cv_record);
6916 let dump = read_synth_dump(dump).unwrap();
6917 let system_info = dump.get_stream::<MinidumpSystemInfo>().unwrap();
6918 assert_eq!(system_info.os, Os::MacOs);
6919
6920 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
6921 let modules = module_list.iter().collect::<Vec<_>>();
6922 assert_eq!(modules.len(), 1);
6923 // should be the uuid stored in cv record
6924 assert_eq!(
6925 modules[0].code_identifier().unwrap(),
6926 CodeId::new("AABBCCDDEEFF00112233445566778899".to_owned())
6927 );
6928 // should match code identifier, but with the age appended to it
6929 assert_eq!(
6930 modules[0].debug_identifier().unwrap(),
6931 DebugId::from_breakpad("AABBCCDDEEFF001122334455667788990").unwrap()
6932 );
6933 assert_eq!(modules[0].code_file(), "macos module");
6934 assert_eq!(modules[0].debug_file().unwrap(), "helpivecrashed.dylib");
6935 }
6936
6937 #[test]
6938 fn test_windows_code_id_no_cv() {
6939 let name = DumpString::new("windows module", Endian::Little);
6940 let module = SynthModule::new(
6941 Endian::Little,
6942 0x100000000,
6943 0x4000, // size of image
6944 &name,
6945 0xb105_4d2a, // datetime
6946 0x34571371,
6947 Some(&STOCK_VERSION_INFO),
6948 );
6949 let dump = SynthMinidump::with_endian(Endian::Little)
6950 .add_system_info(
6951 SystemInfo::new(Endian::Little)
6952 .set_platform_id(PlatformId::VER_PLATFORM_WIN32_NT as u32),
6953 )
6954 .add_module(module)
6955 .add(name);
6956 let dump = read_synth_dump(dump).unwrap();
6957 let system_info = dump.get_stream::<MinidumpSystemInfo>().unwrap();
6958 assert_eq!(system_info.os, Os::Windows);
6959
6960 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
6961 let modules = module_list.iter().collect::<Vec<_>>();
6962 assert_eq!(modules.len(), 1);
6963 // should match datetime + size of image
6964 assert_eq!(
6965 modules[0].code_identifier().unwrap(),
6966 CodeId::new("B1054D2A4000".to_owned())
6967 );
6968 }
6969
6970 #[test]
6971 fn test_null_id() {
6972 // Add a module with an ELF build id of nothing but zeros
6973 let name1 = DumpString::new("module 1", Endian::Little);
6974 const MODULE1_BUILD_ID: &[u8] = &[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
6975 let cv_record1 = Section::with_endian(Endian::Little)
6976 .D32(md::CvSignature::Elf as u32) // signature
6977 .append_bytes(MODULE1_BUILD_ID);
6978 let module1 = SynthModule::new(
6979 Endian::Little,
6980 0x100000000,
6981 0x4000,
6982 &name1,
6983 0xb1054d2a,
6984 0x34571371,
6985 Some(&STOCK_VERSION_INFO),
6986 )
6987 .cv_record(&cv_record1);
6988
6989 // Add a module with a PDB70 build id of nothing but zeros
6990 let name2 = DumpString::new("module 2", Endian::Little);
6991 let cv_record2 = Section::with_endian(Endian::Little)
6992 // signature
6993 .D32(md::CvSignature::Pdb70 as u32)
6994 // signature, a GUID
6995 .D32(0x0)
6996 .D16(0x0)
6997 .D16(0x0)
6998 .append_bytes(b"\0\0\0\0\0\0\0\0")
6999 // age, breakpad writes 0
7000 .D32(0)
7001 // pdb_file_name
7002 .append_bytes(b"\0");
7003 let module2 = SynthModule::new(
7004 Endian::Little,
7005 0x100000000,
7006 0x4000,
7007 &name2,
7008 0xb1054d2a,
7009 0x34571371,
7010 Some(&STOCK_VERSION_INFO),
7011 )
7012 .cv_record(&cv_record2);
7013 let dump = SynthMinidump::with_endian(Endian::Little)
7014 .add_module(module1)
7015 .add_module(module2)
7016 .add(name1)
7017 .add(cv_record1)
7018 .add(name2)
7019 .add(cv_record2);
7020
7021 let dump = read_synth_dump(dump).unwrap();
7022 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
7023 let modules = module_list.iter().collect::<Vec<_>>();
7024
7025 assert!(modules[0].debug_identifier().is_none());
7026 assert!(modules[1].debug_identifier().is_none());
7027 }
7028
7029 #[test]
7030 fn test_thread_list_x86() {
7031 let context = minidump_synth::x86_context(Endian::Little, 0xabcd1234, 0x1010);
7032 let stack = Memory::with_section(
7033 Section::with_endian(Endian::Little).append_repeated(0, 0x1000),
7034 0x1000,
7035 );
7036 let arch = md::ProcessorArchitecture::PROCESSOR_ARCHITECTURE_INTEL as u16;
7037 let system_info = SystemInfo::new(Endian::Little).set_processor_architecture(arch);
7038 let thread = Thread::new(Endian::Little, 0x1234, &stack, &context);
7039 let dump = SynthMinidump::with_endian(Endian::Little)
7040 .add_thread(thread)
7041 .add(context)
7042 .add_memory(stack)
7043 .add_system_info(system_info);
7044 let dump = read_synth_dump(dump).unwrap();
7045 let mut thread_list = dump.get_stream::<MinidumpThreadList<'_>>().unwrap();
7046 let system_info = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7047 let misc_info = dump.get_stream::<MinidumpMiscInfo>().ok();
7048 assert_eq!(thread_list.threads.len(), 1);
7049 let mut thread = thread_list.threads.pop().unwrap();
7050 assert_eq!(thread.raw.thread_id, 0x1234);
7051 let context = thread
7052 .context(&system_info, misc_info.as_ref())
7053 .expect("Should have a thread context");
7054 match &context.raw {
7055 MinidumpRawContext::X86(raw) => {
7056 assert_eq!(raw.eip, 0xabcd1234);
7057 assert_eq!(raw.esp, 0x1010);
7058 }
7059 _ => panic!("Got unexpected raw context type!"),
7060 }
7061 let stack = thread.stack.take().expect("Should have stack memory");
7062 assert_eq!(stack.base_address, 0x1000);
7063 assert_eq!(stack.size, 0x1000);
7064 }
7065
7066 #[test]
7067 fn test_thread_list_amd64() {
7068 let context =
7069 minidump_synth::amd64_context(Endian::Little, 0x1234abcd1234abcd, 0x1000000010000000);
7070 let stack = Memory::with_section(
7071 Section::with_endian(Endian::Little).append_repeated(0, 0x1000),
7072 0x1000000010000000,
7073 );
7074 let arch = md::ProcessorArchitecture::PROCESSOR_ARCHITECTURE_AMD64 as u16;
7075 let system_info = SystemInfo::new(Endian::Little).set_processor_architecture(arch);
7076 let thread = Thread::new(Endian::Little, 0x1234, &stack, &context);
7077 let dump = SynthMinidump::with_endian(Endian::Little)
7078 .add_thread(thread)
7079 .add(context)
7080 .add_memory(stack)
7081 .add_system_info(system_info);
7082 let dump = read_synth_dump(dump).unwrap();
7083 let mut thread_list = dump.get_stream::<MinidumpThreadList<'_>>().unwrap();
7084 let system_info = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7085 let misc_info = dump.get_stream::<MinidumpMiscInfo>().ok();
7086 assert_eq!(thread_list.threads.len(), 1);
7087 let mut thread = thread_list.threads.pop().unwrap();
7088 assert_eq!(thread.raw.thread_id, 0x1234);
7089 let context = thread
7090 .context(&system_info, misc_info.as_ref())
7091 .expect("Should have a thread context");
7092 match &context.raw {
7093 MinidumpRawContext::Amd64(raw) => {
7094 assert_eq!(raw.rip, 0x1234abcd1234abcd);
7095 assert_eq!(raw.rsp, 0x1000000010000000);
7096 }
7097 _ => panic!("Got unexpected raw context type!"),
7098 }
7099 let stack = thread.stack.take().expect("Should have stack memory");
7100 assert_eq!(stack.base_address, 0x1000000010000000);
7101 assert_eq!(stack.size, 0x1000);
7102 }
7103
7104 #[test]
7105 fn test_crashpad_info_missing() {
7106 let dump = SynthMinidump::with_endian(Endian::Little);
7107 let dump = read_synth_dump(dump).unwrap();
7108
7109 assert!(matches!(
7110 dump.get_stream::<MinidumpCrashpadInfo>(),
7111 Err(Error::StreamNotFound)
7112 ));
7113 }
7114
7115 #[test]
7116 fn test_crashpad_info_ids() {
7117 let report_id = GUID {
7118 data1: 1,
7119 data2: 2,
7120 data3: 3,
7121 data4: [4, 5, 6, 7, 8, 9, 10, 11],
7122 };
7123
7124 let client_id = GUID {
7125 data1: 11,
7126 data2: 10,
7127 data3: 9,
7128 data4: [8, 7, 6, 5, 4, 3, 2, 1],
7129 };
7130
7131 let crashpad_info = CrashpadInfo::new(Endian::Little)
7132 .report_id(report_id)
7133 .client_id(client_id);
7134
7135 let dump = SynthMinidump::with_endian(Endian::Little).add_crashpad_info(crashpad_info);
7136 let dump = read_synth_dump(dump).unwrap();
7137
7138 let crashpad_info = dump.get_stream::<MinidumpCrashpadInfo>().unwrap();
7139
7140 assert_eq!(crashpad_info.raw.report_id, report_id);
7141 assert_eq!(crashpad_info.raw.client_id, client_id);
7142 }
7143
7144 #[test]
7145 fn test_crashpad_info_annotations() {
7146 let module = ModuleCrashpadInfo::new(42, Endian::Little)
7147 .add_list_annotation("annotation")
7148 .add_simple_annotation("simple", "module")
7149 .add_annotation_object("string", AnnotationValue::String("value".to_owned()))
7150 .add_annotation_object("invalid", AnnotationValue::Invalid)
7151 .add_annotation_object("custom", AnnotationValue::Custom(0x8001, vec![42]));
7152
7153 let crashpad_info = CrashpadInfo::new(Endian::Little)
7154 .add_module(module)
7155 .add_simple_annotation("simple", "info");
7156
7157 let dump = SynthMinidump::with_endian(Endian::Little).add_crashpad_info(crashpad_info);
7158 let dump = read_synth_dump(dump).unwrap();
7159
7160 let crashpad_info = dump.get_stream::<MinidumpCrashpadInfo>().unwrap();
7161 let module = &crashpad_info.module_list[0];
7162
7163 assert_eq!(crashpad_info.simple_annotations["simple"], "info");
7164 assert_eq!(module.module_index, 42);
7165 assert_eq!(module.list_annotations, vec!["annotation".to_owned()]);
7166 assert_eq!(module.simple_annotations["simple"], "module");
7167 assert_eq!(
7168 module.annotation_objects["string"],
7169 MinidumpAnnotation::String("value".to_owned())
7170 );
7171 assert_eq!(
7172 module.annotation_objects["invalid"],
7173 MinidumpAnnotation::Invalid
7174 );
7175 }
7176
7177 #[test]
7178 fn test_exception_x86() {
7179 // Defaults to x86
7180 let system_info = SystemInfo::new(Endian::Little);
7181
7182 let mut exception = Exception::new(Endian::Little);
7183
7184 // Check that we clear the erroneous high bits for 32-bit
7185 exception.exception_record.exception_address = 0xf0e1_d2c3_b4a5_9687;
7186 // FIXME: test other fields too
7187
7188 let dump = SynthMinidump::with_endian(Endian::Little)
7189 .add_system_info(system_info)
7190 .add_exception(exception);
7191
7192 let dump = read_synth_dump(dump).unwrap();
7193
7194 let system_stream = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7195 let exception_stream = dump.get_stream::<MinidumpException>().unwrap();
7196 assert_eq!(
7197 exception_stream.get_crash_address(system_stream.os, system_stream.cpu),
7198 0xb4a5_9687
7199 );
7200 }
7201
7202 #[test]
7203 fn test_exception_x64() {
7204 // Defaults to x86
7205 let system_info = SystemInfo::new(Endian::Little)
7206 .set_processor_architecture(ProcessorArchitecture::PROCESSOR_ARCHITECTURE_AMD64 as u16);
7207
7208 let mut exception = Exception::new(Endian::Little);
7209
7210 // Check that we don't truncate this on 64-bit
7211 exception.exception_record.exception_address = 0xf0e1_d2c3_b4a5_9687;
7212 // FIXME: test other fields too
7213
7214 let dump = SynthMinidump::with_endian(Endian::Little)
7215 .add_system_info(system_info)
7216 .add_exception(exception);
7217
7218 let dump = read_synth_dump(dump).unwrap();
7219
7220 let system_stream = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7221 let exception_stream = dump.get_stream::<MinidumpException>().unwrap();
7222 assert_eq!(
7223 exception_stream.get_crash_address(system_stream.os, system_stream.cpu),
7224 0xf0e1_d2c3_b4a5_9687
7225 );
7226 }
7227
7228 #[test]
7229 fn test_fuzzed_oom() {
7230 // https://github.com/rust-minidump/rust-minidump/issues/381
7231 let data = b"MDMP\x93\xa7\x00\x00\x00\xffffdYfffff@\n\nfp\n\xbb\xff\xff\xff\n\xff\n";
7232 assert!(Minidump::read(data.as_ref()).is_err());
7233
7234 // https://github.com/getsentry/symbolic/issues/478
7235 let data = b"MDMP\x93\xa7\x00\x00\r\x00\x00\x00 \xff\xff\xff\xff\xff\xff\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
7236 assert!(Minidump::read(data.as_ref()).is_err());
7237 }
7238
7239 #[test]
7240 fn test_empty_module() {
7241 let name = DumpString::new("/SYSV00000000 (deleted)", Endian::Little);
7242 let module = SynthModule::new(
7243 Endian::Little,
7244 0x7f602915e000,
7245 0x26000,
7246 &name,
7247 0x0,
7248 0x0,
7249 // All of these are completely zeroed out in the wild.
7250 Some(&md::VS_FIXEDFILEINFO {
7251 signature: 0,
7252 struct_version: 0,
7253 file_version_hi: 0,
7254 file_version_lo: 0,
7255 product_version_hi: 0,
7256 product_version_lo: 0,
7257 file_flags_mask: 0,
7258 file_flags: 0,
7259 file_os: 0,
7260 file_type: 0,
7261 file_subtype: 0,
7262 file_date_hi: 0,
7263 file_date_lo: 0,
7264 }),
7265 );
7266 let dump = SynthMinidump::with_endian(Endian::Little)
7267 .add_module(module)
7268 .add(name);
7269 let dump = read_synth_dump(dump).unwrap();
7270 let module_list = dump.get_stream::<MinidumpModuleList>().unwrap();
7271 let modules = module_list.iter().collect::<Vec<_>>();
7272 assert_eq!(modules.len(), 1);
7273 assert_eq!(modules[0].code_identifier(), None);
7274 assert_eq!(modules[0].debug_identifier(), None);
7275 assert_eq!(modules[0].code_file(), "/SYSV00000000 (deleted)");
7276 assert_eq!(modules[0].debug_file(), None);
7277 assert_eq!(modules[0].raw.base_of_image, 0x7f602915e000);
7278 assert_eq!(modules[0].raw.size_of_image, 0x26000);
7279 }
7280
7281 #[test]
7282 fn test_handle_data_stream() {
7283 const HANDLE_VALUE: u64 = 123;
7284 const TYPE_NAME: &str = "This is a type name";
7285 const OBJECT_NAME: &str = "And this is an object name";
7286
7287 let type_name = DumpString::new(TYPE_NAME, Endian::Little);
7288 let object_name = DumpString::new(OBJECT_NAME, Endian::Little);
7289 let handle = SynthHandleDescriptor::new(
7290 Endian::Little,
7291 HANDLE_VALUE,
7292 Some(&type_name),
7293 Some(&object_name),
7294 0xf00ff00f,
7295 0xcafecafe,
7296 0xcacacaca,
7297 0xbeefbeef,
7298 );
7299 let dump = SynthMinidump::with_endian(Endian::Little)
7300 .add_handle_descriptor(handle)
7301 .add(type_name)
7302 .add(object_name);
7303 let dump = read_synth_dump(dump).unwrap();
7304 let handle_data_stream = dump
7305 .get_stream::<MinidumpHandleDataStream>()
7306 .expect("The HANDLE_DATA_STREAM must be present");
7307 let handles = handle_data_stream.iter().collect::<Vec<_>>();
7308 assert_eq!(handles.len(), 1);
7309 assert_eq!(
7310 handles[0]
7311 .raw
7312 .handle()
7313 .expect("The `handle` field must be present"),
7314 &HANDLE_VALUE
7315 );
7316 assert_eq!(
7317 handles[0]
7318 .type_name
7319 .as_ref()
7320 .expect("The `type_name` field must be populated"),
7321 TYPE_NAME
7322 );
7323 assert_eq!(
7324 handles[0]
7325 .object_name
7326 .as_ref()
7327 .expect("The `object_name` field must be populated"),
7328 OBJECT_NAME
7329 );
7330 }
7331
7332 #[test]
7333 fn test_windows_status_code() {
7334 let address = 0x1234_5678_u64;
7335 let amd64_system_info = SystemInfo::new(Endian::Little)
7336 .set_processor_architecture(ProcessorArchitecture::PROCESSOR_ARCHITECTURE_AMD64 as u16)
7337 .set_platform_id(PlatformId::VER_PLATFORM_WIN32_NT as u32);
7338 let mut exception = Exception::new(Endian::Little);
7339 exception.exception_record.exception_code =
7340 err::ExceptionCodeWindows::EXCEPTION_IN_PAGE_ERROR as u32;
7341 exception.exception_record.exception_address = address;
7342 exception.exception_record.number_parameters = 3;
7343 exception.exception_record.exception_information[0] =
7344 err::ExceptionCodeWindowsInPageErrorType::WRITE as u64;
7345 exception.exception_record.exception_information[1] = address;
7346 exception.exception_record.exception_information[2] =
7347 err::NtStatusWindows::STATUS_DISK_FULL as u64;
7348
7349 let dump = SynthMinidump::with_endian(Endian::Little)
7350 .add_system_info(amd64_system_info)
7351 .add_exception(exception);
7352 let dump = read_synth_dump(dump).unwrap();
7353 let system_stream = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7354 let exception_stream = dump.get_stream::<MinidumpException>().unwrap();
7355 assert_eq!(
7356 exception_stream.get_crash_reason(system_stream.os, system_stream.cpu),
7357 CrashReason::WindowsInPageError(
7358 err::ExceptionCodeWindowsInPageErrorType::WRITE,
7359 NtStatusWindows::STATUS_DISK_FULL as u64
7360 )
7361 );
7362
7363 // Let's try again but for 32-bit x86
7364 let x86_system_info = SystemInfo::new(Endian::Little)
7365 .set_processor_architecture(ProcessorArchitecture::PROCESSOR_ARCHITECTURE_INTEL as u16)
7366 .set_platform_id(PlatformId::VER_PLATFORM_WIN32_NT as u32);
7367 let mut exception = Exception::new(Endian::Little);
7368 exception.exception_record.exception_code =
7369 err::ExceptionCodeWindows::EXCEPTION_IN_PAGE_ERROR as u32;
7370 exception.exception_record.exception_address = address;
7371 exception.exception_record.number_parameters = 3;
7372 exception.exception_record.exception_information[0] =
7373 err::ExceptionCodeWindowsInPageErrorType::WRITE as u64;
7374 exception.exception_record.exception_information[1] = address;
7375 // Sign extend the error code like 32-bit windbg.dll does
7376 exception.exception_record.exception_information[2] =
7377 0xffff_ffff_0000_0000 | (err::NtStatusWindows::STATUS_DISK_FULL as u64);
7378
7379 let dump = SynthMinidump::with_endian(Endian::Little)
7380 .add_system_info(x86_system_info)
7381 .add_exception(exception);
7382 let dump = read_synth_dump(dump).unwrap();
7383 let system_stream = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7384 let exception_stream = dump.get_stream::<MinidumpException>().unwrap();
7385 assert_eq!(
7386 exception_stream.get_crash_reason(system_stream.os, system_stream.cpu),
7387 CrashReason::WindowsInPageError(
7388 err::ExceptionCodeWindowsInPageErrorType::WRITE,
7389 NtStatusWindows::STATUS_DISK_FULL as u64
7390 )
7391 );
7392 }
7393
7394 #[test]
7395 fn test_linux_abort_si_code() {
7396 let amd64_system_info = SystemInfo::new(Endian::Little)
7397 .set_processor_architecture(ProcessorArchitecture::PROCESSOR_ARCHITECTURE_AMD64 as u16)
7398 .set_platform_id(PlatformId::Linux as u32);
7399 let mut exception = Exception::new(Endian::Little);
7400 exception.exception_record.exception_code = err::ExceptionCodeLinux::SIGABRT as u32;
7401 exception.exception_record.exception_flags = err::ExceptionCodeLinuxSicode::SI_TKILL as u32;
7402
7403 let dump = SynthMinidump::with_endian(Endian::Little)
7404 .add_system_info(amd64_system_info)
7405 .add_exception(exception);
7406 let dump = read_synth_dump(dump).unwrap();
7407 let system_stream = dump.get_stream::<MinidumpSystemInfo>().unwrap();
7408 let exception_stream = dump.get_stream::<MinidumpException>().unwrap();
7409 assert_eq!(
7410 exception_stream
7411 .get_crash_reason(system_stream.os, system_stream.cpu)
7412 .to_string(),
7413 "SIGABRT / SI_TKILL"
7414 );
7415 }
7416 }