Debian Codegraph @

third_party/rust/minidump-writer/src/linux/sections/handle_data_stream.rs

raw
1 use std::{
2 ffi::{CString, OsString},
3 fs::{self, DirEntry},
4 mem::{self},
5 os::unix::prelude::OsStrExt,
6 path::{Path, PathBuf},
7 };
8
9 use crate::mem_writer::MemoryWriter;
10
11 use super::*;
12
13 fn file_stat(path: &Path) -> Option<libc::stat> {
14 let c_path = CString::new(path.as_os_str().as_bytes()).ok()?;
15 let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
16 let result = unsafe { libc::stat(c_path.as_ptr(), &mut stat) };
17
18 if result == 0 {
19 Some(stat)
20 } else {
21 None
22 }
23 }
24
25 fn direntry_to_descriptor(buffer: &mut DumpBuf, entry: &DirEntry) -> Option<MDRawHandleDescriptor> {
26 let handle = filename_to_fd(&entry.file_name())?;
27 let realpath = fs::read_link(entry.path()).ok()?;
28 let path_rva = write_string_to_location(buffer, realpath.to_string_lossy().as_ref()).ok()?;
29 let stat = file_stat(&entry.path())?;
30
31 // TODO: We store the contents of `st_mode` into the `attributes` field, but
32 // we could also store a human-readable string of the file type inside
33 // `type_name_rva`. We might move this missing information (and
34 // more) inside a custom `MINIDUMP_HANDLE_OBJECT_INFORMATION_TYPE` blob.
35 // That would make this conversion loss-less.
36 Some(MDRawHandleDescriptor {
37 handle,
38 type_name_rva: 0,
39 object_name_rva: path_rva.rva,
40 attributes: stat.st_mode,
41 granted_access: 0,
42 handle_count: 0,
43 pointer_count: 0,
44 })
45 }
46
47 fn filename_to_fd(filename: &OsString) -> Option<u64> {
48 let filename = filename.to_string_lossy();
49 filename.parse::<u64>().ok()
50 }
51
52 pub fn write(
53 config: &mut MinidumpWriter,
54 buffer: &mut DumpBuf,
55 ) -> Result<MDRawDirectory, errors::SectionHandleDataStreamError> {
56 let proc_fd_path = PathBuf::from(format!("/proc/{}/fd", config.process_id));
57 let proc_fd_iter = fs::read_dir(proc_fd_path)?;
58 let descriptors: Vec<_> = proc_fd_iter
59 .filter_map(|entry| entry.ok())
60 .filter_map(|entry| direntry_to_descriptor(buffer, &entry))
61 .collect();
62 let number_of_descriptors = descriptors.len() as u32;
63
64 let stream_header = MemoryWriter::<MDRawHandleDataStream>::alloc_with_val(
65 buffer,
66 MDRawHandleDataStream {
67 size_of_header: mem::size_of::<MDRawHandleDataStream>() as u32,
68 size_of_descriptor: mem::size_of::<MDRawHandleDescriptor>() as u32,
69 number_of_descriptors,
70 reserved: 0,
71 },
72 )?;
73
74 let mut dirent = MDRawDirectory {
75 stream_type: MDStreamType::HandleDataStream as u32,
76 location: stream_header.location(),
77 };
78
79 let descriptor_list =
80 MemoryArrayWriter::<MDRawHandleDescriptor>::alloc_from_iter(buffer, descriptors)?;
81
82 dirent.location.data_size += descriptor_list.location().data_size;
83 Ok(dirent)
84 }