Debian Codegraph @

third_party/rust/minidump-writer/src/mac/task_dumper.rs

raw
1 use crate::mac::mach;
2 use mach2::mach_types as mt;
3 use thiserror::Error;
4
5 #[derive(Error, Debug)]
6 pub enum TaskDumpError {
7 #[error("kernel error {syscall} {error})")]
8 Kernel {
9 syscall: &'static str,
10 error: mach::KernelError,
11 },
12 #[error("detected an invalid mach image header")]
13 InvalidMachHeader,
14 #[error(transparent)]
15 NonUtf8String(#[from] std::string::FromUtf8Error),
16 #[error("unable to find the main executable image for the process")]
17 NoExecutableImage,
18 #[error("expected load command {name}({id:?}) was not found for an image")]
19 MissingLoadCommand {
20 name: &'static str,
21 id: mach::LoadCommandKind,
22 },
23 }
24
25 /// Wraps a mach call in a Result
26 macro_rules! mach_call {
27 ($call:expr) => {{
28 // SAFETY: syscall
29 let kr = unsafe { $call };
30 if kr == mach::KERN_SUCCESS {
31 Ok(())
32 } else {
33 // This is ugly, improvements to the macro welcome!
34 let mut syscall = stringify!($call);
35 if let Some(i) = syscall.find('(') {
36 syscall = &syscall[..i];
37 }
38 Err(TaskDumpError::Kernel {
39 syscall,
40 error: kr.into(),
41 })
42 }
43 }};
44 }
45
46 /// `dyld_all_image_infos` from <usr/include/mach-o/dyld_images.h>
47 ///
48 /// This struct is truncated as we only need a couple of fields at the beginning
49 /// of the struct
50 #[repr(C)]
51 #[derive(Copy, Clone)]
52 pub struct AllImagesInfo {
53 // VERSION 1
54 pub version: u32,
55 /// The number of [`ImageInfo`] structs at that following address
56 info_array_count: u32,
57 /// The address in the process where the array of [`ImageInfo`] structs is
58 info_array_addr: u64,
59 /// A function pointer, unused
60 _notification: u64,
61 /// Unused
62 _process_detached_from_shared_region: bool,
63 // VERSION 2
64 lib_system_initialized: bool,
65 // Note that crashpad adds a 32-bit int here to get proper alignment when
66 // building on 32-bit targets...but we explicitly don't care about 32-bit
67 // targets since Apple doesn't
68 pub dyld_image_load_address: u64,
69 }
70
71 /// `dyld_image_info` from <usr/include/mach-o/dyld_images.h>
72 #[repr(C)]
73 #[derive(Debug, Clone, Copy)]
74 pub struct ImageInfo {
75 /// The address in the process where the image is loaded
76 pub load_address: u64,
77 /// The address in the process where the image's file path can be read
78 pub file_path: u64,
79 /// Timestamp for when the image's file was last modified
80 pub file_mod_date: u64,
81 }
82
83 impl PartialEq for ImageInfo {
84 fn eq(&self, o: &Self) -> bool {
85 self.load_address == o.load_address
86 }
87 }
88
89 impl Eq for ImageInfo {}
90
91 impl Ord for ImageInfo {
92 fn cmp(&self, o: &Self) -> std::cmp::Ordering {
93 self.load_address.cmp(&o.load_address)
94 }
95 }
96
97 impl PartialOrd for ImageInfo {
98 fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
99 Some(self.cmp(o))
100 }
101 }
102
103 /// Describes a region of virtual memory
104 pub struct VMRegionInfo {
105 pub info: mach::vm_region_submap_info_64,
106 pub range: std::ops::Range<u64>,
107 }
108
109 /// Similarly to PtraceDumper for Linux, this provides access to information
110 /// for a task (MacOS process)
111 pub struct TaskDumper {
112 task: mt::task_t,
113 page_size: i64,
114 }
115
116 impl TaskDumper {
117 /// Constructs a [`TaskDumper`] for the specified task
118 pub fn new(task: mt::task_t) -> Self {
119 Self {
120 task,
121 // SAFETY: syscall
122 page_size: unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as i64,
123 }
124 }
125
126 /// Reads a block of memory from the task
127 ///
128 /// # Errors
129 ///
130 /// The syscall to read the task's memory fails for some reason, eg bad address.
131 pub fn read_task_memory<T>(&self, address: u64, count: usize) -> Result<Vec<T>, TaskDumpError>
132 where
133 T: Sized + Clone,
134 {
135 let length = (count * std::mem::size_of::<T>()) as u64;
136
137 // use the negative of the page size for the mask to find the page address
138 let page_address = address & (-self.page_size as u64);
139 let last_page_address =
140 (address + length + (self.page_size - 1) as u64) & (-self.page_size as u64);
141
142 let page_size = last_page_address - page_address;
143 let mut local_start = 0;
144 let mut local_length = 0;
145
146 mach_call!(mach::mach_vm_read(
147 self.task,
148 page_address,
149 page_size,
150 &mut local_start,
151 &mut local_length
152 ))?;
153
154 let mut buffer = Vec::with_capacity(count);
155
156 // SAFETY: this is safe as long as the kernel has not lied to us
157 let task_buffer = unsafe {
158 std::slice::from_raw_parts(
159 (local_start as *const u8)
160 .offset((address - page_address) as isize)
161 .cast(),
162 count,
163 )
164 };
165 buffer.extend_from_slice(task_buffer);
166
167 // Don't worry about the return here, if something goes wrong there's probably
168 // not much we can do about it, and we have what we want anyways
169 let _res = mach_call!(mach::mach_vm_deallocate(
170 mach::mach_task_self(),
171 local_start as u64, // vm_read returns a pointer, but vm_deallocate takes a integer address :-/
172 local_length as u64, // vm_read and vm_deallocate use different sizes :-/
173 ));
174
175 Ok(buffer)
176 }
177
178 /// Reads a null terminated string starting at the specified address. This
179 /// is a specialization of [`read_task_memory`] since strings can span VM
180 /// regions.
181 ///
182 /// If not specified, the string is capped at 8k which should never be close
183 /// to being hit in normal scenarios, at least for "system" strings, which is
184 /// all this interface is used to retrieve
185 ///
186 /// # Errors
187 ///
188 /// Fails if the address cannot be read for some reason, or the string is
189 /// not utf-8.
190 pub fn read_string(
191 &self,
192 addr: u64,
193 expected_size: Option<usize>,
194 ) -> Result<Option<String>, TaskDumpError> {
195 // The problem is we don't know how much to read until we know how long
196 // the string is. And we don't know how long the string is, until we've read
197 // the memory! So, we'll try to read kMaxStringLength bytes
198 // (or as many bytes as we can until we reach the end of the vm region).
199 let get_region_size = || -> Result<u64, TaskDumpError> {
200 let region = self.get_vm_region(addr)?;
201
202 let mut size_to_end = region.range.end - addr;
203
204 // If the remaining is less than 4k, check if the next region is
205 // contiguous, and extend the memory that could contain the string
206 // to include it
207 if size_to_end < 4 * 1024 {
208 let maybe_adjacent = self.get_vm_region(region.range.end)?;
209
210 if maybe_adjacent.range.start == region.range.end {
211 size_to_end += maybe_adjacent.range.end - maybe_adjacent.range.start;
212 }
213 }
214
215 Ok(size_to_end)
216 };
217
218 if let Ok(size_to_end) = get_region_size() {
219 let mut bytes = self.read_task_memory(
220 addr,
221 std::cmp::min(size_to_end as usize, expected_size.unwrap_or(8 * 1024)),
222 )?;
223
224 // Find the null terminator and truncate our string
225 if let Some(null_pos) = bytes.iter().position(|c| *c == 0) {
226 bytes.resize(null_pos, 0);
227 }
228
229 Ok(String::from_utf8(bytes).map(Some)?)
230 } else {
231 Ok(None)
232 }
233 }
234
235 /// Retrives information on the virtual memory region the specified address
236 /// is located within.
237 ///
238 /// # Errors
239 ///
240 /// The syscall to retrieve the VM region information fails for some reason,
241 /// eg. a bad address.
242 pub fn get_vm_region(&self, addr: u64) -> Result<VMRegionInfo, TaskDumpError> {
243 let mut region_base = addr;
244 let mut region_size = 0;
245 let mut nesting_level = 0;
246 let mut submap_info = std::mem::MaybeUninit::<mach::vm_region_submap_info_64>::uninit();
247
248 // <user/include/mach/vm_region.h>
249 const VM_REGION_SUBMAP_INFO_COUNT_64: u32 =
250 (std::mem::size_of::<mach::vm_region_submap_info_64>() / std::mem::size_of::<u32>())
251 as u32;
252
253 let mut info_count = VM_REGION_SUBMAP_INFO_COUNT_64;
254
255 mach_call!(mach::mach_vm_region_recurse(
256 self.task,
257 &mut region_base,
258 &mut region_size,
259 &mut nesting_level,
260 submap_info.as_mut_ptr().cast(),
261 &mut info_count,
262 ))?;
263
264 Ok(VMRegionInfo {
265 // SAFETY: this will be valid if the syscall succeeded
266 info: unsafe { submap_info.assume_init() },
267 range: region_base..region_base + region_size,
268 })
269 }
270
271 /// Retrieves the state of the specified thread. The state is an architecture
272 /// specific block of CPU context ie register state.
273 ///
274 /// # Errors
275 ///
276 /// The specified thread id is invalid, or the thread is in a task that is
277 /// compiled for a different architecture than this local task.
278 pub fn read_thread_state(&self, tid: u32) -> Result<mach::ThreadState, TaskDumpError> {
279 let mut thread_state = mach::ThreadState::default();
280
281 mach_call!(mach::thread_get_state(
282 tid,
283 mach::THREAD_STATE_FLAVOR as i32,
284 thread_state.state.as_mut_ptr(),
285 &mut thread_state.state_size,
286 ))?;
287
288 Ok(thread_state)
289 }
290
291 /// Reads the specified task information.
292 ///
293 /// # Errors
294 ///
295 /// The syscall to receive the task information failed for some reason, eg.
296 /// the specified type and the flavor are mismatched and considered invalid.
297 pub fn task_info<T: mach::TaskInfo>(&self) -> Result<T, TaskDumpError> {
298 let mut info = std::mem::MaybeUninit::<T>::uninit();
299 let mut count = (std::mem::size_of::<T>() / std::mem::size_of::<u32>()) as u32;
300
301 mach_call!(mach::task::task_info(
302 self.task,
303 T::FLAVOR,
304 info.as_mut_ptr().cast(),
305 &mut count
306 ))?;
307
308 // SAFETY: this will be initialized if the call succeeded
309 unsafe { Ok(info.assume_init()) }
310 }
311
312 /// Reads the specified task information.
313 ///
314 /// # Errors
315 ///
316 /// The syscall to receive the task information failed for some reason, eg.
317 /// the specified type and the flavor are mismatched and considered invalid,
318 /// or the thread no longer exists
319 pub fn thread_info<T: mach::ThreadInfo>(&self, tid: u32) -> Result<T, TaskDumpError> {
320 let mut thread_info = std::mem::MaybeUninit::<T>::uninit();
321 let mut count = (std::mem::size_of::<T>() / std::mem::size_of::<u32>()) as u32;
322
323 mach_call!(mach::thread_info(
324 tid,
325 T::FLAVOR,
326 thread_info.as_mut_ptr().cast(),
327 &mut count,
328 ))?;
329
330 // SAFETY: this will be initialized if the call succeeded
331 unsafe { Ok(thread_info.assume_init()) }
332 }
333
334 /// Retrieves all of the images loaded in the task.
335 ///
336 /// Note that there may be multiple images with the same load address.
337 ///
338 /// # Errors
339 ///
340 /// The syscall to retrieve the location of the loaded images fails, or
341 /// the syscall to read the loaded images from the process memory fails
342 pub fn read_images(&self) -> Result<(AllImagesInfo, Vec<ImageInfo>), TaskDumpError> {
343 impl mach::TaskInfo for mach::task_info::task_dyld_info {
344 const FLAVOR: u32 = mach::task_info::TASK_DYLD_INFO;
345 }
346
347 // Retrieve the address at which the list of loaded images is located
348 // within the task
349 let all_images_addr = {
350 let dyld_info = self.task_info::<mach::task_info::task_dyld_info>()?;
351 dyld_info.all_image_info_addr
352 };
353
354 // Here we make the assumption that dyld loaded at the same address in
355 // the crashed process vs. this one. This is an assumption made in
356 // "dyld_debug.c" and is said to be nearly always valid.
357 let dyld_all_info_buf =
358 self.read_task_memory::<u8>(all_images_addr, std::mem::size_of::<AllImagesInfo>())?;
359 // SAFETY: this is fine as long as the kernel isn't lying to us
360 let all_images_info: &AllImagesInfo = unsafe { &*(dyld_all_info_buf.as_ptr().cast()) };
361
362 let images = self.read_task_memory::<ImageInfo>(
363 all_images_info.info_array_addr,
364 all_images_info.info_array_count as usize,
365 )?;
366
367 Ok((*all_images_info, images))
368 }
369
370 /// Retrieves the main executable image for the task.
371 ///
372 /// Note that this method is currently only used for tests due to deficiencies
373 /// in `otool`
374 ///
375 /// # Errors
376 ///
377 /// Any of the errors that apply to [`Self::read_images`] apply here, in
378 /// addition to not being able to find the main executable image
379 pub fn read_executable_image(&self) -> Result<ImageInfo, TaskDumpError> {
380 let (_, images) = self.read_images()?;
381
382 for img in images {
383 let mach_header = self.read_task_memory::<mach::MachHeader>(img.load_address, 1)?;
384
385 let header = &mach_header[0];
386
387 if header.magic != mach::MH_MAGIC_64 {
388 return Err(TaskDumpError::InvalidMachHeader);
389 }
390
391 if header.file_type == mach::MH_EXECUTE {
392 return Ok(img);
393 }
394 }
395
396 Err(TaskDumpError::NoExecutableImage)
397 }
398
399 /// Retrieves the load commands for the specified image
400 ///
401 /// # Errors
402 ///
403 /// We fail to read the image header for the specified image, the header we
404 /// read is determined to be invalid, or we fail to read the block of memory
405 /// containing the load commands themselves.
406 pub fn read_load_commands(&self, img: &ImageInfo) -> Result<mach::LoadCommands, TaskDumpError> {
407 let mach_header = self.read_task_memory::<mach::MachHeader>(img.load_address, 1)?;
408
409 let header = &mach_header[0];
410
411 if header.magic != mach::MH_MAGIC_64 {
412 return Err(TaskDumpError::InvalidMachHeader);
413 }
414
415 // Read the load commands which immediately follow the image header from
416 // the task memory. Note that load commands vary in size so we need to
417 // retrieve the memory as a raw byte buffer that we can then iterate
418 // through and step according to the size of each load command
419 let load_commands_buf = self.read_task_memory::<u8>(
420 img.load_address + std::mem::size_of::<mach::MachHeader>() as u64,
421 header.size_commands as usize,
422 )?;
423
424 Ok(mach::LoadCommands {
425 buffer: load_commands_buf,
426 count: header.num_commands,
427 })
428 }
429
430 /// Gets a list of all of the thread ids in the task
431 ///
432 /// # Errors
433 ///
434 /// The syscall to retrieve the list of threads fails
435 pub fn read_threads(&self) -> Result<&'static [u32], TaskDumpError> {
436 let mut threads = std::ptr::null_mut();
437 let mut thread_count = 0;
438
439 mach_call!(mach::task_threads(
440 self.task,
441 &mut threads,
442 &mut thread_count
443 ))?;
444
445 Ok(
446 // SAFETY: This should be valid if the call succeeded
447 unsafe { std::slice::from_raw_parts(threads, thread_count as usize) },
448 )
449 }
450
451 /// Retrieves the PID for the task
452 ///
453 /// # Errors
454 ///
455 /// Presumably the only way this would fail would be if the task we are
456 /// dumping disappears.
457 pub fn pid_for_task(&self) -> Result<i32, TaskDumpError> {
458 let mut pid = 0;
459 mach_call!(mach::pid_for_task(self.task, &mut pid))?;
460 Ok(pid)
461 }
462 }