Debian Codegraph @

third_party/rust/minidump-writer/src/windows/minidump_writer.rs

raw
1 #![allow(unsafe_code)]
2
3 use crate::windows::errors::Error;
4 use crate::windows::ffi::{
5 capture_context, CloseHandle, GetCurrentProcess, GetCurrentThreadId, GetThreadContext,
6 MiniDumpWriteDump, MinidumpType, OpenProcess, OpenThread, ResumeThread, SuspendThread,
7 EXCEPTION_POINTERS, EXCEPTION_RECORD, FALSE, HANDLE, MINIDUMP_EXCEPTION_INFORMATION,
8 MINIDUMP_USER_STREAM, MINIDUMP_USER_STREAM_INFORMATION, PROCESS_ALL_ACCESS,
9 STATUS_NONCONTINUABLE_EXCEPTION, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION,
10 THREAD_SUSPEND_RESUME,
11 };
12 use minidump_common::format::{BreakpadInfoValid, MINIDUMP_BREAKPAD_INFO, MINIDUMP_STREAM_TYPE};
13 use scroll::Pwrite;
14 use std::os::windows::io::AsRawHandle;
15
16 pub struct MinidumpWriter {
17 /// Optional exception information
18 exc_info: Option<MINIDUMP_EXCEPTION_INFORMATION>,
19 /// Handle to the crashing process, which could be ourselves
20 crashing_process: HANDLE,
21 /// The id of the process we are dumping
22 pid: u32,
23 /// The id of the 'crashing' thread
24 tid: u32,
25 /// The exception code for the dump
26 #[allow(dead_code)]
27 exception_code: i32,
28 /// Whether we are dumping the current process or not
29 is_external_process: bool,
30 }
31
32 impl MinidumpWriter {
33 /// Creates a minidump of the current process, optionally including an
34 /// exception code and the CPU context of the specified thread. If no thread
35 /// is specified the current thread CPU context is used.
36 ///
37 /// Note that it is inherently unreliable to dump the currently running
38 /// process, at least in the event of an actual exception. It is recommended
39 /// to dump from an external process if possible via [`Self::dump_crash_context`]
40 ///
41 /// # Errors
42 ///
43 /// In addition to the errors described in [`Self::dump_crash_context`], this
44 /// function can also fail if `thread_id` is specified and we are unable to
45 /// acquire the thread's context
46 pub fn dump_local_context(
47 exception_code: Option<i32>,
48 thread_id: Option<u32>,
49 minidump_type: Option<MinidumpType>,
50 destination: &mut std::fs::File,
51 ) -> Result<(), Error> {
52 let exception_code = exception_code.unwrap_or(STATUS_NONCONTINUABLE_EXCEPTION);
53
54 // SAFETY: syscalls, while this encompasses most of the function, the user
55 // has no invariants to uphold so the entire function is not marked unsafe
56 unsafe {
57 let mut exception_context = if let Some(tid) = thread_id {
58 let mut ec = std::mem::MaybeUninit::uninit();
59
60 // We need to suspend the thread to get its context, which would be bad
61 // if it's the current thread, so we check it early before regrets happen
62 if tid == GetCurrentThreadId() {
63 capture_context(ec.as_mut_ptr());
64 } else {
65 // We _could_ just fallback to the current thread if we can't get the
66 // thread handle, but probably better for this to fail with a specific
67 // error so that the caller can do that themselves if they want to
68 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthread
69 let thread_handle = OpenThread(
70 THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SUSPEND_RESUME, // desired access rights, we only need to get the context, which also requires suspension
71 FALSE, // inherit handles
72 tid, // thread id
73 );
74
75 if thread_handle == 0 {
76 return Err(Error::ThreadOpen(std::io::Error::last_os_error()));
77 }
78
79 struct OwnedHandle(HANDLE);
80
81 impl Drop for OwnedHandle {
82 fn drop(&mut self) {
83 // SAFETY: syscall
84 unsafe { CloseHandle(self.0) };
85 }
86 }
87
88 let thread_handle = OwnedHandle(thread_handle);
89
90 // As noted in the GetThreadContext docs, we have to suspend the thread before we can get its context
91 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread
92 if SuspendThread(thread_handle.0) == u32::MAX {
93 return Err(Error::ThreadSuspend(std::io::Error::last_os_error()));
94 }
95
96 // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext
97 if GetThreadContext(thread_handle.0, ec.as_mut_ptr()) == 0 {
98 // Try to be a good citizen and resume the thread
99 ResumeThread(thread_handle.0);
100
101 return Err(Error::ThreadContext(std::io::Error::last_os_error()));
102 }
103
104 // _presumably_ this will not fail if SuspendThread succeeded, but if it does
105 // there's really not much we can do about it, thus we don't bother checking the
106 // return value
107 ResumeThread(thread_handle.0);
108 }
109
110 ec.assume_init()
111 } else {
112 let mut ec = std::mem::MaybeUninit::uninit();
113 capture_context(ec.as_mut_ptr());
114 ec.assume_init()
115 };
116
117 let mut exception_record: EXCEPTION_RECORD = std::mem::zeroed();
118
119 let exception_ptrs = EXCEPTION_POINTERS {
120 ExceptionRecord: &mut exception_record,
121 ContextRecord: &mut exception_context,
122 };
123
124 exception_record.ExceptionCode = exception_code;
125
126 let cc = crash_context::CrashContext {
127 exception_pointers: (&exception_ptrs as *const EXCEPTION_POINTERS).cast(),
128 process_id: std::process::id(),
129 thread_id: thread_id.unwrap_or_else(|| GetCurrentThreadId()),
130 exception_code,
131 };
132
133 Self::dump_crash_context(cc, minidump_type, destination)
134 }
135 }
136
137 /// Writes a minidump for the context described by [`crash_context::CrashContext`].
138 ///
139 /// # Errors
140 ///
141 /// Fails if the process specified in the context is not the local process
142 /// and we are unable to open it due to eg. security reasons, or we fail to
143 /// write the minidump, which can be due to a host of issues with both acquiring
144 /// the process information as well as writing the actual minidump contents to disk
145 ///
146 /// # Safety
147 ///
148 /// If [`crash_context::CrashContext::exception_pointers`] is specified, it
149 /// is the responsibility of the caller to ensure that the pointer is valid
150 /// for the duration of this function call.
151 pub fn dump_crash_context(
152 crash_context: crash_context::CrashContext,
153 minidump_type: Option<MinidumpType>,
154 destination: &mut std::fs::File,
155 ) -> Result<(), Error> {
156 let pid = crash_context.process_id;
157
158 // SAFETY: syscalls
159 let (crashing_process, is_external_process) = unsafe {
160 if pid != std::process::id() {
161 let proc = OpenProcess(
162 PROCESS_ALL_ACCESS, // desired access
163 FALSE, // inherit handles
164 pid, // pid
165 );
166
167 if proc == 0 {
168 return Err(std::io::Error::last_os_error().into());
169 }
170
171 (proc, true)
172 } else {
173 (GetCurrentProcess(), false)
174 }
175 };
176
177 let pid = crash_context.process_id;
178 let tid = crash_context.thread_id;
179 let exception_code = crash_context.exception_code;
180
181 let exc_info = (!crash_context.exception_pointers.is_null()).then_some(
182 // https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/ns-minidumpapiset-minidump_exception_information
183 MINIDUMP_EXCEPTION_INFORMATION {
184 ThreadId: crash_context.thread_id,
185 // This is a mut pointer for some reason...I don't _think_ it is
186 // actually mut in practice...?
187 ExceptionPointers: crash_context.exception_pointers as *mut _,
188 // The `EXCEPTION_POINTERS` contained in crash context is a pointer into the
189 // memory of the process that crashed, as it contains an `EXCEPTION_RECORD`
190 // record which is an internally linked list, so in the case that we are
191 // dumping a process other than the current one, we need to tell
192 // `MiniDumpWriteDump` that the pointers come from an external process so that
193 // it can use eg `ReadProcessMemory` to get the contextual information from
194 // the crash, rather than from the current process
195 ClientPointers: i32::from(is_external_process),
196 },
197 );
198
199 let mdw = Self {
200 exc_info,
201 crashing_process,
202 pid,
203 tid,
204 exception_code,
205 is_external_process,
206 };
207
208 mdw.dump(minidump_type, destination)
209 }
210
211 /// Writes a minidump to the specified file
212 fn dump(
213 mut self,
214 minidump_type: Option<MinidumpType>,
215 destination: &mut std::fs::File,
216 ) -> Result<(), Error> {
217 let exc_info = self.exc_info.take();
218
219 let mut user_streams = Vec::with_capacity(1);
220
221 let mut breakpad_info = self.fill_breakpad_stream();
222
223 if let Some(bp_info) = &mut breakpad_info {
224 user_streams.push(MINIDUMP_USER_STREAM {
225 Type: MINIDUMP_STREAM_TYPE::BreakpadInfoStream as u32,
226 BufferSize: bp_info.len() as u32,
227 // Again with the mut pointer
228 Buffer: bp_info.as_mut_ptr().cast(),
229 });
230 }
231
232 let user_stream_infos = MINIDUMP_USER_STREAM_INFORMATION {
233 UserStreamCount: user_streams.len() as u32,
234 UserStreamArray: user_streams.as_mut_ptr(),
235 };
236
237 // Write the actual minidump
238 // https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/nf-minidumpapiset-minidumpwritedump
239 // SAFETY: syscall
240 let ret = unsafe {
241 MiniDumpWriteDump(
242 self.crashing_process, // HANDLE to the process with the crash we want to capture
243 self.pid, // process id
244 destination.as_raw_handle() as HANDLE, // file to write the minidump to
245 minidump_type.unwrap_or(MinidumpType::Normal),
246 exc_info
247 .as_ref()
248 .map_or(std::ptr::null(), |ei| ei as *const _), // exceptionparam - the actual exception information
249 &user_stream_infos, // user streams
250 std::ptr::null(), // callback, unused
251 )
252 };
253
254 if ret == 0 {
255 Err(std::io::Error::last_os_error().into())
256 } else {
257 Ok(())
258 }
259 }
260
261 /// Create an MDRawBreakpadInfo stream to the minidump, to provide additional
262 /// information about the exception handler to the Breakpad processor.
263 /// The information will help the processor determine which threads are
264 /// relevant. The Breakpad processor does not require this information but
265 /// can function better with Breakpad-generated dumps when it is present.
266 /// The native debugger is not harmed by the presence of this information.
267 ///
268 /// This info is only relevant for in-process dumping
269 fn fill_breakpad_stream(&self) -> Option<[u8; 12]> {
270 if self.is_external_process {
271 return None;
272 }
273
274 let mut breakpad_info = [0u8; 12];
275
276 let bp_info = MINIDUMP_BREAKPAD_INFO {
277 validity: BreakpadInfoValid::DumpThreadId.bits()
278 | BreakpadInfoValid::RequestingThreadId.bits(),
279 dump_thread_id: self.tid,
280 // SAFETY: syscall
281 requesting_thread_id: unsafe { GetCurrentThreadId() },
282 };
283
284 // TODO: derive Pwrite for MINIDUMP_BREAKPAD_INFO
285 // https://github.com/rust-minidump/rust-minidump/pull/534
286 let mut offset = 0;
287 breakpad_info.gwrite(bp_info.validity, &mut offset).ok()?;
288 breakpad_info
289 .gwrite(bp_info.dump_thread_id, &mut offset)
290 .ok()?;
291 breakpad_info
292 .gwrite(bp_info.requesting_thread_id, &mut offset)
293 .ok()?;
294
295 Some(breakpad_info)
296 }
297 }
298
299 impl Drop for MinidumpWriter {
300 fn drop(&mut self) {
301 // Note we close the handle regardless of whether it is the local handle
302 // or an external one, as noted in the docs
303 //
304 // > The pseudo handle need not be closed when it is no longer needed.
305 // > Calling the CloseHandle function with a pseudo handle has no effect.
306 // SAFETY: syscall
307 unsafe { CloseHandle(self.crashing_process) };
308 }
309 }