1 // Copyright 2012 Google LLC
2 //
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
5 // met:
6 //
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
12 // distribution.
13 // * Neither the name of Google LLC nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 // linux_ptrace_dumper.cc: Implement google_breakpad::LinuxPtraceDumper.
30 // See linux_ptrace_dumper.h for detals.
31 // This class was originally splitted from google_breakpad::LinuxDumper.
32
33 // This code deals with the mechanics of getting information about a crashed
34 // process. Since this code may run in a compromised address space, the same
35 // rules apply as detailed at the top of minidump_writer.h: no libc calls and
36 // use the alternative allocator.
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h> // Must come first
40 #endif
41
42 #include "client/linux/minidump_writer/linux_ptrace_dumper.h"
43
44 #include <asm/ptrace.h>
45 #include <assert.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <limits.h>
49 #include <stddef.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <sys/ptrace.h>
53 #include <sys/uio.h>
54 #include <sys/wait.h>
55
56 #if defined(__i386)
57 #include <cpuid.h>
58 #endif
59
60 #include "client/linux/minidump_writer/directory_reader.h"
61 #include "client/linux/minidump_writer/line_reader.h"
62 #include "common/linux/linux_libc_support.h"
63 #include "third_party/lss/linux_syscall_support.h"
64
65 // Suspends a thread by attaching to it.
SuspendThread(pid_t pid)66 static bool SuspendThread(pid_t pid) {
67 // This may fail if the thread has just died or debugged.
68 errno = 0;
69 if (sys_ptrace(PTRACE_ATTACH, pid, NULL, NULL) != 0 &&
70 errno != 0) {
71 return false;
72 }
73 while (sys_waitpid(pid, NULL, __WALL) < 0) {
74 if (errno != EINTR) {
75 sys_ptrace(PTRACE_DETACH, pid, NULL, NULL);
76 return false;
77 }
78 }
79 #if defined(__i386) || defined(__x86_64)
80 // On x86, the stack pointer is NULL or -1, when executing trusted code in
81 // the seccomp sandbox. Not only does this cause difficulties down the line
82 // when trying to dump the thread's stack, it also results in the minidumps
83 // containing information about the trusted threads. This information is
84 // generally completely meaningless and just pollutes the minidumps.
85 // We thus test the stack pointer and exclude any threads that are part of
86 // the seccomp sandbox's trusted code.
87 user_regs_struct regs;
88 if (sys_ptrace(PTRACE_GETREGS, pid, NULL, ®s) == -1 ||
89 #if defined(__i386)
90 !regs.esp
91 #elif defined(__x86_64)
92 !regs.rsp
93 #endif
94 ) {
95 sys_ptrace(PTRACE_DETACH, pid, NULL, NULL);
96 return false;
97 }
98 #endif
99 return true;
100 }
101
102 // Resumes a thread by detaching from it.
ResumeThread(pid_t pid)103 static bool ResumeThread(pid_t pid) {
104 return sys_ptrace(PTRACE_DETACH, pid, NULL, NULL) >= 0;
105 }
106
107 namespace google_breakpad {
108
LinuxPtraceDumper(pid_t pid)109 LinuxPtraceDumper::LinuxPtraceDumper(pid_t pid)
110 : LinuxDumper(pid),
111 threads_suspended_(false) {
112 }
113
BuildProcPath(char * path,pid_t pid,const char * node) const114 bool LinuxPtraceDumper::BuildProcPath(char* path, pid_t pid,
115 const char* node) const {
116 if (!path || !node || pid <= 0)
117 return false;
118
119 size_t node_len = my_strlen(node);
120 if (node_len == 0)
121 return false;
122
123 const unsigned pid_len = my_uint_len(pid);
124 const size_t total_length = 6 + pid_len + 1 + node_len;
125 if (total_length >= NAME_MAX)
126 return false;
127
128 my_memcpy(path, "/proc/", 6);
129 my_uitos(path + 6, pid, pid_len);
130 path[6 + pid_len] = '/';
131 my_memcpy(path + 6 + pid_len + 1, node, node_len);
132 path[total_length] = '\0';
133 return true;
134 }
135
CopyFromProcess(void * dest,pid_t child,const void * src,size_t length)136 bool LinuxPtraceDumper::CopyFromProcess(void* dest, pid_t child,
137 const void* src, size_t length) {
138 unsigned long tmp = 55;
139 size_t done = 0;
140 static const size_t word_size = sizeof(tmp);
141 uint8_t* const local = (uint8_t*) dest;
142 uint8_t* const remote = (uint8_t*) src;
143
144 while (done < length) {
145 const size_t l = (length - done > word_size) ? word_size : (length - done);
146 if (sys_ptrace(PTRACE_PEEKDATA, child, remote + done, &tmp) == -1) {
147 tmp = 0;
148 }
149 my_memcpy(local + done, &tmp, l);
150 done += l;
151 }
152 return true;
153 }
154
ReadRegisterSet(ThreadInfo * info,pid_t tid)155 bool LinuxPtraceDumper::ReadRegisterSet(ThreadInfo* info, pid_t tid)
156 {
157 #ifdef PTRACE_GETREGSET
158 struct iovec io;
159 info->GetGeneralPurposeRegisters(&io.iov_base, &io.iov_len);
160 if (sys_ptrace(PTRACE_GETREGSET, tid, (void*)NT_PRSTATUS, (void*)&io) == -1) {
161 return false;
162 }
163
164 info->GetFloatingPointRegisters(&io.iov_base, &io.iov_len);
165 if (sys_ptrace(PTRACE_GETREGSET, tid, (void*)NT_FPREGSET, (void*)&io) == -1) {
166 return false;
167 }
168 return true;
169 #else
170 return false;
171 #endif
172 }
173
ReadRegisters(ThreadInfo * info,pid_t tid)174 bool LinuxPtraceDumper::ReadRegisters(ThreadInfo* info, pid_t tid) {
175 #ifdef PTRACE_GETREGS
176 void* gp_addr;
177 info->GetGeneralPurposeRegisters(&gp_addr, NULL);
178 if (sys_ptrace(PTRACE_GETREGS, tid, NULL, gp_addr) == -1) {
179 return false;
180 }
181
182 // When running on arm processors the binary may be built with softfp or
183 // hardfp. If built with softfp we have no hardware registers to read from,
184 // so the following read will always fail. gcc defines __SOFTFP__ macro,
185 // clang13 does not do so. see: https://reviews.llvm.org/D135680.
186 // If you are using clang and the macro is NOT defined, please include the
187 // macro define for applicable targets.
188 #if !defined(__SOFTFP__)
189 #if !(defined(__ANDROID__) && defined(__ARM_EABI__))
190 // When running an arm build on an arm64 device, attempting to get the
191 // floating point registers fails. On Android, the floating point registers
192 // aren't written to the cpu context anyway, so just don't get them here.
193 // See http://crbug.com/508324
194 void* fp_addr;
195 info->GetFloatingPointRegisters(&fp_addr, NULL);
196 if (sys_ptrace(PTRACE_GETFPREGS, tid, NULL, fp_addr) == -1) {
197 return false;
198 }
199 #endif // !(defined(__ANDROID__) && defined(__ARM_EABI__))
200 #endif // !defined(__SOFTFP__)
201 return true;
202 #else // PTRACE_GETREGS
203 return false;
204 #endif
205 }
206
207 // Read thread info from /proc/$pid/status.
208 // Fill out the |tgid|, |ppid| and |pid| members of |info|. If unavailable,
209 // these members are set to -1. Returns true iff all three members are
210 // available.
GetThreadInfoByIndex(size_t index,ThreadInfo * info)211 bool LinuxPtraceDumper::GetThreadInfoByIndex(size_t index, ThreadInfo* info) {
212 if (index >= threads_.size())
213 return false;
214
215 pid_t tid = threads_[index];
216
217 assert(info != NULL);
218 char status_path[NAME_MAX];
219 if (!BuildProcPath(status_path, tid, "status"))
220 return false;
221
222 const int fd = sys_open(status_path, O_RDONLY, 0);
223 if (fd < 0)
224 return false;
225
226 LineReader* const line_reader = new(allocator_) LineReader(fd);
227 const char* line;
228 unsigned line_len;
229
230 info->ppid = info->tgid = -1;
231
232 while (line_reader->GetNextLine(&line, &line_len)) {
233 if (my_strncmp("Tgid:\t", line, 6) == 0) {
234 my_strtoui(&info->tgid, line + 6);
235 } else if (my_strncmp("PPid:\t", line, 6) == 0) {
236 my_strtoui(&info->ppid, line + 6);
237 }
238
239 line_reader->PopLine(line_len);
240 }
241 sys_close(fd);
242
243 if (info->ppid == -1 || info->tgid == -1)
244 return false;
245
246 if (!ReadRegisterSet(info, tid)) {
247 if (!ReadRegisters(info, tid)) {
248 return false;
249 }
250 }
251
252 #if defined(__i386)
253 #if !defined(bit_FXSAVE) // e.g. Clang
254 #define bit_FXSAVE bit_FXSR
255 #endif
256 // Detect if the CPU supports the FXSAVE/FXRSTOR instructions
257 int eax, ebx, ecx, edx;
258 __cpuid(1, eax, ebx, ecx, edx);
259 if (edx & bit_FXSAVE) {
260 if (sys_ptrace(PTRACE_GETFPXREGS, tid, NULL, &info->fpxregs) == -1) {
261 return false;
262 }
263 } else {
264 memset(&info->fpxregs, 0, sizeof(info->fpxregs));
265 }
266 #endif // defined(__i386)
267
268 #if defined(__i386) || defined(__x86_64)
269 for (unsigned i = 0; i < ThreadInfo::kNumDebugRegisters; ++i) {
270 if (sys_ptrace(
271 PTRACE_PEEKUSER, tid,
272 reinterpret_cast<void*> (offsetof(struct user,
273 u_debugreg[0]) + i *
274 sizeof(debugreg_t)),
275 &info->dregs[i]) == -1) {
276 return false;
277 }
278 }
279 #endif
280
281 #if defined(__mips__)
282 sys_ptrace(PTRACE_PEEKUSER, tid,
283 reinterpret_cast<void*>(PC), &info->mcontext.pc);
284 sys_ptrace(PTRACE_PEEKUSER, tid,
285 reinterpret_cast<void*>(DSP_BASE), &info->mcontext.hi1);
286 sys_ptrace(PTRACE_PEEKUSER, tid,
287 reinterpret_cast<void*>(DSP_BASE + 1), &info->mcontext.lo1);
288 sys_ptrace(PTRACE_PEEKUSER, tid,
289 reinterpret_cast<void*>(DSP_BASE + 2), &info->mcontext.hi2);
290 sys_ptrace(PTRACE_PEEKUSER, tid,
291 reinterpret_cast<void*>(DSP_BASE + 3), &info->mcontext.lo2);
292 sys_ptrace(PTRACE_PEEKUSER, tid,
293 reinterpret_cast<void*>(DSP_BASE + 4), &info->mcontext.hi3);
294 sys_ptrace(PTRACE_PEEKUSER, tid,
295 reinterpret_cast<void*>(DSP_BASE + 5), &info->mcontext.lo3);
296 sys_ptrace(PTRACE_PEEKUSER, tid,
297 reinterpret_cast<void*>(DSP_CONTROL), &info->mcontext.dsp);
298 #endif
299
300 const uint8_t* stack_pointer;
301 #if defined(__i386)
302 my_memcpy(&stack_pointer, &info->regs.esp, sizeof(info->regs.esp));
303 #elif defined(__x86_64)
304 my_memcpy(&stack_pointer, &info->regs.rsp, sizeof(info->regs.rsp));
305 #elif defined(__ARM_EABI__)
306 my_memcpy(&stack_pointer, &info->regs.ARM_sp, sizeof(info->regs.ARM_sp));
307 #elif defined(__aarch64__)
308 my_memcpy(&stack_pointer, &info->regs.sp, sizeof(info->regs.sp));
309 #elif defined(__mips__)
310 stack_pointer =
311 reinterpret_cast<uint8_t*>(info->mcontext.gregs[MD_CONTEXT_MIPS_REG_SP]);
312 #elif defined(__riscv)
313 stack_pointer = reinterpret_cast<uint8_t*>(
314 info->mcontext.__gregs[MD_CONTEXT_RISCV_REG_SP]);
315 #else
316 # error "This code hasn't been ported to your platform yet."
317 #endif
318 info->stack_pointer = reinterpret_cast<uintptr_t>(stack_pointer);
319
320 return true;
321 }
322
IsPostMortem() const323 bool LinuxPtraceDumper::IsPostMortem() const {
324 return false;
325 }
326
ThreadsSuspend()327 bool LinuxPtraceDumper::ThreadsSuspend() {
328 if (threads_suspended_)
329 return true;
330 for (size_t i = 0; i < threads_.size(); ++i) {
331 if (!SuspendThread(threads_[i])) {
332 // If the thread either disappeared before we could attach to it, or if
333 // it was part of the seccomp sandbox's trusted code, it is OK to
334 // silently drop it from the minidump.
335 if (i < threads_.size() - 1) {
336 my_memmove(&threads_[i], &threads_[i + 1],
337 (threads_.size() - i - 1) * sizeof(threads_[i]));
338 }
339 threads_.resize(threads_.size() - 1);
340 --i;
341 }
342 }
343 threads_suspended_ = true;
344 return threads_.size() > 0;
345 }
346
ThreadsResume()347 bool LinuxPtraceDumper::ThreadsResume() {
348 if (!threads_suspended_)
349 return false;
350 bool good = true;
351 for (size_t i = 0; i < threads_.size(); ++i)
352 good &= ResumeThread(threads_[i]);
353 threads_suspended_ = false;
354 return good;
355 }
356
357 // Parse /proc/$pid/task to list all the threads of the process identified by
358 // pid.
EnumerateThreads()359 bool LinuxPtraceDumper::EnumerateThreads() {
360 char task_path[NAME_MAX];
361 if (!BuildProcPath(task_path, pid_, "task"))
362 return false;
363
364 const int fd = sys_open(task_path, O_RDONLY | O_DIRECTORY, 0);
365 if (fd < 0)
366 return false;
367 DirectoryReader* dir_reader = new(allocator_) DirectoryReader(fd);
368
369 // The directory may contain duplicate entries which we filter by assuming
370 // that they are consecutive.
371 int last_tid = -1;
372 const char* dent_name;
373 while (dir_reader->GetNextEntry(&dent_name)) {
374 if (my_strcmp(dent_name, ".") &&
375 my_strcmp(dent_name, "..")) {
376 int tid = 0;
377 if (my_strtoui(&tid, dent_name) &&
378 last_tid != tid) {
379 last_tid = tid;
380 threads_.push_back(tid);
381 }
382 }
383 dir_reader->PopEntry();
384 }
385
386 sys_close(fd);
387 return true;
388 }
389
390 } // namespace google_breakpad
391