blob: d752608d2b8c550405360d85a80beb4d54932222 [file] [log] [blame]
nealsidb0baafc2009-08-17 23:12:53 +00001// Copyright (c) 2009, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright
9// notice, this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above
11// copyright notice, this list of conditions and the following disclaimer
12// in the documentation and/or other materials provided with the
13// distribution.
14// * Neither the name of Google Inc. nor the names of its
15// contributors may be used to endorse or promote products derived from
16// this software without specific prior written permission.
17//
18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30// This code deals with the mechanics of getting information about a crashed
31// process. Since this code may run in a compromised address space, the same
32// rules apply as detailed at the top of minidump_writer.h: no libc calls and
33// use the alternative allocator.
34
35#include "client/linux/minidump_writer/linux_dumper.h"
36
37#include <assert.h>
38#include <limits.h>
39#include <stddef.h>
40#include <stdlib.h>
41#include <stdio.h>
42#include <string.h>
43
44#include <unistd.h>
ted.mielczarek0a5fc5d2009-12-23 17:09:27 +000045#include <elf.h>
nealsidb0baafc2009-08-17 23:12:53 +000046#include <errno.h>
47#include <fcntl.h>
ted.mielczarek0a5fc5d2009-12-23 17:09:27 +000048#include <link.h>
nealsidb0baafc2009-08-17 23:12:53 +000049
50#include <sys/types.h>
51#include <sys/ptrace.h>
52#include <sys/wait.h>
53
ted.mielczarek0a5fc5d2009-12-23 17:09:27 +000054#include <algorithm>
55
nealsidb0baafc2009-08-17 23:12:53 +000056#include "client/linux/minidump_writer/directory_reader.h"
57#include "client/linux/minidump_writer/line_reader.h"
ted.mielczarek0a5fc5d2009-12-23 17:09:27 +000058#include "common/linux/file_id.h"
nealsidb0baafc2009-08-17 23:12:53 +000059#include "common/linux/linux_libc_support.h"
60#include "common/linux/linux_syscall_support.h"
61
62// Suspend a thread by attaching to it.
63static bool SuspendThread(pid_t pid) {
64 // This may fail if the thread has just died or debugged.
65 errno = 0;
66 if (sys_ptrace(PTRACE_ATTACH, pid, NULL, NULL) != 0 &&
67 errno != 0) {
68 return false;
69 }
70 while (sys_waitpid(pid, NULL, __WALL) < 0) {
71 if (errno != EINTR) {
72 sys_ptrace(PTRACE_DETACH, pid, NULL, NULL);
73 return false;
74 }
75 }
76 return true;
77}
78
79// Resume a thread by detaching from it.
80static bool ResumeThread(pid_t pid) {
81 return sys_ptrace(PTRACE_DETACH, pid, NULL, NULL) >= 0;
82}
83
84namespace google_breakpad {
85
86LinuxDumper::LinuxDumper(int pid)
87 : pid_(pid),
88 threads_suspened_(false),
89 threads_(&allocator_, 8),
90 mappings_(&allocator_) {
91}
92
93bool LinuxDumper::Init() {
94 return EnumerateThreads(&threads_) &&
95 EnumerateMappings(&mappings_);
96}
97
98bool LinuxDumper::ThreadsSuspend() {
99 if (threads_suspened_)
100 return true;
101 bool good = true;
102 for (size_t i = 0; i < threads_.size(); ++i)
103 good &= SuspendThread(threads_[i]);
104 threads_suspened_ = true;
105 return good;
106}
107
108bool LinuxDumper::ThreadsResume() {
109 if (!threads_suspened_)
110 return false;
111 bool good = true;
112 for (size_t i = 0; i < threads_.size(); ++i)
113 good &= ResumeThread(threads_[i]);
114 threads_suspened_ = false;
115 return good;
116}
117
118void
119LinuxDumper::BuildProcPath(char* path, pid_t pid, const char* node) const {
120 assert(path);
121 if (!path) {
122 return;
123 }
124
125 path[0] = '\0';
126
127 const unsigned pid_len = my_int_len(pid);
128
129 assert(node);
130 if (!node) {
131 return;
132 }
133
134 size_t node_len = my_strlen(node);
135 assert(node_len < NAME_MAX);
136 if (node_len >= NAME_MAX) {
137 return;
138 }
139
140 assert(node_len > 0);
141 if (node_len == 0) {
142 return;
143 }
144
145 assert(pid > 0);
146 if (pid <= 0) {
147 return;
148 }
149
150 const size_t total_length = 6 + pid_len + 1 + node_len;
151
152 assert(total_length < NAME_MAX);
153 if (total_length >= NAME_MAX) {
154 return;
155 }
156
157 memcpy(path, "/proc/", 6);
158 my_itos(path + 6, pid, pid_len);
159 memcpy(path + 6 + pid_len, "/", 1);
160 memcpy(path + 6 + pid_len + 1, node, node_len);
161 memcpy(path + total_length, "\0", 1);
162}
163
ted.mielczarek0a5fc5d2009-12-23 17:09:27 +0000164bool
165LinuxDumper::ElfFileIdentifierForMapping(unsigned int mapping_id,
166 uint8_t identifier[sizeof(MDGUID)])
167{
168 assert(mapping_id < mappings_.size());
169 const MappingInfo* mapping = mappings_[mapping_id];
170 int fd = sys_open(mapping->name, O_RDONLY, 0);
171 if (fd < 0)
172 return false;
173 struct kernel_stat st;
174 if (sys_fstat(fd, &st) != 0) {
175 sys_close(fd);
176 return false;
177 }
178 void* base = sys_mmap2(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
179 sys_close(fd);
180 if (base == MAP_FAILED)
181 return false;
182
183 bool success = FileID::ElfFileIdentifierFromMappedFile(base, identifier);
184 sys_munmap(base, st.st_size);
185 return success;
186}
187
nealsidb0baafc2009-08-17 23:12:53 +0000188void*
189LinuxDumper::FindBeginningOfLinuxGateSharedLibrary(const pid_t pid) const {
190 char auxv_path[80];
191 BuildProcPath(auxv_path, pid, "auxv");
192
193 // If BuildProcPath errors out due to invalid input, we'll handle it when
194 // we try to sys_open the file.
195
196 // Find the AT_SYSINFO_EHDR entry for linux-gate.so
197 // See http://www.trilithium.com/johan/2005/08/linux-gate/ for more
198 // information.
199 int fd = sys_open(auxv_path, O_RDONLY, 0);
200 if (fd < 0) {
201 return NULL;
202 }
203
204 elf_aux_entry one_aux_entry;
205 while (sys_read(fd,
206 &one_aux_entry,
207 sizeof(elf_aux_entry)) == sizeof(elf_aux_entry) &&
208 one_aux_entry.a_type != AT_NULL) {
209 if (one_aux_entry.a_type == AT_SYSINFO_EHDR) {
210 close(fd);
211 return reinterpret_cast<void*>(one_aux_entry.a_un.a_val);
212 }
213 }
214 close(fd);
215 return NULL;
216}
217
218bool
219LinuxDumper::EnumerateMappings(wasteful_vector<MappingInfo*>* result) const {
220 char maps_path[80];
221 BuildProcPath(maps_path, pid_, "maps");
222
223 // linux_gate_loc is the beginning of the kernel's mapping of
224 // linux-gate.so in the process. It doesn't actually show up in the
225 // maps list as a filename, so we use the aux vector to find it's
226 // load location and special case it's entry when creating the list
227 // of mappings.
228 const void* linux_gate_loc;
229 linux_gate_loc = FindBeginningOfLinuxGateSharedLibrary(pid_);
230
231 const int fd = sys_open(maps_path, O_RDONLY, 0);
232 if (fd < 0)
233 return false;
234 LineReader* const line_reader = new(allocator_) LineReader(fd);
235
236 const char* line;
237 unsigned line_len;
238 while (line_reader->GetNextLine(&line, &line_len)) {
239 uintptr_t start_addr, end_addr, offset;
240
241 const char* i1 = my_read_hex_ptr(&start_addr, line);
242 if (*i1 == '-') {
243 const char* i2 = my_read_hex_ptr(&end_addr, i1 + 1);
244 if (*i2 == ' ') {
245 const char* i3 = my_read_hex_ptr(&offset, i2 + 6 /* skip ' rwxp ' */);
246 if (*i3 == ' ') {
247 MappingInfo* const module = new(allocator_) MappingInfo;
248 memset(module, 0, sizeof(MappingInfo));
249 module->start_addr = start_addr;
250 module->size = end_addr - start_addr;
251 module->offset = offset;
252 const char* name = NULL;
253 // Only copy name if the name is a valid path name, or if
254 // we've found the VDSO image
255 if ((name = my_strchr(line, '/')) != NULL) {
256 const unsigned l = my_strlen(name);
257 if (l < sizeof(module->name))
258 memcpy(module->name, name, l);
259 } else if (linux_gate_loc &&
260 reinterpret_cast<void*>(module->start_addr) ==
261 linux_gate_loc) {
262 memcpy(module->name,
263 kLinuxGateLibraryName,
264 my_strlen(kLinuxGateLibraryName));
265 module->offset = 0;
266 }
267 result->push_back(module);
268 }
269 }
270 }
271 line_reader->PopLine(line_len);
272 }
273
274 sys_close(fd);
275
276 return result->size() > 0;
277}
278
279// Parse /proc/$pid/task to list all the threads of the process identified by
280// pid.
281bool LinuxDumper::EnumerateThreads(wasteful_vector<pid_t>* result) const {
282 char task_path[80];
283 BuildProcPath(task_path, pid_, "task");
284
285 const int fd = sys_open(task_path, O_RDONLY | O_DIRECTORY, 0);
286 if (fd < 0)
287 return false;
288 DirectoryReader* dir_reader = new(allocator_) DirectoryReader(fd);
289
290 // The directory may contain duplicate entries which we filter by assuming
291 // that they are consecutive.
292 int last_tid = -1;
293 const char* dent_name;
294 while (dir_reader->GetNextEntry(&dent_name)) {
295 if (my_strcmp(dent_name, ".") &&
296 my_strcmp(dent_name, "..")) {
297 int tid = 0;
298 if (my_strtoui(&tid, dent_name) &&
299 last_tid != tid) {
300 last_tid = tid;
301 result->push_back(tid);
302 }
303 }
304 dir_reader->PopEntry();
305 }
306
307 sys_close(fd);
308 return true;
309}
310
311// Read thread info from /proc/$pid/status.
312// Fill out the |tgid|, |ppid| and |pid| members of |info|. If unavailible,
313// these members are set to -1. Returns true iff all three members are
314// availible.
315bool LinuxDumper::ThreadInfoGet(pid_t tid, ThreadInfo* info) {
316 assert(info != NULL);
317 char status_path[80];
318 BuildProcPath(status_path, tid, "status");
319
320 const int fd = open(status_path, O_RDONLY);
321 if (fd < 0)
322 return false;
323
324 LineReader* const line_reader = new(allocator_) LineReader(fd);
325 const char* line;
326 unsigned line_len;
327
328 info->ppid = info->tgid = -1;
329
330 while (line_reader->GetNextLine(&line, &line_len)) {
331 if (my_strncmp("Tgid:\t", line, 6) == 0) {
332 my_strtoui(&info->tgid, line + 6);
333 } else if (my_strncmp("PPid:\t", line, 6) == 0) {
334 my_strtoui(&info->ppid, line + 6);
335 }
336
337 line_reader->PopLine(line_len);
338 }
339
340 if (info->ppid == -1 || info->tgid == -1)
341 return false;
342
343 if (sys_ptrace(PTRACE_GETREGS, tid, NULL, &info->regs) == -1 ||
344 sys_ptrace(PTRACE_GETFPREGS, tid, NULL, &info->fpregs) == -1) {
345 return false;
346 }
347
nealsid096992f2009-12-01 21:35:52 +0000348#if defined(__i386)
nealsidb0baafc2009-08-17 23:12:53 +0000349 if (sys_ptrace(PTRACE_GETFPXREGS, tid, NULL, &info->fpxregs) == -1)
350 return false;
nealsid096992f2009-12-01 21:35:52 +0000351#endif
nealsidb0baafc2009-08-17 23:12:53 +0000352
nealsid096992f2009-12-01 21:35:52 +0000353#if defined(__i386) || defined(__x86_64)
nealsidb0baafc2009-08-17 23:12:53 +0000354 for (unsigned i = 0; i < ThreadInfo::kNumDebugRegisters; ++i) {
355 if (sys_ptrace(
356 PTRACE_PEEKUSER, tid,
357 reinterpret_cast<void*> (offsetof(struct user,
358 u_debugreg[0]) + i *
359 sizeof(debugreg_t)),
360 &info->dregs[i]) == -1) {
361 return false;
362 }
363 }
364#endif
365
366 const uint8_t* stack_pointer;
367#if defined(__i386)
368 memcpy(&stack_pointer, &info->regs.esp, sizeof(info->regs.esp));
369#elif defined(__x86_64)
370 memcpy(&stack_pointer, &info->regs.rsp, sizeof(info->regs.rsp));
371#else
372#error "This code hasn't been ported to your platform yet."
373#endif
374
375 if (!GetStackInfo(&info->stack, &info->stack_len,
376 (uintptr_t) stack_pointer))
377 return false;
378
379 return true;
380}
381
382// Get information about the stack, given the stack pointer. We don't try to
383// walk the stack since we might not have all the information needed to do
384// unwind. So we just grab, up to, 32k of stack.
385bool LinuxDumper::GetStackInfo(const void** stack, size_t* stack_len,
386 uintptr_t int_stack_pointer) {
387#if defined(__i386) || defined(__x86_64)
388 static const bool stack_grows_down = true;
389 static const uintptr_t page_size = 4096;
390#else
391#error "This code has not been ported to your platform yet."
392#endif
393 // Move the stack pointer to the bottom of the page that it's in.
394 uint8_t* const stack_pointer =
395 reinterpret_cast<uint8_t*>(int_stack_pointer & ~(page_size - 1));
396
397 // The number of bytes of stack which we try to capture.
nealsidbb618862009-12-10 19:15:44 +0000398 static ptrdiff_t kStackToCapture = 32 * 1024;
nealsidb0baafc2009-08-17 23:12:53 +0000399
400 const MappingInfo* mapping = FindMapping(stack_pointer);
401 if (!mapping)
402 return false;
403 if (stack_grows_down) {
404 const ptrdiff_t offset = stack_pointer - (uint8_t*) mapping->start_addr;
405 const ptrdiff_t distance_to_end =
406 static_cast<ptrdiff_t>(mapping->size) - offset;
407 *stack_len = distance_to_end > kStackToCapture ?
408 kStackToCapture : distance_to_end;
409 *stack = stack_pointer;
410 } else {
411 const ptrdiff_t offset = stack_pointer - (uint8_t*) mapping->start_addr;
412 *stack_len = offset > kStackToCapture ? kStackToCapture : offset;
413 *stack = stack_pointer - *stack_len;
414 }
415
416 return true;
417}
418
419// static
420void LinuxDumper::CopyFromProcess(void* dest, pid_t child, const void* src,
421 size_t length) {
422 unsigned long tmp;
423 size_t done = 0;
424 static const size_t word_size = sizeof(tmp);
425 uint8_t* const local = (uint8_t*) dest;
426 uint8_t* const remote = (uint8_t*) src;
427
428 while (done < length) {
429 const size_t l = length - done > word_size ? word_size : length - done;
430 if (sys_ptrace(PTRACE_PEEKDATA, child, remote + done, &tmp) == -1)
431 tmp = 0;
432 memcpy(local + done, &tmp, l);
433 done += l;
434 }
435}
436
437// Find the mapping which the given memory address falls in.
438const MappingInfo* LinuxDumper::FindMapping(const void* address) const {
439 const uintptr_t addr = (uintptr_t) address;
440
441 for (size_t i = 0; i < mappings_.size(); ++i) {
442 const uintptr_t start = static_cast<uintptr_t>(mappings_[i]->start_addr);
443 if (addr >= start && addr - start < mappings_[i]->size)
444 return mappings_[i];
445 }
446
447 return NULL;
448}
449
450} // namespace google_breakpad