Debian Codegraph @

third_party/rust/minidump-writer/src/linux/dso_debug.rs

raw
1 use crate::{
2 linux::{auxv::AuxvDumpInfo, errors::SectionDsoDebugError, ptrace_dumper::PtraceDumper},
3 mem_writer::{write_string_to_location, Buffer, MemoryArrayWriter, MemoryWriter},
4 minidump_format::*,
5 };
6
7 type Result<T> = std::result::Result<T, SectionDsoDebugError>;
8
9 cfg_if::cfg_if! {
10 if #[cfg(target_pointer_width = "32")] {
11 use goblin::elf::program_header::program_header32::SIZEOF_PHDR;
12 } else if #[cfg(target_pointer_width = "64")] {
13 use goblin::elf::program_header::program_header64::SIZEOF_PHDR;
14 }
15 }
16
17 cfg_if::cfg_if! {
18 if #[cfg(all(target_pointer_width = "64", target_arch = "arm"))] {
19 type ElfAddr = u64;
20 } else if #[cfg(all(target_pointer_width = "64", not(target_arch = "arm")))] {
21 type ElfAddr = libc::Elf64_Addr;
22 } else if #[cfg(all(target_pointer_width = "32", target_arch = "arm"))] {
23 type ElfAddr = u32;
24 } else if #[cfg(all(target_pointer_width = "32", not(target_arch = "arm")))] {
25 type ElfAddr = libc::Elf32_Addr;
26 }
27 }
28
29 // COPY from <link.h>
30 #[derive(Debug, Clone, Default)]
31 #[repr(C)]
32 pub struct LinkMap {
33 /* These first few members are part of the protocol with the debugger.
34 This is the same format used in SVR4. */
35 l_addr: ElfAddr, /* Difference between the address in the ELF
36 file and the addresses in memory. */
37 l_name: usize, /* Absolute file name object was found in. WAS: `char*` */
38 l_ld: usize, /* Dynamic section of the shared object. WAS: `ElfW(Dyn) *` */
39 l_next: usize, /* Chain of loaded objects. WAS: `struct link_map *` */
40 l_prev: usize, /* Chain of loaded objects. WAS: `struct link_map *` */
41 }
42
43 // COPY from <link.h>
44 /// This state value describes the mapping change taking place when
45 /// the `r_brk' address is called.
46 #[derive(Debug, Clone, Default)]
47 #[allow(non_camel_case_types, unused)]
48 #[repr(C)]
49 enum RState {
50 /// Mapping change is complete.
51 #[default]
52 RT_CONSISTENT,
53 /// Beginning to add a new object.
54 RT_ADD,
55 /// Beginning to remove an object mapping.
56 RT_DELETE,
57 }
58
59 // COPY from <link.h>
60 #[derive(Debug, Clone, Default)]
61 #[repr(C)]
62 pub struct RDebug {
63 r_version: libc::c_int, /* Version number for this protocol. */
64 r_map: usize, /* Head of the chain of loaded objects. WAS: `struct link_map *` */
65
66 /* This is the address of a function internal to the run-time linker,
67 that will always be called when the linker begins to map in a
68 library or unmap it, and again when the mapping change is complete.
69 The debugger can set a breakpoint at this address if it wants to
70 notice shared object mapping changes. */
71 r_brk: ElfAddr,
72 r_state: RState,
73 r_ldbase: ElfAddr, /* Base address the linker is loaded at. */
74 }
75
76 pub fn write_dso_debug_stream(
77 buffer: &mut Buffer,
78 blamed_thread: i32,
79 auxv: &AuxvDumpInfo,
80 ) -> Result<MDRawDirectory> {
81 let phnum_max =
82 auxv.get_program_header_count()
83 .ok_or(SectionDsoDebugError::CouldNotFind("AT_PHNUM in auxv"))? as usize;
84 let phdr = auxv
85 .get_program_header_address()
86 .ok_or(SectionDsoDebugError::CouldNotFind("AT_PHDR in auxv"))? as usize;
87
88 let ph = PtraceDumper::copy_from_process(blamed_thread, phdr, SIZEOF_PHDR * phnum_max)?;
89 let program_headers;
90 #[cfg(target_pointer_width = "64")]
91 {
92 program_headers = goblin::elf::program_header::program_header64::ProgramHeader::from_bytes(
93 &ph, phnum_max,
94 );
95 }
96 #[cfg(target_pointer_width = "32")]
97 {
98 program_headers = goblin::elf::program_header::program_header32::ProgramHeader::from_bytes(
99 &ph, phnum_max,
100 );
101 };
102
103 // Assume the program base is at the beginning of the same page as the PHDR
104 let mut base = phdr & !0xfff;
105 let mut dyn_addr = 0;
106 // Search for the program PT_DYNAMIC segment
107 for ph in program_headers {
108 // Adjust base address with the virtual address of the PT_LOAD segment
109 // corresponding to offset 0
110 if ph.p_type == goblin::elf::program_header::PT_LOAD && ph.p_offset == 0 {
111 base -= ph.p_vaddr as usize;
112 }
113 if ph.p_type == goblin::elf::program_header::PT_DYNAMIC {
114 dyn_addr = ph.p_vaddr;
115 }
116 }
117
118 if dyn_addr == 0 {
119 return Err(SectionDsoDebugError::CouldNotFind(
120 "dyn_addr in program headers",
121 ));
122 }
123
124 dyn_addr += base as ElfAddr;
125
126 let dyn_size = std::mem::size_of::<goblin::elf::Dyn>();
127 let mut r_debug = 0usize;
128 let mut dynamic_length = 0usize;
129
130 // The dynamic linker makes information available that helps gdb find all
131 // DSOs loaded into the program. If this information is indeed available,
132 // dump it to a MD_LINUX_DSO_DEBUG stream.
133 loop {
134 let dyn_data = PtraceDumper::copy_from_process(
135 blamed_thread,
136 dyn_addr as usize + dynamic_length,
137 dyn_size,
138 )?;
139 dynamic_length += dyn_size;
140
141 // goblin::elf::Dyn doesn't have padding bytes
142 let (head, body, _tail) = unsafe { dyn_data.align_to::<goblin::elf::Dyn>() };
143 assert!(head.is_empty(), "Data was not aligned");
144 let dyn_struct = &body[0];
145
146 let debug_tag = goblin::elf::dynamic::DT_DEBUG;
147 if dyn_struct.d_tag == debug_tag {
148 r_debug = dyn_struct.d_val as usize;
149 } else if dyn_struct.d_tag == goblin::elf::dynamic::DT_NULL {
150 break;
151 }
152 }
153
154 // The "r_map" field of that r_debug struct contains a linked list of all
155 // loaded DSOs.
156 // Our list of DSOs potentially is different from the ones in the crashing
157 // process. So, we have to be careful to never dereference pointers
158 // directly. Instead, we use CopyFromProcess() everywhere.
159 // See <link.h> for a more detailed discussion of the how the dynamic
160 // loader communicates with debuggers.
161
162 let debug_entry_data =
163 PtraceDumper::copy_from_process(blamed_thread, r_debug, std::mem::size_of::<RDebug>())?;
164
165 // goblin::elf::Dyn doesn't have padding bytes
166 let (head, body, _tail) = unsafe { debug_entry_data.align_to::<RDebug>() };
167 assert!(head.is_empty(), "Data was not aligned");
168 let debug_entry = &body[0];
169
170 // Count the number of loaded DSOs
171 let mut dso_vec = Vec::new();
172 let mut curr_map = debug_entry.r_map;
173 while curr_map != 0 {
174 let link_map_data = PtraceDumper::copy_from_process(
175 blamed_thread,
176 curr_map,
177 std::mem::size_of::<LinkMap>(),
178 )?;
179
180 // LinkMap is repr(C) and doesn't have padding bytes, so this should be safe
181 let (head, body, _tail) = unsafe { link_map_data.align_to::<LinkMap>() };
182 assert!(head.is_empty(), "Data was not aligned");
183 let map = &body[0];
184
185 curr_map = map.l_next;
186 dso_vec.push(map.clone());
187 }
188
189 let mut linkmap_rva = u32::MAX;
190 if !dso_vec.is_empty() {
191 // If we have at least one DSO, create an array of MDRawLinkMap
192 // entries in the minidump file.
193 let mut linkmap = MemoryArrayWriter::<MDRawLinkMap>::alloc_array(buffer, dso_vec.len())?;
194 linkmap_rva = linkmap.location().rva;
195
196 // Iterate over DSOs and write their information to mini dump
197 for (idx, map) in dso_vec.iter().enumerate() {
198 let mut filename = String::new();
199 if map.l_name > 0 {
200 let filename_data =
201 PtraceDumper::copy_from_process(blamed_thread, map.l_name, 256)?;
202
203 // C - string is NULL-terminated
204 if let Some(name) = filename_data.splitn(2, |x| *x == b'\0').next() {
205 filename = String::from_utf8(name.to_vec())?;
206 }
207 }
208 let location = write_string_to_location(buffer, &filename)?;
209 let entry = MDRawLinkMap {
210 addr: map.l_addr,
211 name: location.rva,
212 ld: map.l_ld as ElfAddr,
213 };
214
215 linkmap.set_value_at(buffer, entry, idx)?;
216 }
217 }
218
219 // Write MD_LINUX_DSO_DEBUG record
220 let debug = MDRawDebug {
221 version: debug_entry.r_version as u32,
222 map: linkmap_rva,
223 dso_count: dso_vec.len() as u32,
224 brk: debug_entry.r_brk,
225 ldbase: debug_entry.r_ldbase,
226 dynamic: dyn_addr,
227 };
228 let debug_loc = MemoryWriter::<MDRawDebug>::alloc_with_val(buffer, debug)?;
229
230 let mut dirent = MDRawDirectory {
231 stream_type: MDStreamType::LinuxDsoDebug as u32,
232 location: debug_loc.location(),
233 };
234
235 dirent.location.data_size += dynamic_length as u32;
236 let dso_debug_data =
237 PtraceDumper::copy_from_process(blamed_thread, dyn_addr as usize, dynamic_length)?;
238 MemoryArrayWriter::write_bytes(buffer, &dso_debug_data);
239
240 Ok(dirent)
241 }