1 // 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 // Converts a minidump file to a core file which gdb can read.
31 // Large parts lifted from the userspace core dumper:
32 //   http://code.google.com/p/google-coredumper/
33 //
34 // Usage: minidump-2-core [-v] 1234.dmp > core
35 
36 #include <elf.h>
37 #include <errno.h>
38 #include <link.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sys/user.h>
43 #include <unistd.h>
44 
45 #include <map>
46 #include <string>
47 #include <vector>
48 
49 #include "common/linux/memory_mapped_file.h"
50 #include "common/scoped_ptr.h"
51 #include "google_breakpad/common/minidump_format.h"
52 #include "third_party/lss/linux_syscall_support.h"
53 #include "tools/linux/md2core/minidump_memory_range.h"
54 
55 #if __WORDSIZE == 64
56   #define ELF_CLASS ELFCLASS64
57 #else
58   #define ELF_CLASS ELFCLASS32
59 #endif
60 #define Ehdr   ElfW(Ehdr)
61 #define Phdr   ElfW(Phdr)
62 #define Shdr   ElfW(Shdr)
63 #define Nhdr   ElfW(Nhdr)
64 #define auxv_t ElfW(auxv_t)
65 
66 
67 #if defined(__x86_64__)
68   #define ELF_ARCH  EM_X86_64
69 #elif defined(__i386__)
70   #define ELF_ARCH  EM_386
71 #elif defined(__arm__)
72   #define ELF_ARCH  EM_ARM
73 #elif defined(__mips__)
74   #define ELF_ARCH  EM_MIPS
75 #endif
76 
77 #if defined(__arm__)
78 // GLibc/ARM and Android/ARM both use 'user_regs' for the structure type
79 // containing core registers, while they use 'user_regs_struct' on other
80 // architectures. This file-local typedef simplifies the source code.
81 typedef user_regs user_regs_struct;
82 #endif
83 
84 using google_breakpad::MemoryMappedFile;
85 using google_breakpad::MinidumpMemoryRange;
86 
87 static const MDRVA kInvalidMDRVA = static_cast<MDRVA>(-1);
88 static bool verbose;
89 
usage(const char * argv0)90 static int usage(const char* argv0) {
91   fprintf(stderr, "Usage: %s [-v] <minidump file>\n", argv0);
92   return 1;
93 }
94 
95 // Write all of the given buffer, handling short writes and EINTR. Return true
96 // iff successful.
97 static bool
writea(int fd,const void * idata,size_t length)98 writea(int fd, const void* idata, size_t length) {
99   const uint8_t* data = (const uint8_t*) idata;
100 
101   size_t done = 0;
102   while (done < length) {
103     ssize_t r;
104     do {
105       r = write(fd, data + done, length - done);
106     } while (r == -1 && errno == EINTR);
107 
108     if (r < 1)
109       return false;
110     done += r;
111   }
112 
113   return true;
114 }
115 
116 /* Dynamically determines the byte sex of the system. Returns non-zero
117  * for big-endian machines.
118  */
sex()119 static inline int sex() {
120   int probe = 1;
121   return !*(char *)&probe;
122 }
123 
124 typedef struct elf_timeval {    /* Time value with microsecond resolution    */
125   long tv_sec;                  /* Seconds                                   */
126   long tv_usec;                 /* Microseconds                              */
127 } elf_timeval;
128 
129 typedef struct elf_siginfo {    /* Information about signal (unused)         */
130   int32_t si_signo;             /* Signal number                             */
131   int32_t si_code;              /* Extra code                                */
132   int32_t si_errno;             /* Errno                                     */
133 } elf_siginfo;
134 
135 typedef struct prstatus {       /* Information about thread; includes CPU reg*/
136   elf_siginfo    pr_info;       /* Info associated with signal               */
137   uint16_t       pr_cursig;     /* Current signal                            */
138   unsigned long  pr_sigpend;    /* Set of pending signals                    */
139   unsigned long  pr_sighold;    /* Set of held signals                       */
140   pid_t          pr_pid;        /* Process ID                                */
141   pid_t          pr_ppid;       /* Parent's process ID                       */
142   pid_t          pr_pgrp;       /* Group ID                                  */
143   pid_t          pr_sid;        /* Session ID                                */
144   elf_timeval    pr_utime;      /* User time                                 */
145   elf_timeval    pr_stime;      /* System time                               */
146   elf_timeval    pr_cutime;     /* Cumulative user time                      */
147   elf_timeval    pr_cstime;     /* Cumulative system time                    */
148   user_regs_struct pr_reg;      /* CPU registers                             */
149   uint32_t       pr_fpvalid;    /* True if math co-processor being used      */
150 } prstatus;
151 
152 typedef struct prpsinfo {       /* Information about process                 */
153   unsigned char  pr_state;      /* Numeric process state                     */
154   char           pr_sname;      /* Char for pr_state                         */
155   unsigned char  pr_zomb;       /* Zombie                                    */
156   signed char    pr_nice;       /* Nice val                                  */
157   unsigned long  pr_flag;       /* Flags                                     */
158 #if defined(__x86_64__) || defined(__mips__)
159   uint32_t       pr_uid;        /* User ID                                   */
160   uint32_t       pr_gid;        /* Group ID                                  */
161 #else
162   uint16_t       pr_uid;        /* User ID                                   */
163   uint16_t       pr_gid;        /* Group ID                                  */
164 #endif
165   pid_t          pr_pid;        /* Process ID                                */
166   pid_t          pr_ppid;       /* Parent's process ID                       */
167   pid_t          pr_pgrp;       /* Group ID                                  */
168   pid_t          pr_sid;        /* Session ID                                */
169   char           pr_fname[16];  /* Filename of executable                    */
170   char           pr_psargs[80]; /* Initial part of arg list                  */
171 } prpsinfo;
172 
173 // We parse the minidump file and keep the parsed information in this structure
174 struct CrashedProcess {
CrashedProcessCrashedProcess175   CrashedProcess()
176       : crashing_tid(-1),
177         auxv(NULL),
178         auxv_length(0) {
179     memset(&prps, 0, sizeof(prps));
180     prps.pr_sname = 'R';
181     memset(&debug, 0, sizeof(debug));
182   }
183 
184   struct Mapping {
MappingCrashedProcess::Mapping185     Mapping()
186       : permissions(0xFFFFFFFF),
187         start_address(0),
188         end_address(0),
189         offset(0) {
190     }
191 
192     uint32_t permissions;
193     uint64_t start_address, end_address, offset;
194     std::string filename;
195     std::string data;
196   };
197   std::map<uint64_t, Mapping> mappings;
198 
199   pid_t crashing_tid;
200   int fatal_signal;
201 
202   struct Thread {
203     pid_t tid;
204     user_regs_struct regs;
205 #if defined(__i386__) || defined(__x86_64__) || defined(__mips__)
206     user_fpregs_struct fpregs;
207 #endif
208 #if defined(__i386__)
209     user_fpxregs_struct fpxregs;
210 #endif
211     uintptr_t stack_addr;
212     const uint8_t* stack;
213     size_t stack_length;
214   };
215   std::vector<Thread> threads;
216 
217   const uint8_t* auxv;
218   size_t auxv_length;
219 
220   prpsinfo prps;
221 
222   std::map<uintptr_t, std::string> signatures;
223 
224   std::string dynamic_data;
225   MDRawDebug debug;
226   std::vector<MDRawLinkMap> link_map;
227 };
228 
229 #if defined(__i386__)
230 static uint32_t
U32(const uint8_t * data)231 U32(const uint8_t* data) {
232   uint32_t v;
233   memcpy(&v, data, sizeof(v));
234   return v;
235 }
236 
237 static uint16_t
U16(const uint8_t * data)238 U16(const uint8_t* data) {
239   uint16_t v;
240   memcpy(&v, data, sizeof(v));
241   return v;
242 }
243 
244 static void
ParseThreadRegisters(CrashedProcess::Thread * thread,const MinidumpMemoryRange & range)245 ParseThreadRegisters(CrashedProcess::Thread* thread,
246                      const MinidumpMemoryRange& range) {
247   const MDRawContextX86* rawregs = range.GetData<MDRawContextX86>(0);
248 
249   thread->regs.ebx = rawregs->ebx;
250   thread->regs.ecx = rawregs->ecx;
251   thread->regs.edx = rawregs->edx;
252   thread->regs.esi = rawregs->esi;
253   thread->regs.edi = rawregs->edi;
254   thread->regs.ebp = rawregs->ebp;
255   thread->regs.eax = rawregs->eax;
256   thread->regs.xds = rawregs->ds;
257   thread->regs.xes = rawregs->es;
258   thread->regs.xfs = rawregs->fs;
259   thread->regs.xgs = rawregs->gs;
260   thread->regs.orig_eax = rawregs->eax;
261   thread->regs.eip = rawregs->eip;
262   thread->regs.xcs = rawregs->cs;
263   thread->regs.eflags = rawregs->eflags;
264   thread->regs.esp = rawregs->esp;
265   thread->regs.xss = rawregs->ss;
266 
267   thread->fpregs.cwd = rawregs->float_save.control_word;
268   thread->fpregs.swd = rawregs->float_save.status_word;
269   thread->fpregs.twd = rawregs->float_save.tag_word;
270   thread->fpregs.fip = rawregs->float_save.error_offset;
271   thread->fpregs.fcs = rawregs->float_save.error_selector;
272   thread->fpregs.foo = rawregs->float_save.data_offset;
273   thread->fpregs.fos = rawregs->float_save.data_selector;
274   memcpy(thread->fpregs.st_space, rawregs->float_save.register_area,
275          10 * 8);
276 
277   thread->fpxregs.cwd = rawregs->float_save.control_word;
278   thread->fpxregs.swd = rawregs->float_save.status_word;
279   thread->fpxregs.twd = rawregs->float_save.tag_word;
280   thread->fpxregs.fop = U16(rawregs->extended_registers + 6);
281   thread->fpxregs.fip = U16(rawregs->extended_registers + 8);
282   thread->fpxregs.fcs = U16(rawregs->extended_registers + 12);
283   thread->fpxregs.foo = U16(rawregs->extended_registers + 16);
284   thread->fpxregs.fos = U16(rawregs->extended_registers + 20);
285   thread->fpxregs.mxcsr = U32(rawregs->extended_registers + 24);
286   memcpy(thread->fpxregs.st_space, rawregs->extended_registers + 32, 128);
287   memcpy(thread->fpxregs.xmm_space, rawregs->extended_registers + 160, 128);
288 }
289 #elif defined(__x86_64__)
290 static void
ParseThreadRegisters(CrashedProcess::Thread * thread,const MinidumpMemoryRange & range)291 ParseThreadRegisters(CrashedProcess::Thread* thread,
292                      const MinidumpMemoryRange& range) {
293   const MDRawContextAMD64* rawregs = range.GetData<MDRawContextAMD64>(0);
294 
295   thread->regs.r15 = rawregs->r15;
296   thread->regs.r14 = rawregs->r14;
297   thread->regs.r13 = rawregs->r13;
298   thread->regs.r12 = rawregs->r12;
299   thread->regs.rbp = rawregs->rbp;
300   thread->regs.rbx = rawregs->rbx;
301   thread->regs.r11 = rawregs->r11;
302   thread->regs.r10 = rawregs->r10;
303   thread->regs.r9 = rawregs->r9;
304   thread->regs.r8 = rawregs->r8;
305   thread->regs.rax = rawregs->rax;
306   thread->regs.rcx = rawregs->rcx;
307   thread->regs.rdx = rawregs->rdx;
308   thread->regs.rsi = rawregs->rsi;
309   thread->regs.rdi = rawregs->rdi;
310   thread->regs.orig_rax = rawregs->rax;
311   thread->regs.rip = rawregs->rip;
312   thread->regs.cs  = rawregs->cs;
313   thread->regs.eflags = rawregs->eflags;
314   thread->regs.rsp = rawregs->rsp;
315   thread->regs.ss = rawregs->ss;
316   thread->regs.fs_base = 0;
317   thread->regs.gs_base = 0;
318   thread->regs.ds = rawregs->ds;
319   thread->regs.es = rawregs->es;
320   thread->regs.fs = rawregs->fs;
321   thread->regs.gs = rawregs->gs;
322 
323   thread->fpregs.cwd = rawregs->flt_save.control_word;
324   thread->fpregs.swd = rawregs->flt_save.status_word;
325   thread->fpregs.ftw = rawregs->flt_save.tag_word;
326   thread->fpregs.fop = rawregs->flt_save.error_opcode;
327   thread->fpregs.rip = rawregs->flt_save.error_offset;
328   thread->fpregs.rdp = rawregs->flt_save.data_offset;
329   thread->fpregs.mxcsr = rawregs->flt_save.mx_csr;
330   thread->fpregs.mxcr_mask = rawregs->flt_save.mx_csr_mask;
331   memcpy(thread->fpregs.st_space, rawregs->flt_save.float_registers, 8 * 16);
332   memcpy(thread->fpregs.xmm_space, rawregs->flt_save.xmm_registers, 16 * 16);
333 }
334 #elif defined(__arm__)
335 static void
ParseThreadRegisters(CrashedProcess::Thread * thread,const MinidumpMemoryRange & range)336 ParseThreadRegisters(CrashedProcess::Thread* thread,
337                      const MinidumpMemoryRange& range) {
338   const MDRawContextARM* rawregs = range.GetData<MDRawContextARM>(0);
339 
340   thread->regs.uregs[0] = rawregs->iregs[0];
341   thread->regs.uregs[1] = rawregs->iregs[1];
342   thread->regs.uregs[2] = rawregs->iregs[2];
343   thread->regs.uregs[3] = rawregs->iregs[3];
344   thread->regs.uregs[4] = rawregs->iregs[4];
345   thread->regs.uregs[5] = rawregs->iregs[5];
346   thread->regs.uregs[6] = rawregs->iregs[6];
347   thread->regs.uregs[7] = rawregs->iregs[7];
348   thread->regs.uregs[8] = rawregs->iregs[8];
349   thread->regs.uregs[9] = rawregs->iregs[9];
350   thread->regs.uregs[10] = rawregs->iregs[10];
351   thread->regs.uregs[11] = rawregs->iregs[11];
352   thread->regs.uregs[12] = rawregs->iregs[12];
353   thread->regs.uregs[13] = rawregs->iregs[13];
354   thread->regs.uregs[14] = rawregs->iregs[14];
355   thread->regs.uregs[15] = rawregs->iregs[15];
356 
357   thread->regs.uregs[16] = rawregs->cpsr;
358   thread->regs.uregs[17] = 0;  // what is ORIG_r0 exactly?
359 }
360 #elif defined(__mips__)
361 static void
ParseThreadRegisters(CrashedProcess::Thread * thread,const MinidumpMemoryRange & range)362 ParseThreadRegisters(CrashedProcess::Thread* thread,
363                      const MinidumpMemoryRange& range) {
364   const MDRawContextMIPS* rawregs = range.GetData<MDRawContextMIPS>(0);
365 
366   for (int i = 0; i < MD_CONTEXT_MIPS_GPR_COUNT; ++i)
367     thread->regs.regs[i] = rawregs->iregs[i];
368 
369   thread->regs.lo = rawregs->mdlo;
370   thread->regs.hi = rawregs->mdhi;
371   thread->regs.epc = rawregs->epc;
372   thread->regs.badvaddr = rawregs->badvaddr;
373   thread->regs.status = rawregs->status;
374   thread->regs.cause = rawregs->cause;
375 
376   for (int i = 0; i < MD_FLOATINGSAVEAREA_MIPS_FPR_COUNT; ++i)
377     thread->fpregs.regs[i] = rawregs->float_save.regs[i];
378 
379   thread->fpregs.fpcsr = rawregs->float_save.fpcsr;
380   thread->fpregs.fir = rawregs->float_save.fir;
381 }
382 #else
383 #error "This code has not been ported to your platform yet"
384 #endif
385 
386 static void
ParseThreadList(CrashedProcess * crashinfo,const MinidumpMemoryRange & range,const MinidumpMemoryRange & full_file)387 ParseThreadList(CrashedProcess* crashinfo, const MinidumpMemoryRange& range,
388                 const MinidumpMemoryRange& full_file) {
389   const uint32_t num_threads = *range.GetData<uint32_t>(0);
390   if (verbose) {
391     fprintf(stderr,
392             "MD_THREAD_LIST_STREAM:\n"
393             "Found %d threads\n"
394             "\n\n",
395             num_threads);
396   }
397   for (unsigned i = 0; i < num_threads; ++i) {
398     CrashedProcess::Thread thread;
399     memset(&thread, 0, sizeof(thread));
400     const MDRawThread* rawthread =
401         range.GetArrayElement<MDRawThread>(sizeof(uint32_t), i);
402     thread.tid = rawthread->thread_id;
403     thread.stack_addr = rawthread->stack.start_of_memory_range;
404     MinidumpMemoryRange stack_range =
405         full_file.Subrange(rawthread->stack.memory);
406     thread.stack = stack_range.data();
407     thread.stack_length = rawthread->stack.memory.data_size;
408 
409     ParseThreadRegisters(&thread,
410                          full_file.Subrange(rawthread->thread_context));
411 
412     crashinfo->threads.push_back(thread);
413   }
414 }
415 
416 static void
ParseSystemInfo(CrashedProcess * crashinfo,const MinidumpMemoryRange & range,const MinidumpMemoryRange & full_file)417 ParseSystemInfo(CrashedProcess* crashinfo, const MinidumpMemoryRange& range,
418                 const MinidumpMemoryRange& full_file) {
419   const MDRawSystemInfo* sysinfo = range.GetData<MDRawSystemInfo>(0);
420   if (!sysinfo) {
421     fprintf(stderr, "Failed to access MD_SYSTEM_INFO_STREAM\n");
422     _exit(1);
423   }
424 #if defined(__i386__)
425   if (sysinfo->processor_architecture != MD_CPU_ARCHITECTURE_X86) {
426     fprintf(stderr,
427             "This version of minidump-2-core only supports x86 (32bit)%s.\n",
428             sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_AMD64 ?
429             ",\nbut the minidump file is from a 64bit machine" : "");
430     _exit(1);
431   }
432 #elif defined(__x86_64__)
433   if (sysinfo->processor_architecture != MD_CPU_ARCHITECTURE_AMD64) {
434     fprintf(stderr,
435             "This version of minidump-2-core only supports x86 (64bit)%s.\n",
436             sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_X86 ?
437             ",\nbut the minidump file is from a 32bit machine" : "");
438     _exit(1);
439   }
440 #elif defined(__arm__)
441   if (sysinfo->processor_architecture != MD_CPU_ARCHITECTURE_ARM) {
442     fprintf(stderr,
443             "This version of minidump-2-core only supports ARM (32bit).\n");
444     _exit(1);
445   }
446 #elif defined(__mips__)
447   if (sysinfo->processor_architecture != MD_CPU_ARCHITECTURE_MIPS) {
448     fprintf(stderr,
449             "This version of minidump-2-core only supports mips (32bit).\n");
450     _exit(1);
451   }
452 #else
453 #error "This code has not been ported to your platform yet"
454 #endif
455   if (!strstr(full_file.GetAsciiMDString(sysinfo->csd_version_rva).c_str(),
456               "Linux") &&
457       sysinfo->platform_id != MD_OS_NACL) {
458     fprintf(stderr, "This minidump was not generated by Linux or NaCl.\n");
459     _exit(1);
460   }
461 
462   if (verbose) {
463     fprintf(stderr,
464             "MD_SYSTEM_INFO_STREAM:\n"
465             "Architecture: %s\n"
466             "Number of processors: %d\n"
467             "Processor level: %d\n"
468             "Processor model: %d\n"
469             "Processor stepping: %d\n",
470             sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_X86
471             ? "i386"
472             : sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_AMD64
473             ? "x86-64"
474             : sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_ARM
475             ? "ARM"
476             : sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_MIPS
477             ? "MIPS"
478             : "???",
479             sysinfo->number_of_processors,
480             sysinfo->processor_level,
481             sysinfo->processor_revision >> 8,
482             sysinfo->processor_revision & 0xFF);
483     if (sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_X86 ||
484         sysinfo->processor_architecture == MD_CPU_ARCHITECTURE_AMD64) {
485       fputs("Vendor id: ", stderr);
486       const char *nul =
487         (const char *)memchr(sysinfo->cpu.x86_cpu_info.vendor_id, 0,
488                              sizeof(sysinfo->cpu.x86_cpu_info.vendor_id));
489       fwrite(sysinfo->cpu.x86_cpu_info.vendor_id,
490              nul ? nul - (const char *)&sysinfo->cpu.x86_cpu_info.vendor_id[0]
491              : sizeof(sysinfo->cpu.x86_cpu_info.vendor_id), 1, stderr);
492       fputs("\n", stderr);
493     }
494     fprintf(stderr, "OS: %s\n",
495             full_file.GetAsciiMDString(sysinfo->csd_version_rva).c_str());
496     fputs("\n\n", stderr);
497   }
498 }
499 
500 static void
ParseCPUInfo(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)501 ParseCPUInfo(CrashedProcess* crashinfo, const MinidumpMemoryRange& range) {
502   if (verbose) {
503     fputs("MD_LINUX_CPU_INFO:\n", stderr);
504     fwrite(range.data(), range.length(), 1, stderr);
505     fputs("\n\n\n", stderr);
506   }
507 }
508 
509 static void
ParseProcessStatus(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)510 ParseProcessStatus(CrashedProcess* crashinfo,
511                    const MinidumpMemoryRange& range) {
512   if (verbose) {
513     fputs("MD_LINUX_PROC_STATUS:\n", stderr);
514     fwrite(range.data(), range.length(), 1, stderr);
515     fputs("\n\n", stderr);
516   }
517 }
518 
519 static void
ParseLSBRelease(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)520 ParseLSBRelease(CrashedProcess* crashinfo, const MinidumpMemoryRange& range) {
521   if (verbose) {
522     fputs("MD_LINUX_LSB_RELEASE:\n", stderr);
523     fwrite(range.data(), range.length(), 1, stderr);
524     fputs("\n\n", stderr);
525   }
526 }
527 
528 static void
ParseMaps(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)529 ParseMaps(CrashedProcess* crashinfo, const MinidumpMemoryRange& range) {
530   if (verbose) {
531     fputs("MD_LINUX_MAPS:\n", stderr);
532     fwrite(range.data(), range.length(), 1, stderr);
533   }
534   for (const uint8_t* ptr = range.data();
535        ptr < range.data() + range.length();) {
536     const uint8_t* eol = (uint8_t*)memchr(ptr, '\n',
537                                        range.data() + range.length() - ptr);
538     std::string line((const char*)ptr,
539                      eol ? eol - ptr : range.data() + range.length() - ptr);
540     ptr = eol ? eol + 1 : range.data() + range.length();
541     unsigned long long start, stop, offset;
542     char* permissions = NULL;
543     char* filename = NULL;
544     sscanf(line.c_str(), "%llx-%llx %m[-rwxp] %llx %*[:0-9a-f] %*d %ms",
545            &start, &stop, &permissions, &offset, &filename);
546     if (filename && *filename == '/') {
547       CrashedProcess::Mapping mapping;
548       mapping.permissions = 0;
549       if (strchr(permissions, 'r')) {
550         mapping.permissions |= PF_R;
551       }
552       if (strchr(permissions, 'w')) {
553         mapping.permissions |= PF_W;
554       }
555       if (strchr(permissions, 'x')) {
556         mapping.permissions |= PF_X;
557       }
558       mapping.start_address = start;
559       mapping.end_address = stop;
560       mapping.offset = offset;
561       if (filename) {
562         mapping.filename = filename;
563       }
564       crashinfo->mappings[mapping.start_address] = mapping;
565     }
566     free(permissions);
567     free(filename);
568   }
569   if (verbose) {
570     fputs("\n\n\n", stderr);
571   }
572 }
573 
574 static void
ParseEnvironment(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)575 ParseEnvironment(CrashedProcess* crashinfo, const MinidumpMemoryRange& range) {
576   if (verbose) {
577     fputs("MD_LINUX_ENVIRON:\n", stderr);
578     char *env = new char[range.length()];
579     memcpy(env, range.data(), range.length());
580     int nul_count = 0;
581     for (char *ptr = env;;) {
582       ptr = (char *)memchr(ptr, '\000', range.length() - (ptr - env));
583       if (!ptr) {
584         break;
585       }
586       if (ptr > env && ptr[-1] == '\n') {
587         if (++nul_count > 5) {
588           // Some versions of Chrome try to rewrite the process' command line
589           // in a way that causes the environment to be corrupted. Afterwards,
590           // part of the environment will contain the trailing bit of the
591           // command line. The rest of the environment will be filled with
592           // NUL bytes.
593           // We detect this corruption by counting the number of consecutive
594           // NUL bytes. Normally, we would not expect any consecutive NUL
595           // bytes. But we are conservative and only suppress printing of
596           // the environment if we see at least five consecutive NULs.
597           fputs("Environment has been corrupted; no data available", stderr);
598           goto env_corrupted;
599         }
600       } else {
601         nul_count = 0;
602       }
603       *ptr = '\n';
604     }
605     fwrite(env, range.length(), 1, stderr);
606   env_corrupted:
607     delete[] env;
608     fputs("\n\n\n", stderr);
609   }
610 }
611 
612 static void
ParseAuxVector(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)613 ParseAuxVector(CrashedProcess* crashinfo, const MinidumpMemoryRange& range) {
614   // Some versions of Chrome erroneously used the MD_LINUX_AUXV stream value
615   // when dumping /proc/$x/maps
616   if (range.length() > 17) {
617     // The AUXV vector contains binary data, whereas the maps always begin
618     // with an 8+ digit hex address followed by a hyphen and another 8+ digit
619     // address.
620     char addresses[18];
621     memcpy(addresses, range.data(), 17);
622     addresses[17] = '\000';
623     if (strspn(addresses, "0123456789abcdef-") == 17) {
624       ParseMaps(crashinfo, range);
625       return;
626     }
627   }
628 
629   crashinfo->auxv = range.data();
630   crashinfo->auxv_length = range.length();
631 }
632 
633 static void
ParseCmdLine(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)634 ParseCmdLine(CrashedProcess* crashinfo, const MinidumpMemoryRange& range) {
635   // The command line is supposed to use NUL bytes to separate arguments.
636   // As Chrome rewrites its own command line and (incorrectly) substitutes
637   // spaces, this is often not the case in our minidump files.
638   const char* cmdline = (const char*) range.data();
639   if (verbose) {
640     fputs("MD_LINUX_CMD_LINE:\n", stderr);
641     unsigned i = 0;
642     for (; i < range.length() && cmdline[i] && cmdline[i] != ' '; ++i) { }
643     fputs("argv[0] = \"", stderr);
644     fwrite(cmdline, i, 1, stderr);
645     fputs("\"\n", stderr);
646     for (unsigned j = ++i, argc = 1; j < range.length(); ++j) {
647       if (!cmdline[j] || cmdline[j] == ' ') {
648         fprintf(stderr, "argv[%d] = \"", argc++);
649         fwrite(cmdline + i, j - i, 1, stderr);
650         fputs("\"\n", stderr);
651         i = j + 1;
652       }
653     }
654     fputs("\n\n", stderr);
655   }
656 
657   const char *binary_name = cmdline;
658   for (size_t i = 0; i < range.length(); ++i) {
659     if (cmdline[i] == '/') {
660       binary_name = cmdline + i + 1;
661     } else if (cmdline[i] == 0 || cmdline[i] == ' ') {
662       static const size_t fname_len = sizeof(crashinfo->prps.pr_fname) - 1;
663       static const size_t args_len = sizeof(crashinfo->prps.pr_psargs) - 1;
664       memset(crashinfo->prps.pr_fname, 0, fname_len + 1);
665       memset(crashinfo->prps.pr_psargs, 0, args_len + 1);
666       unsigned len = cmdline + i - binary_name;
667       memcpy(crashinfo->prps.pr_fname, binary_name,
668                len > fname_len ? fname_len : len);
669 
670       len = range.length() > args_len ? args_len : range.length();
671       memcpy(crashinfo->prps.pr_psargs, cmdline, len);
672       for (unsigned j = 0; j < len; ++j) {
673         if (crashinfo->prps.pr_psargs[j] == 0)
674           crashinfo->prps.pr_psargs[j] = ' ';
675       }
676       break;
677     }
678   }
679 }
680 
681 static void
ParseDSODebugInfo(CrashedProcess * crashinfo,const MinidumpMemoryRange & range,const MinidumpMemoryRange & full_file)682 ParseDSODebugInfo(CrashedProcess* crashinfo, const MinidumpMemoryRange& range,
683                   const MinidumpMemoryRange& full_file) {
684   const MDRawDebug* debug = range.GetData<MDRawDebug>(0);
685   if (!debug) {
686     return;
687   }
688   if (verbose) {
689     fprintf(stderr,
690             "MD_LINUX_DSO_DEBUG:\n"
691             "Version: %d\n"
692             "Number of DSOs: %d\n"
693             "Brk handler: %p\n"
694             "Dynamic loader at: %p\n"
695             "_DYNAMIC: %p\n",
696             debug->version,
697             debug->dso_count,
698             debug->brk,
699             debug->ldbase,
700             debug->dynamic);
701   }
702   crashinfo->debug = *debug;
703   if (range.length() > sizeof(MDRawDebug)) {
704     char* dynamic_data = (char*)range.data() + sizeof(MDRawDebug);
705     crashinfo->dynamic_data.assign(dynamic_data,
706                                    range.length() - sizeof(MDRawDebug));
707   }
708   if (debug->map != kInvalidMDRVA) {
709     for (unsigned int i = 0; i < debug->dso_count; ++i) {
710       const MDRawLinkMap* link_map =
711           full_file.GetArrayElement<MDRawLinkMap>(debug->map, i);
712       if (link_map) {
713         if (verbose) {
714           fprintf(stderr,
715                   "#%03d: %p, %p, \"%s\"\n",
716                   i, link_map->addr, link_map->ld,
717                   full_file.GetAsciiMDString(link_map->name).c_str());
718         }
719         crashinfo->link_map.push_back(*link_map);
720       }
721     }
722   }
723   if (verbose) {
724     fputs("\n\n", stderr);
725   }
726 }
727 
728 static void
ParseExceptionStream(CrashedProcess * crashinfo,const MinidumpMemoryRange & range)729 ParseExceptionStream(CrashedProcess* crashinfo,
730                      const MinidumpMemoryRange& range) {
731   const MDRawExceptionStream* exp = range.GetData<MDRawExceptionStream>(0);
732   crashinfo->crashing_tid = exp->thread_id;
733   crashinfo->fatal_signal = (int) exp->exception_record.exception_code;
734 }
735 
736 static bool
WriteThread(const CrashedProcess::Thread & thread,int fatal_signal)737 WriteThread(const CrashedProcess::Thread& thread, int fatal_signal) {
738   struct prstatus pr;
739   memset(&pr, 0, sizeof(pr));
740 
741   pr.pr_info.si_signo = fatal_signal;
742   pr.pr_cursig = fatal_signal;
743   pr.pr_pid = thread.tid;
744   memcpy(&pr.pr_reg, &thread.regs, sizeof(user_regs_struct));
745 
746   Nhdr nhdr;
747   memset(&nhdr, 0, sizeof(nhdr));
748   nhdr.n_namesz = 5;
749   nhdr.n_descsz = sizeof(struct prstatus);
750   nhdr.n_type = NT_PRSTATUS;
751   if (!writea(1, &nhdr, sizeof(nhdr)) ||
752       !writea(1, "CORE\0\0\0\0", 8) ||
753       !writea(1, &pr, sizeof(struct prstatus))) {
754     return false;
755   }
756 
757 #if defined(__i386__) || defined(__x86_64__)
758   nhdr.n_descsz = sizeof(user_fpregs_struct);
759   nhdr.n_type = NT_FPREGSET;
760   if (!writea(1, &nhdr, sizeof(nhdr)) ||
761       !writea(1, "CORE\0\0\0\0", 8) ||
762       !writea(1, &thread.fpregs, sizeof(user_fpregs_struct))) {
763     return false;
764   }
765 #endif
766 
767 #if defined(__i386__)
768   nhdr.n_descsz = sizeof(user_fpxregs_struct);
769   nhdr.n_type = NT_PRXFPREG;
770   if (!writea(1, &nhdr, sizeof(nhdr)) ||
771       !writea(1, "LINUX\0\0\0", 8) ||
772       !writea(1, &thread.fpxregs, sizeof(user_fpxregs_struct))) {
773     return false;
774   }
775 #endif
776 
777   return true;
778 }
779 
780 static void
ParseModuleStream(CrashedProcess * crashinfo,const MinidumpMemoryRange & range,const MinidumpMemoryRange & full_file)781 ParseModuleStream(CrashedProcess* crashinfo, const MinidumpMemoryRange& range,
782                   const MinidumpMemoryRange& full_file) {
783   if (verbose) {
784     fputs("MD_MODULE_LIST_STREAM:\n", stderr);
785   }
786   const uint32_t num_mappings = *range.GetData<uint32_t>(0);
787   for (unsigned i = 0; i < num_mappings; ++i) {
788     CrashedProcess::Mapping mapping;
789     const MDRawModule* rawmodule = reinterpret_cast<const MDRawModule*>(
790         range.GetArrayElement(sizeof(uint32_t), MD_MODULE_SIZE, i));
791     mapping.start_address = rawmodule->base_of_image;
792     mapping.end_address = rawmodule->size_of_image + rawmodule->base_of_image;
793 
794     if (crashinfo->mappings.find(mapping.start_address) ==
795         crashinfo->mappings.end()) {
796       // We prefer data from MD_LINUX_MAPS over MD_MODULE_LIST_STREAM, as
797       // the former is a strict superset of the latter.
798       crashinfo->mappings[mapping.start_address] = mapping;
799     }
800 
801     const MDCVInfoPDB70* record = reinterpret_cast<const MDCVInfoPDB70*>(
802         full_file.GetData(rawmodule->cv_record.rva, MDCVInfoPDB70_minsize));
803     char guid[40];
804     sprintf(guid, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
805             record->signature.data1, record->signature.data2,
806             record->signature.data3,
807             record->signature.data4[0], record->signature.data4[1],
808             record->signature.data4[2], record->signature.data4[3],
809             record->signature.data4[4], record->signature.data4[5],
810             record->signature.data4[6], record->signature.data4[7]);
811     std::string filename =
812         full_file.GetAsciiMDString(rawmodule->module_name_rva);
813     size_t slash = filename.find_last_of('/');
814     std::string basename = slash == std::string::npos ?
815       filename : filename.substr(slash + 1);
816     if (strcmp(guid, "00000000-0000-0000-0000-000000000000")) {
817       crashinfo->signatures[rawmodule->base_of_image] =
818         std::string("/var/lib/breakpad/") + guid + "-" + basename;
819     }
820 
821     if (verbose) {
822       fprintf(stderr, "0x%08llX-0x%08llX, ChkSum: 0x%08X, GUID: %s, \"%s\"\n",
823               (unsigned long long)rawmodule->base_of_image,
824               (unsigned long long)rawmodule->base_of_image +
825               rawmodule->size_of_image,
826               rawmodule->checksum, guid, filename.c_str());
827     }
828   }
829   if (verbose) {
830     fputs("\n\n", stderr);
831   }
832 }
833 
834 static void
AddDataToMapping(CrashedProcess * crashinfo,const std::string & data,uintptr_t addr)835 AddDataToMapping(CrashedProcess* crashinfo, const std::string& data,
836                  uintptr_t addr) {
837   for (std::map<uint64_t, CrashedProcess::Mapping>::iterator
838          iter = crashinfo->mappings.begin();
839        iter != crashinfo->mappings.end();
840        ++iter) {
841     if (addr >= iter->second.start_address &&
842         addr < iter->second.end_address) {
843       CrashedProcess::Mapping mapping = iter->second;
844       if ((addr & ~4095) != iter->second.start_address) {
845         // If there are memory pages in the mapping prior to where the
846         // data starts, truncate the existing mapping so that it ends with
847         // the page immediately preceding the data region.
848         iter->second.end_address = addr & ~4095;
849         if (!mapping.filename.empty()) {
850           // "mapping" is a copy of "iter->second". We are splitting the
851           // existing mapping into two separate ones when we write the data
852           // to the core file. The first one does not have any associated
853           // data in the core file, the second one is backed by data that is
854           // included with the core file.
855           // If this mapping wasn't supposed to be anonymous, then we also
856           // have to update the file offset upon splitting the mapping.
857           mapping.offset += iter->second.end_address -
858             iter->second.start_address;
859         }
860       }
861       // Create a new mapping that contains the data contents. We often
862       // limit the amount of data that is actually written to the core
863       // file. But it is OK if the mapping itself extends past the end of
864       // the data.
865       mapping.start_address = addr & ~4095;
866       mapping.data.assign(addr & 4095, 0).append(data);
867       mapping.data.append(-mapping.data.size() & 4095, 0);
868       crashinfo->mappings[mapping.start_address] = mapping;
869       return;
870     }
871   }
872   // Didn't find a suitable existing mapping for the data. Create a new one.
873   CrashedProcess::Mapping mapping;
874   mapping.permissions = PF_R | PF_W;
875   mapping.start_address = addr & ~4095;
876   mapping.end_address =
877     (addr + data.size() + 4095) & ~4095;
878   mapping.data.assign(addr & 4095, 0).append(data);
879   mapping.data.append(-mapping.data.size() & 4095, 0);
880   crashinfo->mappings[mapping.start_address] = mapping;
881 }
882 
883 static void
AugmentMappings(CrashedProcess * crashinfo,const MinidumpMemoryRange & full_file)884 AugmentMappings(CrashedProcess* crashinfo,
885                 const MinidumpMemoryRange& full_file) {
886   // For each thread, find the memory mapping that matches the thread's stack.
887   // Then adjust the mapping to include the stack dump.
888   for (unsigned i = 0; i < crashinfo->threads.size(); ++i) {
889     const CrashedProcess::Thread& thread = crashinfo->threads[i];
890     AddDataToMapping(crashinfo,
891                      std::string((char *)thread.stack, thread.stack_length),
892                      thread.stack_addr);
893   }
894 
895   // Create a new link map with information about DSOs. We move this map to
896   // the beginning of the address space, as this area should always be
897   // available.
898   static const uintptr_t start_addr = 4096;
899   std::string data;
900   struct r_debug debug = { 0 };
901   debug.r_version = crashinfo->debug.version;
902   debug.r_brk = (ElfW(Addr))crashinfo->debug.brk;
903   debug.r_state = r_debug::RT_CONSISTENT;
904   debug.r_ldbase = (ElfW(Addr))crashinfo->debug.ldbase;
905   debug.r_map = crashinfo->debug.dso_count > 0 ?
906     (struct link_map*)(start_addr + sizeof(debug)) : 0;
907   data.append((char*)&debug, sizeof(debug));
908 
909   struct link_map* prev = 0;
910   for (std::vector<MDRawLinkMap>::iterator iter = crashinfo->link_map.begin();
911        iter != crashinfo->link_map.end();
912        ++iter) {
913     struct link_map link_map = { 0 };
914     link_map.l_addr = (ElfW(Addr))iter->addr;
915     link_map.l_name = (char*)(start_addr + data.size() + sizeof(link_map));
916     link_map.l_ld = (ElfW(Dyn)*)iter->ld;
917     link_map.l_prev = prev;
918     prev = (struct link_map*)(start_addr + data.size());
919     std::string filename = full_file.GetAsciiMDString(iter->name);
920 
921     // Look up signature for this filename. If available, change filename
922     // to point to GUID, instead.
923     std::map<uintptr_t, std::string>::const_iterator guid =
924       crashinfo->signatures.find((uintptr_t)iter->addr);
925     if (guid != crashinfo->signatures.end()) {
926       filename = guid->second;
927     }
928 
929     if (std::distance(iter, crashinfo->link_map.end()) == 1) {
930       link_map.l_next = 0;
931     } else {
932       link_map.l_next = (struct link_map*)(start_addr + data.size() +
933                                            sizeof(link_map) +
934                                            ((filename.size() + 8) & ~7));
935     }
936     data.append((char*)&link_map, sizeof(link_map));
937     data.append(filename);
938     data.append(8 - (filename.size() & 7), 0);
939   }
940   AddDataToMapping(crashinfo, data, start_addr);
941 
942   // Map the page containing the _DYNAMIC array
943   if (!crashinfo->dynamic_data.empty()) {
944     // Make _DYNAMIC DT_DEBUG entry point to our link map
945     for (int i = 0;; ++i) {
946       ElfW(Dyn) dyn;
947       if ((i+1)*sizeof(dyn) > crashinfo->dynamic_data.length()) {
948       no_dt_debug:
949         if (verbose) {
950           fprintf(stderr, "No DT_DEBUG entry found\n");
951         }
952         return;
953       }
954       memcpy(&dyn, crashinfo->dynamic_data.c_str() + i*sizeof(dyn),
955              sizeof(dyn));
956       if (dyn.d_tag == DT_DEBUG) {
957         crashinfo->dynamic_data.replace(i*sizeof(dyn) +
958                                        offsetof(ElfW(Dyn), d_un.d_ptr),
959                                        sizeof(start_addr),
960                                        (char*)&start_addr, sizeof(start_addr));
961         break;
962       } else if (dyn.d_tag == DT_NULL) {
963         goto no_dt_debug;
964       }
965     }
966     AddDataToMapping(crashinfo, crashinfo->dynamic_data,
967                      (uintptr_t)crashinfo->debug.dynamic);
968   }
969 }
970 
971 int
main(int argc,char ** argv)972 main(int argc, char** argv) {
973   int argi = 1;
974   while (argi < argc && argv[argi][0] == '-') {
975     if (!strcmp(argv[argi], "-v")) {
976       verbose = true;
977     } else {
978       return usage(argv[0]);
979     }
980     argi++;
981   }
982 
983   if (argc != argi + 1)
984     return usage(argv[0]);
985 
986   MemoryMappedFile mapped_file(argv[argi]);
987   if (!mapped_file.data()) {
988     fprintf(stderr, "Failed to mmap dump file\n");
989     return 1;
990   }
991 
992   MinidumpMemoryRange dump(mapped_file.data(), mapped_file.size());
993 
994   const MDRawHeader* header = dump.GetData<MDRawHeader>(0);
995 
996   CrashedProcess crashinfo;
997 
998   // Always check the system info first, as that allows us to tell whether
999   // this is a minidump file that is compatible with our converter.
1000   bool ok = false;
1001   for (unsigned i = 0; i < header->stream_count; ++i) {
1002     const MDRawDirectory* dirent =
1003         dump.GetArrayElement<MDRawDirectory>(header->stream_directory_rva, i);
1004     switch (dirent->stream_type) {
1005       case MD_SYSTEM_INFO_STREAM:
1006         ParseSystemInfo(&crashinfo, dump.Subrange(dirent->location), dump);
1007         ok = true;
1008         break;
1009       default:
1010         break;
1011     }
1012   }
1013   if (!ok) {
1014     fprintf(stderr, "Cannot determine input file format.\n");
1015     _exit(1);
1016   }
1017 
1018   for (unsigned i = 0; i < header->stream_count; ++i) {
1019     const MDRawDirectory* dirent =
1020         dump.GetArrayElement<MDRawDirectory>(header->stream_directory_rva, i);
1021     switch (dirent->stream_type) {
1022       case MD_THREAD_LIST_STREAM:
1023         ParseThreadList(&crashinfo, dump.Subrange(dirent->location), dump);
1024         break;
1025       case MD_LINUX_CPU_INFO:
1026         ParseCPUInfo(&crashinfo, dump.Subrange(dirent->location));
1027         break;
1028       case MD_LINUX_PROC_STATUS:
1029         ParseProcessStatus(&crashinfo, dump.Subrange(dirent->location));
1030         break;
1031       case MD_LINUX_LSB_RELEASE:
1032         ParseLSBRelease(&crashinfo, dump.Subrange(dirent->location));
1033         break;
1034       case MD_LINUX_ENVIRON:
1035         ParseEnvironment(&crashinfo, dump.Subrange(dirent->location));
1036         break;
1037       case MD_LINUX_MAPS:
1038         ParseMaps(&crashinfo, dump.Subrange(dirent->location));
1039         break;
1040       case MD_LINUX_AUXV:
1041         ParseAuxVector(&crashinfo, dump.Subrange(dirent->location));
1042         break;
1043       case MD_LINUX_CMD_LINE:
1044         ParseCmdLine(&crashinfo, dump.Subrange(dirent->location));
1045         break;
1046       case MD_LINUX_DSO_DEBUG:
1047         ParseDSODebugInfo(&crashinfo, dump.Subrange(dirent->location), dump);
1048         break;
1049       case MD_EXCEPTION_STREAM:
1050         ParseExceptionStream(&crashinfo, dump.Subrange(dirent->location));
1051         break;
1052       case MD_MODULE_LIST_STREAM:
1053         ParseModuleStream(&crashinfo, dump.Subrange(dirent->location), dump);
1054         break;
1055       default:
1056         if (verbose)
1057           fprintf(stderr, "Skipping %x\n", dirent->stream_type);
1058     }
1059   }
1060 
1061   AugmentMappings(&crashinfo, dump);
1062 
1063   // Write the ELF header. The file will look like:
1064   //   ELF header
1065   //   Phdr for the PT_NOTE
1066   //   Phdr for each of the thread stacks
1067   //   PT_NOTE
1068   //   each of the thread stacks
1069   Ehdr ehdr;
1070   memset(&ehdr, 0, sizeof(Ehdr));
1071   ehdr.e_ident[0] = ELFMAG0;
1072   ehdr.e_ident[1] = ELFMAG1;
1073   ehdr.e_ident[2] = ELFMAG2;
1074   ehdr.e_ident[3] = ELFMAG3;
1075   ehdr.e_ident[4] = ELF_CLASS;
1076   ehdr.e_ident[5] = sex() ? ELFDATA2MSB : ELFDATA2LSB;
1077   ehdr.e_ident[6] = EV_CURRENT;
1078   ehdr.e_type     = ET_CORE;
1079   ehdr.e_machine  = ELF_ARCH;
1080   ehdr.e_version  = EV_CURRENT;
1081   ehdr.e_phoff    = sizeof(Ehdr);
1082   ehdr.e_ehsize   = sizeof(Ehdr);
1083   ehdr.e_phentsize= sizeof(Phdr);
1084   ehdr.e_phnum    = 1 +                         // PT_NOTE
1085                     crashinfo.mappings.size();  // memory mappings
1086   ehdr.e_shentsize= sizeof(Shdr);
1087   if (!writea(1, &ehdr, sizeof(Ehdr)))
1088     return 1;
1089 
1090   size_t offset = sizeof(Ehdr) + ehdr.e_phnum * sizeof(Phdr);
1091   size_t filesz = sizeof(Nhdr) + 8 + sizeof(prpsinfo) +
1092                   // sizeof(Nhdr) + 8 + sizeof(user) +
1093                   sizeof(Nhdr) + 8 + crashinfo.auxv_length +
1094                   crashinfo.threads.size() * (
1095                     (sizeof(Nhdr) + 8 + sizeof(prstatus))
1096 #if defined(__i386__) || defined(__x86_64__)
1097                    + sizeof(Nhdr) + 8 + sizeof(user_fpregs_struct)
1098 #endif
1099 #if defined(__i386__)
1100                    + sizeof(Nhdr) + 8 + sizeof(user_fpxregs_struct)
1101 #endif
1102                     );
1103 
1104   Phdr phdr;
1105   memset(&phdr, 0, sizeof(Phdr));
1106   phdr.p_type = PT_NOTE;
1107   phdr.p_offset = offset;
1108   phdr.p_filesz = filesz;
1109   if (!writea(1, &phdr, sizeof(phdr)))
1110     return 1;
1111 
1112   phdr.p_type = PT_LOAD;
1113   phdr.p_align = 4096;
1114   size_t note_align = phdr.p_align - ((offset+filesz) % phdr.p_align);
1115   if (note_align == phdr.p_align)
1116     note_align = 0;
1117   offset += note_align;
1118 
1119   for (std::map<uint64_t, CrashedProcess::Mapping>::const_iterator iter =
1120          crashinfo.mappings.begin();
1121        iter != crashinfo.mappings.end(); ++iter) {
1122     const CrashedProcess::Mapping& mapping = iter->second;
1123     if (mapping.permissions == 0xFFFFFFFF) {
1124       // This is a map that we found in MD_MODULE_LIST_STREAM (as opposed to
1125       // MD_LINUX_MAPS). It lacks some of the information that we would like
1126       // to include.
1127       phdr.p_flags = PF_R;
1128     } else {
1129       phdr.p_flags = mapping.permissions;
1130     }
1131     phdr.p_vaddr = mapping.start_address;
1132     phdr.p_memsz = mapping.end_address - mapping.start_address;
1133     if (mapping.data.size()) {
1134       offset += filesz;
1135       filesz = mapping.data.size();
1136       phdr.p_filesz = mapping.data.size();
1137       phdr.p_offset = offset;
1138     } else {
1139       phdr.p_filesz = 0;
1140       phdr.p_offset = 0;
1141     }
1142     if (!writea(1, &phdr, sizeof(phdr)))
1143       return 1;
1144   }
1145 
1146   Nhdr nhdr;
1147   memset(&nhdr, 0, sizeof(nhdr));
1148   nhdr.n_namesz = 5;
1149   nhdr.n_descsz = sizeof(prpsinfo);
1150   nhdr.n_type = NT_PRPSINFO;
1151   if (!writea(1, &nhdr, sizeof(nhdr)) ||
1152       !writea(1, "CORE\0\0\0\0", 8) ||
1153       !writea(1, &crashinfo.prps, sizeof(prpsinfo))) {
1154     return 1;
1155   }
1156 
1157   nhdr.n_descsz = crashinfo.auxv_length;
1158   nhdr.n_type = NT_AUXV;
1159   if (!writea(1, &nhdr, sizeof(nhdr)) ||
1160       !writea(1, "CORE\0\0\0\0", 8) ||
1161       !writea(1, crashinfo.auxv, crashinfo.auxv_length)) {
1162     return 1;
1163   }
1164 
1165   for (unsigned i = 0; i < crashinfo.threads.size(); ++i) {
1166     if (crashinfo.threads[i].tid == crashinfo.crashing_tid) {
1167       WriteThread(crashinfo.threads[i], crashinfo.fatal_signal);
1168       break;
1169     }
1170   }
1171 
1172   for (unsigned i = 0; i < crashinfo.threads.size(); ++i) {
1173     if (crashinfo.threads[i].tid != crashinfo.crashing_tid)
1174       WriteThread(crashinfo.threads[i], 0);
1175   }
1176 
1177   if (note_align) {
1178     google_breakpad::scoped_array<char> scratch(new char[note_align]);
1179     memset(scratch.get(), 0, note_align);
1180     if (!writea(1, scratch.get(), note_align))
1181       return 1;
1182   }
1183 
1184   for (std::map<uint64_t, CrashedProcess::Mapping>::const_iterator iter =
1185          crashinfo.mappings.begin();
1186        iter != crashinfo.mappings.end(); ++iter) {
1187     const CrashedProcess::Mapping& mapping = iter->second;
1188     if (mapping.data.size()) {
1189       if (!writea(1, mapping.data.c_str(), mapping.data.size()))
1190         return 1;
1191     }
1192   }
1193 
1194   return 0;
1195 }
1196