Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / components / breakpad / app / breakpad_linux.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // For linux_syscall_support.h. This makes it safe to call embedded system
6 // calls when in seccomp mode.
7
8 #include "components/breakpad/app/breakpad_linux.h"
9
10 #include <fcntl.h>
11 #include <poll.h>
12 #include <signal.h>
13 #include <stdlib.h>
14 #include <sys/socket.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <sys/uio.h>
18 #include <sys/wait.h>
19 #include <time.h>
20 #include <unistd.h>
21
22 #include <algorithm>
23 #include <string>
24
25 #include "base/base_switches.h"
26 #include "base/command_line.h"
27 #include "base/debug/crash_logging.h"
28 #include "base/debug/dump_without_crashing.h"
29 #include "base/files/file_path.h"
30 #include "base/linux_util.h"
31 #include "base/path_service.h"
32 #include "base/platform_file.h"
33 #include "base/posix/eintr_wrapper.h"
34 #include "base/posix/global_descriptors.h"
35 #include "base/process/memory.h"
36 #include "base/strings/string_util.h"
37 #include "breakpad/src/client/linux/handler/exception_handler.h"
38 #include "breakpad/src/client/linux/minidump_writer/directory_reader.h"
39 #include "breakpad/src/common/linux/linux_libc_support.h"
40 #include "breakpad/src/common/memory.h"
41 #include "components/breakpad/app/breakpad_client.h"
42 #include "components/breakpad/app/breakpad_linux_impl.h"
43 #include "content/public/common/content_descriptors.h"
44
45 #if defined(OS_ANDROID)
46 #include <android/log.h>
47 #include <sys/stat.h>
48
49 #include "base/android/build_info.h"
50 #include "base/android/path_utils.h"
51 #endif
52 #include "third_party/lss/linux_syscall_support.h"
53
54 #if defined(ADDRESS_SANITIZER)
55 #include <ucontext.h>  // for getcontext().
56 #endif
57
58 #if defined(OS_ANDROID)
59 #define STAT_STRUCT struct stat
60 #define FSTAT_FUNC fstat
61 #else
62 #define STAT_STRUCT struct kernel_stat
63 #define FSTAT_FUNC sys_fstat
64 #endif
65
66 // Some versions of gcc are prone to warn about unused return values. In cases
67 // where we either a) know the call cannot fail, or b) there is nothing we
68 // can do when a call fails, we mark the return code as ignored. This avoids
69 // spurious compiler warnings.
70 #define IGNORE_RET(x) do { if (x); } while (0)
71
72 using google_breakpad::ExceptionHandler;
73 using google_breakpad::MinidumpDescriptor;
74
75 namespace breakpad {
76
77 namespace {
78
79 #if !defined(OS_CHROMEOS)
80 const char kUploadURL[] = "https://clients2.google.com/cr/report";
81 #endif
82
83 bool g_is_crash_reporter_enabled = false;
84 uint64_t g_process_start_time = 0;
85 pid_t g_pid = 0;
86 char* g_crash_log_path = NULL;
87 ExceptionHandler* g_breakpad = NULL;
88
89 #if defined(ADDRESS_SANITIZER)
90 const char* g_asan_report_str = NULL;
91 #endif
92 #if defined(OS_ANDROID)
93 char* g_process_type = NULL;
94 #endif
95
96 CrashKeyStorage* g_crash_keys = NULL;
97
98 // Writes the value |v| as 16 hex characters to the memory pointed at by
99 // |output|.
100 void write_uint64_hex(char* output, uint64_t v) {
101   static const char hextable[] = "0123456789abcdef";
102
103   for (int i = 15; i >= 0; --i) {
104     output[i] = hextable[v & 15];
105     v >>= 4;
106   }
107 }
108
109 // The following helper functions are for calculating uptime.
110
111 // Converts a struct timeval to milliseconds.
112 uint64_t timeval_to_ms(struct timeval *tv) {
113   uint64_t ret = tv->tv_sec;  // Avoid overflow by explicitly using a uint64_t.
114   ret *= 1000;
115   ret += tv->tv_usec / 1000;
116   return ret;
117 }
118
119 // Converts a struct timeval to milliseconds.
120 uint64_t kernel_timeval_to_ms(struct kernel_timeval *tv) {
121   uint64_t ret = tv->tv_sec;  // Avoid overflow by explicitly using a uint64_t.
122   ret *= 1000;
123   ret += tv->tv_usec / 1000;
124   return ret;
125 }
126
127 // String buffer size to use to convert a uint64_t to string.
128 const size_t kUint64StringSize = 21;
129
130 void SetProcessStartTime() {
131   // Set the base process start time value.
132   struct timeval tv;
133   if (!gettimeofday(&tv, NULL))
134     g_process_start_time = timeval_to_ms(&tv);
135   else
136     g_process_start_time = 0;
137 }
138
139 // uint64_t version of my_int_len() from
140 // breakpad/src/common/linux/linux_libc_support.h. Return the length of the
141 // given, non-negative integer when expressed in base 10.
142 unsigned my_uint64_len(uint64_t i) {
143   if (!i)
144     return 1;
145
146   unsigned len = 0;
147   while (i) {
148     len++;
149     i /= 10;
150   }
151
152   return len;
153 }
154
155 // uint64_t version of my_uitos() from
156 // breakpad/src/common/linux/linux_libc_support.h. Convert a non-negative
157 // integer to a string (not null-terminated).
158 void my_uint64tos(char* output, uint64_t i, unsigned i_len) {
159   for (unsigned index = i_len; index; --index, i /= 10)
160     output[index - 1] = '0' + (i % 10);
161 }
162
163 #if defined(OS_ANDROID)
164 char* my_strncpy(char* dst, const char* src, size_t len) {
165   int i = len;
166   char* p = dst;
167   if (!dst || !src)
168     return dst;
169   while (i != 0 && *src != '\0') {
170     *p++ = *src++;
171     i--;
172   }
173   while (i != 0) {
174     *p++ = '\0';
175     i--;
176   }
177   return dst;
178 }
179
180 char* my_strncat(char *dest, const char* src, size_t len) {
181   char* ret = dest;
182   while (*dest)
183       dest++;
184   while (len--)
185     if (!(*dest++ = *src++))
186       return ret;
187   *dest = 0;
188   return ret;
189 }
190 #endif
191
192 size_t LengthWithoutTrailingSpaces(const char* str, size_t len) {
193   while (len > 0 && str[len - 1] == ' ') {
194     len--;
195   }
196   return len;
197 }
198
199 // Populates the passed in allocated string and its size with the distro of
200 // the crashing process.
201 // The passed string is expected to be at least kDistroSize bytes long.
202 void PopulateDistro(char* distro, size_t* distro_len_param) {
203   size_t distro_len = std::min(my_strlen(base::g_linux_distro), kDistroSize);
204   memcpy(distro, base::g_linux_distro, distro_len);
205   if (distro_len_param)
206     *distro_len_param = distro_len;
207 }
208
209 void SetClientIdFromCommandLine(const CommandLine& command_line) {
210   // Get the guid and linux distro from the command line switch.
211   std::string switch_value =
212       command_line.GetSwitchValueASCII(switches::kEnableCrashReporter);
213   size_t separator = switch_value.find(",");
214   if (separator != std::string::npos) {
215     GetBreakpadClient()->SetClientID(switch_value.substr(0, separator));
216     base::SetLinuxDistro(switch_value.substr(separator + 1));
217   } else {
218     GetBreakpadClient()->SetClientID(switch_value);
219   }
220 }
221
222 // MIME substrings.
223 #if defined(OS_CHROMEOS)
224 const char g_sep[] = ":";
225 #endif
226 const char g_rn[] = "\r\n";
227 const char g_form_data_msg[] = "Content-Disposition: form-data; name=\"";
228 const char g_quote_msg[] = "\"";
229 const char g_dashdash_msg[] = "--";
230 const char g_dump_msg[] = "upload_file_minidump\"; filename=\"dump\"";
231 #if defined(ADDRESS_SANITIZER)
232 const char g_log_msg[] = "upload_file_log\"; filename=\"log\"";
233 #endif
234 const char g_content_type_msg[] = "Content-Type: application/octet-stream";
235
236 // MimeWriter manages an iovec for writing MIMEs to a file.
237 class MimeWriter {
238  public:
239   static const int kIovCapacity = 30;
240   static const size_t kMaxCrashChunkSize = 64;
241
242   MimeWriter(int fd, const char* const mime_boundary);
243   ~MimeWriter();
244
245   // Append boundary.
246   virtual void AddBoundary();
247
248   // Append end of file boundary.
249   virtual void AddEnd();
250
251   // Append key/value pair with specified sizes.
252   virtual void AddPairData(const char* msg_type,
253                            size_t msg_type_size,
254                            const char* msg_data,
255                            size_t msg_data_size);
256
257   // Append key/value pair.
258   void AddPairString(const char* msg_type,
259                      const char* msg_data) {
260     AddPairData(msg_type, my_strlen(msg_type), msg_data, my_strlen(msg_data));
261   }
262
263   // Append key/value pair, splitting value into chunks no larger than
264   // |chunk_size|. |chunk_size| cannot be greater than |kMaxCrashChunkSize|.
265   // The msg_type string will have a counter suffix to distinguish each chunk.
266   virtual void AddPairDataInChunks(const char* msg_type,
267                                    size_t msg_type_size,
268                                    const char* msg_data,
269                                    size_t msg_data_size,
270                                    size_t chunk_size,
271                                    bool strip_trailing_spaces);
272
273   // Add binary file contents to be uploaded with the specified filename.
274   virtual void AddFileContents(const char* filename_msg,
275                                uint8_t* file_data,
276                                size_t file_size);
277
278   // Flush any pending iovecs to the output file.
279   void Flush() {
280     IGNORE_RET(sys_writev(fd_, iov_, iov_index_));
281     iov_index_ = 0;
282   }
283
284  protected:
285   void AddItem(const void* base, size_t size);
286   // Minor performance trade-off for easier-to-maintain code.
287   void AddString(const char* str) {
288     AddItem(str, my_strlen(str));
289   }
290   void AddItemWithoutTrailingSpaces(const void* base, size_t size);
291
292   struct kernel_iovec iov_[kIovCapacity];
293   int iov_index_;
294
295   // Output file descriptor.
296   int fd_;
297
298   const char* const mime_boundary_;
299
300   DISALLOW_COPY_AND_ASSIGN(MimeWriter);
301 };
302
303 MimeWriter::MimeWriter(int fd, const char* const mime_boundary)
304     : iov_index_(0),
305       fd_(fd),
306       mime_boundary_(mime_boundary) {
307 }
308
309 MimeWriter::~MimeWriter() {
310 }
311
312 void MimeWriter::AddBoundary() {
313   AddString(mime_boundary_);
314   AddString(g_rn);
315 }
316
317 void MimeWriter::AddEnd() {
318   AddString(mime_boundary_);
319   AddString(g_dashdash_msg);
320   AddString(g_rn);
321 }
322
323 void MimeWriter::AddPairData(const char* msg_type,
324                              size_t msg_type_size,
325                              const char* msg_data,
326                              size_t msg_data_size) {
327   AddString(g_form_data_msg);
328   AddItem(msg_type, msg_type_size);
329   AddString(g_quote_msg);
330   AddString(g_rn);
331   AddString(g_rn);
332   AddItem(msg_data, msg_data_size);
333   AddString(g_rn);
334 }
335
336 void MimeWriter::AddPairDataInChunks(const char* msg_type,
337                                      size_t msg_type_size,
338                                      const char* msg_data,
339                                      size_t msg_data_size,
340                                      size_t chunk_size,
341                                      bool strip_trailing_spaces) {
342   if (chunk_size > kMaxCrashChunkSize)
343     return;
344
345   unsigned i = 0;
346   size_t done = 0, msg_length = msg_data_size;
347
348   while (msg_length) {
349     char num[kUint64StringSize];
350     const unsigned num_len = my_uint_len(++i);
351     my_uitos(num, i, num_len);
352
353     size_t chunk_len = std::min(chunk_size, msg_length);
354
355     AddString(g_form_data_msg);
356     AddItem(msg_type, msg_type_size);
357     AddItem(num, num_len);
358     AddString(g_quote_msg);
359     AddString(g_rn);
360     AddString(g_rn);
361     if (strip_trailing_spaces) {
362       AddItemWithoutTrailingSpaces(msg_data + done, chunk_len);
363     } else {
364       AddItem(msg_data + done, chunk_len);
365     }
366     AddString(g_rn);
367     AddBoundary();
368     Flush();
369
370     done += chunk_len;
371     msg_length -= chunk_len;
372   }
373 }
374
375 void MimeWriter::AddFileContents(const char* filename_msg, uint8_t* file_data,
376                                  size_t file_size) {
377   AddString(g_form_data_msg);
378   AddString(filename_msg);
379   AddString(g_rn);
380   AddString(g_content_type_msg);
381   AddString(g_rn);
382   AddString(g_rn);
383   AddItem(file_data, file_size);
384   AddString(g_rn);
385 }
386
387 void MimeWriter::AddItem(const void* base, size_t size) {
388   // Check if the iovec is full and needs to be flushed to output file.
389   if (iov_index_ == kIovCapacity) {
390     Flush();
391   }
392   iov_[iov_index_].iov_base = const_cast<void*>(base);
393   iov_[iov_index_].iov_len = size;
394   ++iov_index_;
395 }
396
397 void MimeWriter::AddItemWithoutTrailingSpaces(const void* base, size_t size) {
398   AddItem(base, LengthWithoutTrailingSpaces(static_cast<const char*>(base),
399                                             size));
400 }
401
402 #if defined(OS_CHROMEOS)
403 // This subclass is used on Chromium OS to report crashes in a format easy for
404 // the central crash reporting facility to understand.
405 // Format is <name>:<data length in decimal>:<data>
406 class CrashReporterWriter : public MimeWriter
407 {
408  public:
409   explicit CrashReporterWriter(int fd);
410
411   virtual void AddBoundary() OVERRIDE;
412
413   virtual void AddEnd() OVERRIDE;
414
415   virtual void AddPairData(const char* msg_type,
416                            size_t msg_type_size,
417                           const char* msg_data,
418                            size_t msg_data_size) OVERRIDE;
419
420   virtual void AddPairDataInChunks(const char* msg_type,
421                                    size_t msg_type_size,
422                                    const char* msg_data,
423                                    size_t msg_data_size,
424                                    size_t chunk_size,
425                                    bool strip_trailing_spaces) OVERRIDE;
426
427   virtual void AddFileContents(const char* filename_msg,
428                                uint8_t* file_data,
429                                size_t file_size) OVERRIDE;
430
431  private:
432   DISALLOW_COPY_AND_ASSIGN(CrashReporterWriter);
433 };
434
435
436 CrashReporterWriter::CrashReporterWriter(int fd) : MimeWriter(fd, "") {}
437
438 // No-ops.
439 void CrashReporterWriter::AddBoundary() {}
440 void CrashReporterWriter::AddEnd() {}
441
442 void CrashReporterWriter::AddPairData(const char* msg_type,
443                                       size_t msg_type_size,
444                                       const char* msg_data,
445                                       size_t msg_data_size) {
446   char data[kUint64StringSize];
447   const unsigned data_len = my_uint_len(msg_data_size);
448   my_uitos(data, msg_data_size, data_len);
449
450   AddItem(msg_type, msg_type_size);
451   AddString(g_sep);
452   AddItem(data, data_len);
453   AddString(g_sep);
454   AddItem(msg_data, msg_data_size);
455   Flush();
456 }
457
458 void CrashReporterWriter::AddPairDataInChunks(const char* msg_type,
459                                               size_t msg_type_size,
460                                               const char* msg_data,
461                                               size_t msg_data_size,
462                                               size_t chunk_size,
463                                               bool strip_trailing_spaces) {
464   if (chunk_size > kMaxCrashChunkSize)
465     return;
466
467   unsigned i = 0;
468   size_t done = 0;
469   size_t msg_length = msg_data_size;
470
471   while (msg_length) {
472     char num[kUint64StringSize];
473     const unsigned num_len = my_uint_len(++i);
474     my_uitos(num, i, num_len);
475
476     size_t chunk_len = std::min(chunk_size, msg_length);
477
478     size_t write_len = chunk_len;
479     if (strip_trailing_spaces) {
480       // Take care of this here because we need to know the exact length of
481       // what is going to be written.
482       write_len = LengthWithoutTrailingSpaces(msg_data + done, write_len);
483     }
484
485     char data[kUint64StringSize];
486     const unsigned data_len = my_uint_len(write_len);
487     my_uitos(data, write_len, data_len);
488
489     AddItem(msg_type, msg_type_size);
490     AddItem(num, num_len);
491     AddString(g_sep);
492     AddItem(data, data_len);
493     AddString(g_sep);
494     AddItem(msg_data + done, write_len);
495     Flush();
496
497     done += chunk_len;
498     msg_length -= chunk_len;
499   }
500 }
501
502 void CrashReporterWriter::AddFileContents(const char* filename_msg,
503                                           uint8_t* file_data,
504                                           size_t file_size) {
505   char data[kUint64StringSize];
506   const unsigned data_len = my_uint_len(file_size);
507   my_uitos(data, file_size, data_len);
508
509   AddString(filename_msg);
510   AddString(g_sep);
511   AddItem(data, data_len);
512   AddString(g_sep);
513   AddItem(file_data, file_size);
514   Flush();
515 }
516 #endif
517
518 void DumpProcess() {
519   if (g_breakpad)
520     g_breakpad->WriteMinidump();
521 }
522
523 #if defined(OS_ANDROID)
524 const char kGoogleBreakpad[] = "google-breakpad";
525 #endif
526
527 size_t WriteLog(const char* buf, size_t nbytes) {
528 #if defined(OS_ANDROID)
529   return __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad, buf);
530 #else
531   return sys_write(2, buf, nbytes);
532 #endif
533 }
534
535 #if defined(OS_ANDROID)
536 // Android's native crash handler outputs a diagnostic tombstone to the device
537 // log. By returning false from the HandlerCallbacks, breakpad will reinstall
538 // the previous (i.e. native) signal handlers before returning from its own
539 // handler. A Chrome build fingerprint is written to the log, so that the
540 // specific build of Chrome and the location of the archived Chrome symbols can
541 // be determined directly from it.
542 bool FinalizeCrashDoneAndroid() {
543   base::android::BuildInfo* android_build_info =
544       base::android::BuildInfo::GetInstance();
545
546   __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
547                       "### ### ### ### ### ### ### ### ### ### ### ### ###");
548   __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
549                       "Chrome build fingerprint:");
550   __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
551                       android_build_info->package_version_name());
552   __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
553                       android_build_info->package_version_code());
554   __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
555                       CHROME_BUILD_ID);
556   __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
557                       "### ### ### ### ### ### ### ### ### ### ### ### ###");
558   return false;
559 }
560 #endif
561
562 bool CrashDone(const MinidumpDescriptor& minidump,
563                const bool upload,
564                const bool succeeded) {
565   // WARNING: this code runs in a compromised context. It may not call into
566   // libc nor allocate memory normally.
567   if (!succeeded) {
568     const char msg[] = "Failed to generate minidump.";
569     WriteLog(msg, sizeof(msg) - 1);
570     return false;
571   }
572
573   DCHECK(!minidump.IsFD());
574
575   BreakpadInfo info = {0};
576   info.filename = minidump.path();
577   info.fd = minidump.fd();
578 #if defined(ADDRESS_SANITIZER)
579   google_breakpad::PageAllocator allocator;
580   const size_t log_path_len = my_strlen(minidump.path());
581   char* log_path = reinterpret_cast<char*>(allocator.Alloc(log_path_len + 1));
582   my_memcpy(log_path, minidump.path(), log_path_len);
583   my_memcpy(log_path + log_path_len - 4, ".log", 4);
584   log_path[log_path_len] = '\0';
585   info.log_filename = log_path;
586 #endif
587   info.process_type = "browser";
588   info.process_type_length = 7;
589   info.distro = base::g_linux_distro;
590   info.distro_length = my_strlen(base::g_linux_distro);
591   info.upload = upload;
592   info.process_start_time = g_process_start_time;
593   info.oom_size = base::g_oom_size;
594   info.pid = g_pid;
595   info.crash_keys = g_crash_keys;
596   HandleCrashDump(info);
597 #if defined(OS_ANDROID)
598   return FinalizeCrashDoneAndroid();
599 #else
600   return true;
601 #endif
602 }
603
604 // Wrapper function, do not add more code here.
605 bool CrashDoneNoUpload(const MinidumpDescriptor& minidump,
606                        void* context,
607                        bool succeeded) {
608   return CrashDone(minidump, false, succeeded);
609 }
610
611 #if !defined(OS_ANDROID)
612 // Wrapper function, do not add more code here.
613 bool CrashDoneUpload(const MinidumpDescriptor& minidump,
614                      void* context,
615                      bool succeeded) {
616   return CrashDone(minidump, true, succeeded);
617 }
618 #endif
619
620 #if defined(ADDRESS_SANITIZER)
621 extern "C"
622 void __asan_set_error_report_callback(void (*cb)(const char*));
623
624 extern "C"
625 void AsanLinuxBreakpadCallback(const char* report) {
626   g_asan_report_str = report;
627   // Send minidump here.
628   g_breakpad->SimulateSignalDelivery(SIGKILL);
629 }
630 #endif
631
632 void EnableCrashDumping(bool unattended) {
633   g_is_crash_reporter_enabled = true;
634
635   base::FilePath tmp_path("/tmp");
636   PathService::Get(base::DIR_TEMP, &tmp_path);
637
638   base::FilePath dumps_path(tmp_path);
639   if (GetBreakpadClient()->GetCrashDumpLocation(&dumps_path)) {
640     base::FilePath logfile =
641         dumps_path.Append(GetBreakpadClient()->GetReporterLogFilename());
642     std::string logfile_str = logfile.value();
643     const size_t crash_log_path_len = logfile_str.size() + 1;
644     g_crash_log_path = new char[crash_log_path_len];
645     strncpy(g_crash_log_path, logfile_str.c_str(), crash_log_path_len);
646   }
647   DCHECK(!g_breakpad);
648   MinidumpDescriptor minidump_descriptor(dumps_path.value());
649   minidump_descriptor.set_size_limit(kMaxMinidumpFileSize);
650 #if defined(OS_ANDROID)
651   unattended = true;  // Android never uploads directly.
652 #endif
653   if (unattended) {
654     g_breakpad = new ExceptionHandler(
655         minidump_descriptor,
656         NULL,
657         CrashDoneNoUpload,
658         NULL,
659         true,  // Install handlers.
660         -1);   // Server file descriptor. -1 for in-process.
661     return;
662   }
663
664 #if !defined(OS_ANDROID)
665   // Attended mode
666   g_breakpad = new ExceptionHandler(
667       minidump_descriptor,
668       NULL,
669       CrashDoneUpload,
670       NULL,
671       true,  // Install handlers.
672       -1);   // Server file descriptor. -1 for in-process.
673 #endif
674 }
675
676 #if defined(OS_ANDROID)
677 bool CrashDoneInProcessNoUpload(
678     const google_breakpad::MinidumpDescriptor& descriptor,
679     void* context,
680     const bool succeeded) {
681   // WARNING: this code runs in a compromised context. It may not call into
682   // libc nor allocate memory normally.
683   if (!succeeded) {
684     static const char msg[] = "Crash dump generation failed.\n";
685     WriteLog(msg, sizeof(msg) - 1);
686     return false;
687   }
688
689   // Start constructing the message to send to the browser.
690   char distro[kDistroSize + 1] = {0};
691   size_t distro_length = 0;
692   PopulateDistro(distro, &distro_length);
693   BreakpadInfo info = {0};
694   info.filename = NULL;
695   info.fd = descriptor.fd();
696   info.process_type = g_process_type;
697   info.process_type_length = my_strlen(g_process_type);
698   info.distro = distro;
699   info.distro_length = distro_length;
700   info.upload = false;
701   info.process_start_time = g_process_start_time;
702   info.pid = g_pid;
703   info.crash_keys = g_crash_keys;
704   HandleCrashDump(info);
705   bool finalize_result = FinalizeCrashDoneAndroid();
706   base::android::BuildInfo* android_build_info =
707       base::android::BuildInfo::GetInstance();
708   if (android_build_info->sdk_int() >= 18 &&
709       strcmp(android_build_info->build_type(), "eng") != 0 &&
710       strcmp(android_build_info->build_type(), "userdebug") != 0) {
711     // On JB MR2 and later, the system crash handler displays a dialog. For
712     // renderer crashes, this is a bad user experience and so this is disabled
713     // for user builds of Android.
714     // TODO(cjhopman): There should be some way to recover the crash stack from
715     // non-uploading user clients. See http://crbug.com/273706.
716     __android_log_write(ANDROID_LOG_WARN,
717                         kGoogleBreakpad,
718                         "Tombstones are disabled on JB MR2+ user builds.");
719     __android_log_write(ANDROID_LOG_WARN,
720                         kGoogleBreakpad,
721                         "### ### ### ### ### ### ### ### ### ### ### ### ###");
722     return true;
723   } else {
724     return finalize_result;
725   }
726 }
727
728 void EnableNonBrowserCrashDumping(const std::string& process_type,
729                                   int minidump_fd) {
730   // This will guarantee that the BuildInfo has been initialized and subsequent
731   // calls will not require memory allocation.
732   base::android::BuildInfo::GetInstance();
733   SetClientIdFromCommandLine(*CommandLine::ForCurrentProcess());
734
735   // On Android, the current sandboxing uses process isolation, in which the
736   // child process runs with a different UID. That breaks the normal crash
737   // reporting where the browser process generates the minidump by inspecting
738   // the child process. This is because the browser process now does not have
739   // the permission to access the states of the child process (as it has a
740   // different UID).
741   // TODO(jcivelli): http://b/issue?id=6776356 we should use a watchdog
742   // process forked from the renderer process that generates the minidump.
743   if (minidump_fd == -1) {
744     LOG(ERROR) << "Minidump file descriptor not found, crash reporting will "
745         " not work.";
746     return;
747   }
748   SetProcessStartTime();
749   g_pid = getpid();
750
751   g_is_crash_reporter_enabled = true;
752   // Save the process type (it is leaked).
753   const size_t process_type_len = process_type.size() + 1;
754   g_process_type = new char[process_type_len];
755   strncpy(g_process_type, process_type.c_str(), process_type_len);
756   new google_breakpad::ExceptionHandler(MinidumpDescriptor(minidump_fd),
757       NULL, CrashDoneInProcessNoUpload, NULL, true, -1);
758 }
759 #else
760 // Non-Browser = Extension, Gpu, Plugins, Ppapi and Renderer
761 bool NonBrowserCrashHandler(const void* crash_context,
762                             size_t crash_context_size,
763                             void* context) {
764   const int fd = reinterpret_cast<intptr_t>(context);
765   int fds[2] = { -1, -1 };
766   if (sys_socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
767     static const char msg[] = "Failed to create socket for crash dumping.\n";
768     WriteLog(msg, sizeof(msg) - 1);
769     return false;
770   }
771
772   // Start constructing the message to send to the browser.
773   char distro[kDistroSize + 1] = {0};
774   PopulateDistro(distro, NULL);
775
776   char b;  // Dummy variable for sys_read below.
777   const char* b_addr = &b;  // Get the address of |b| so we can create the
778                             // expected /proc/[pid]/syscall content in the
779                             // browser to convert namespace tids.
780
781   // The length of the control message:
782   static const unsigned kControlMsgSize = sizeof(fds);
783   static const unsigned kControlMsgSpaceSize = CMSG_SPACE(kControlMsgSize);
784   static const unsigned kControlMsgLenSize = CMSG_LEN(kControlMsgSize);
785
786   struct kernel_msghdr msg;
787   my_memset(&msg, 0, sizeof(struct kernel_msghdr));
788   struct kernel_iovec iov[kCrashIovSize];
789   iov[0].iov_base = const_cast<void*>(crash_context);
790   iov[0].iov_len = crash_context_size;
791   iov[1].iov_base = distro;
792   iov[1].iov_len = kDistroSize + 1;
793   iov[2].iov_base = &b_addr;
794   iov[2].iov_len = sizeof(b_addr);
795   iov[3].iov_base = &fds[0];
796   iov[3].iov_len = sizeof(fds[0]);
797   iov[4].iov_base = &g_process_start_time;
798   iov[4].iov_len = sizeof(g_process_start_time);
799   iov[5].iov_base = &base::g_oom_size;
800   iov[5].iov_len = sizeof(base::g_oom_size);
801   google_breakpad::SerializedNonAllocatingMap* serialized_map;
802   iov[6].iov_len = g_crash_keys->Serialize(
803       const_cast<const google_breakpad::SerializedNonAllocatingMap**>(
804           &serialized_map));
805   iov[6].iov_base = serialized_map;
806 #if defined(ADDRESS_SANITIZER)
807   iov[7].iov_base = const_cast<char*>(g_asan_report_str);
808   iov[7].iov_len = kMaxAsanReportSize + 1;
809 #endif
810
811   msg.msg_iov = iov;
812   msg.msg_iovlen = kCrashIovSize;
813   char cmsg[kControlMsgSpaceSize];
814   my_memset(cmsg, 0, kControlMsgSpaceSize);
815   msg.msg_control = cmsg;
816   msg.msg_controllen = sizeof(cmsg);
817
818   struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg);
819   hdr->cmsg_level = SOL_SOCKET;
820   hdr->cmsg_type = SCM_RIGHTS;
821   hdr->cmsg_len = kControlMsgLenSize;
822   ((int*) CMSG_DATA(hdr))[0] = fds[0];
823   ((int*) CMSG_DATA(hdr))[1] = fds[1];
824
825   if (HANDLE_EINTR(sys_sendmsg(fd, &msg, 0)) < 0) {
826     static const char errmsg[] = "Failed to tell parent about crash.\n";
827     WriteLog(errmsg, sizeof(errmsg) - 1);
828     IGNORE_RET(sys_close(fds[1]));
829     return false;
830   }
831   IGNORE_RET(sys_close(fds[1]));
832
833   if (HANDLE_EINTR(sys_read(fds[0], &b, 1)) != 1) {
834     static const char errmsg[] = "Parent failed to complete crash dump.\n";
835     WriteLog(errmsg, sizeof(errmsg) - 1);
836   }
837
838   return true;
839 }
840
841 void EnableNonBrowserCrashDumping() {
842   const int fd = base::GlobalDescriptors::GetInstance()->Get(kCrashDumpSignal);
843   g_is_crash_reporter_enabled = true;
844   // We deliberately leak this object.
845   DCHECK(!g_breakpad);
846
847   g_breakpad = new ExceptionHandler(
848       MinidumpDescriptor("/tmp"),  // Unused but needed or Breakpad will assert.
849       NULL,
850       NULL,
851       reinterpret_cast<void*>(fd),  // Param passed to the crash handler.
852       true,
853       -1);
854   g_breakpad->set_crash_handler(NonBrowserCrashHandler);
855 }
856 #endif  // defined(OS_ANDROID)
857
858 void SetCrashKeyValue(const base::StringPiece& key,
859                       const base::StringPiece& value) {
860   g_crash_keys->SetKeyValue(key.data(), value.data());
861 }
862
863 void ClearCrashKey(const base::StringPiece& key) {
864   g_crash_keys->RemoveKey(key.data());
865 }
866
867 }  // namespace
868
869 void LoadDataFromFD(google_breakpad::PageAllocator& allocator,
870                     int fd, bool close_fd, uint8_t** file_data, size_t* size) {
871   STAT_STRUCT st;
872   if (FSTAT_FUNC(fd, &st) != 0) {
873     static const char msg[] = "Cannot upload crash dump: stat failed\n";
874     WriteLog(msg, sizeof(msg) - 1);
875     if (close_fd)
876       IGNORE_RET(sys_close(fd));
877     return;
878   }
879
880   *file_data = reinterpret_cast<uint8_t*>(allocator.Alloc(st.st_size));
881   if (!(*file_data)) {
882     static const char msg[] = "Cannot upload crash dump: cannot alloc\n";
883     WriteLog(msg, sizeof(msg) - 1);
884     if (close_fd)
885       IGNORE_RET(sys_close(fd));
886     return;
887   }
888   my_memset(*file_data, 0xf, st.st_size);
889
890   *size = st.st_size;
891   int byte_read = sys_read(fd, *file_data, *size);
892   if (byte_read == -1) {
893     static const char msg[] = "Cannot upload crash dump: read failed\n";
894     WriteLog(msg, sizeof(msg) - 1);
895     if (close_fd)
896       IGNORE_RET(sys_close(fd));
897     return;
898   }
899
900   if (close_fd)
901     IGNORE_RET(sys_close(fd));
902 }
903
904 void LoadDataFromFile(google_breakpad::PageAllocator& allocator,
905                       const char* filename,
906                       int* fd, uint8_t** file_data, size_t* size) {
907   // WARNING: this code runs in a compromised context. It may not call into
908   // libc nor allocate memory normally.
909   *fd = sys_open(filename, O_RDONLY, 0);
910   *size = 0;
911
912   if (*fd < 0) {
913     static const char msg[] = "Cannot upload crash dump: failed to open\n";
914     WriteLog(msg, sizeof(msg) - 1);
915     return;
916   }
917
918   LoadDataFromFD(allocator, *fd, true, file_data, size);
919 }
920
921 // Spawn the appropriate upload process for the current OS:
922 // - generic Linux invokes wget.
923 // - ChromeOS invokes crash_reporter.
924 // |dumpfile| is the path to the dump data file.
925 // |mime_boundary| is only used on Linux.
926 // |exe_buf| is only used on CrOS and is the crashing process' name.
927 void ExecUploadProcessOrTerminate(const BreakpadInfo& info,
928                                   const char* dumpfile,
929                                   const char* mime_boundary,
930                                   const char* exe_buf,
931                                   google_breakpad::PageAllocator* allocator) {
932 #if defined(OS_CHROMEOS)
933   // CrOS uses crash_reporter instead of wget to report crashes,
934   // it needs to know where the crash dump lives and the pid and uid of the
935   // crashing process.
936   static const char kCrashReporterBinary[] = "/sbin/crash_reporter";
937
938   char pid_buf[kUint64StringSize];
939   uint64_t pid_str_length = my_uint64_len(info.pid);
940   my_uint64tos(pid_buf, info.pid, pid_str_length);
941   pid_buf[pid_str_length] = '\0';
942
943   char uid_buf[kUint64StringSize];
944   uid_t uid = geteuid();
945   uint64_t uid_str_length = my_uint64_len(uid);
946   my_uint64tos(uid_buf, uid, uid_str_length);
947   uid_buf[uid_str_length] = '\0';
948   const char* args[] = {
949     kCrashReporterBinary,
950     "--chrome",
951     dumpfile,
952     "--pid",
953     pid_buf,
954     "--uid",
955     uid_buf,
956     "--exe",
957     exe_buf,
958     NULL,
959   };
960   static const char msg[] = "Cannot upload crash dump: cannot exec "
961                             "/sbin/crash_reporter\n";
962 #else
963   // The --header argument to wget looks like:
964   //   --header=Content-Type: multipart/form-data; boundary=XYZ
965   // where the boundary has two fewer leading '-' chars
966   static const char header_msg[] =
967       "--header=Content-Type: multipart/form-data; boundary=";
968   char* const header = reinterpret_cast<char*>(allocator->Alloc(
969       sizeof(header_msg) - 1 + strlen(mime_boundary) - 2 + 1));
970   memcpy(header, header_msg, sizeof(header_msg) - 1);
971   memcpy(header + sizeof(header_msg) - 1, mime_boundary + 2,
972          strlen(mime_boundary) - 2);
973   // We grab the NUL byte from the end of |mime_boundary|.
974
975   // The --post-file argument to wget looks like:
976   //   --post-file=/tmp/...
977   static const char post_file_msg[] = "--post-file=";
978   char* const post_file = reinterpret_cast<char*>(allocator->Alloc(
979        sizeof(post_file_msg) - 1 + strlen(dumpfile) + 1));
980   memcpy(post_file, post_file_msg, sizeof(post_file_msg) - 1);
981   memcpy(post_file + sizeof(post_file_msg) - 1, dumpfile, strlen(dumpfile));
982
983   static const char kWgetBinary[] = "/usr/bin/wget";
984   const char* args[] = {
985     kWgetBinary,
986     header,
987     post_file,
988     kUploadURL,
989     "--timeout=10",  // Set a timeout so we don't hang forever.
990     "--tries=1",     // Don't retry if the upload fails.
991     "-O",  // output reply to fd 3
992     "/dev/fd/3",
993     NULL,
994   };
995   static const char msg[] = "Cannot upload crash dump: cannot exec "
996                             "/usr/bin/wget\n";
997 #endif
998   execve(args[0], const_cast<char**>(args), environ);
999   WriteLog(msg, sizeof(msg) - 1);
1000   sys__exit(1);
1001 }
1002
1003 #if defined(OS_CHROMEOS)
1004 const char* GetCrashingProcessName(const BreakpadInfo& info,
1005                                    google_breakpad::PageAllocator* allocator) {
1006   // Symlink to process binary is at /proc/###/exe.
1007   char linkpath[kUint64StringSize + sizeof("/proc/") + sizeof("/exe")] =
1008     "/proc/";
1009   uint64_t pid_value_len = my_uint64_len(info.pid);
1010   my_uint64tos(linkpath + sizeof("/proc/") - 1, info.pid, pid_value_len);
1011   linkpath[sizeof("/proc/") - 1 + pid_value_len] = '\0';
1012   my_strlcat(linkpath, "/exe", sizeof(linkpath));
1013
1014   const int kMaxSize = 4096;
1015   char* link = reinterpret_cast<char*>(allocator->Alloc(kMaxSize));
1016   if (link) {
1017     ssize_t size = readlink(linkpath, link, kMaxSize);
1018     if (size < kMaxSize && size > 0) {
1019       // readlink(2) doesn't add a terminating NUL, so do it now.
1020       link[size] = '\0';
1021
1022       const char* name = my_strrchr(link, '/');
1023       if (name)
1024         return name + 1;
1025       return link;
1026     }
1027   }
1028   // Either way too long, or a read error.
1029   return "chrome-crash-unknown-process";
1030 }
1031 #endif
1032
1033 void HandleCrashDump(const BreakpadInfo& info) {
1034   int dumpfd;
1035   bool keep_fd = false;
1036   size_t dump_size;
1037   uint8_t* dump_data;
1038   google_breakpad::PageAllocator allocator;
1039   const char* exe_buf = NULL;
1040
1041 #if defined(OS_CHROMEOS)
1042   // Grab the crashing process' name now, when it should still be available.
1043   // If we try to do this later in our grandchild the crashing process has
1044   // already terminated.
1045   exe_buf = GetCrashingProcessName(info, &allocator);
1046 #endif
1047
1048   if (info.fd != -1) {
1049     // Dump is provided with an open FD.
1050     keep_fd = true;
1051     dumpfd = info.fd;
1052
1053     // The FD is pointing to the end of the file.
1054     // Rewind, we'll read the data next.
1055     if (lseek(dumpfd, 0, SEEK_SET) == -1) {
1056       static const char msg[] = "Cannot upload crash dump: failed to "
1057           "reposition minidump FD\n";
1058       WriteLog(msg, sizeof(msg) - 1);
1059       IGNORE_RET(sys_close(dumpfd));
1060       return;
1061     }
1062     LoadDataFromFD(allocator, info.fd, false, &dump_data, &dump_size);
1063   } else {
1064     // Dump is provided with a path.
1065     keep_fd = false;
1066     LoadDataFromFile(allocator, info.filename, &dumpfd, &dump_data, &dump_size);
1067   }
1068
1069   // TODO(jcivelli): make log work when using FDs.
1070 #if defined(ADDRESS_SANITIZER)
1071   int logfd;
1072   size_t log_size;
1073   uint8_t* log_data;
1074   // Load the AddressSanitizer log into log_data.
1075   LoadDataFromFile(allocator, info.log_filename, &logfd, &log_data, &log_size);
1076 #endif
1077
1078   // We need to build a MIME block for uploading to the server. Since we are
1079   // going to fork and run wget, it needs to be written to a temp file.
1080   const int ufd = sys_open("/dev/urandom", O_RDONLY, 0);
1081   if (ufd < 0) {
1082     static const char msg[] = "Cannot upload crash dump because /dev/urandom"
1083                               " is missing\n";
1084     WriteLog(msg, sizeof(msg) - 1);
1085     return;
1086   }
1087
1088   static const char temp_file_template[] =
1089       "/tmp/chromium-upload-XXXXXXXXXXXXXXXX";
1090   char temp_file[sizeof(temp_file_template)];
1091   int temp_file_fd = -1;
1092   if (keep_fd) {
1093     temp_file_fd = dumpfd;
1094     // Rewind the destination, we are going to overwrite it.
1095     if (lseek(dumpfd, 0, SEEK_SET) == -1) {
1096       static const char msg[] = "Cannot upload crash dump: failed to "
1097           "reposition minidump FD (2)\n";
1098       WriteLog(msg, sizeof(msg) - 1);
1099       IGNORE_RET(sys_close(dumpfd));
1100       return;
1101     }
1102   } else {
1103     if (info.upload) {
1104       memcpy(temp_file, temp_file_template, sizeof(temp_file_template));
1105
1106       for (unsigned i = 0; i < 10; ++i) {
1107         uint64_t t;
1108         sys_read(ufd, &t, sizeof(t));
1109         write_uint64_hex(temp_file + sizeof(temp_file) - (16 + 1), t);
1110
1111         temp_file_fd = sys_open(temp_file, O_WRONLY | O_CREAT | O_EXCL, 0600);
1112         if (temp_file_fd >= 0)
1113           break;
1114       }
1115
1116       if (temp_file_fd < 0) {
1117         static const char msg[] = "Failed to create temporary file in /tmp: "
1118             "cannot upload crash dump\n";
1119         WriteLog(msg, sizeof(msg) - 1);
1120         IGNORE_RET(sys_close(ufd));
1121         return;
1122       }
1123     } else {
1124       temp_file_fd = sys_open(info.filename, O_WRONLY, 0600);
1125       if (temp_file_fd < 0) {
1126         static const char msg[] = "Failed to save crash dump: failed to open\n";
1127         WriteLog(msg, sizeof(msg) - 1);
1128         IGNORE_RET(sys_close(ufd));
1129         return;
1130       }
1131     }
1132   }
1133
1134   // The MIME boundary is 28 hyphens, followed by a 64-bit nonce and a NUL.
1135   char mime_boundary[28 + 16 + 1];
1136   my_memset(mime_boundary, '-', 28);
1137   uint64_t boundary_rand;
1138   sys_read(ufd, &boundary_rand, sizeof(boundary_rand));
1139   write_uint64_hex(mime_boundary + 28, boundary_rand);
1140   mime_boundary[28 + 16] = 0;
1141   IGNORE_RET(sys_close(ufd));
1142
1143   // The MIME block looks like this:
1144   //   BOUNDARY \r\n
1145   //   Content-Disposition: form-data; name="prod" \r\n \r\n
1146   //   Chrome_Linux \r\n
1147   //   BOUNDARY \r\n
1148   //   Content-Disposition: form-data; name="ver" \r\n \r\n
1149   //   1.2.3.4 \r\n
1150   //   BOUNDARY \r\n
1151   //
1152   //   zero or one:
1153   //   Content-Disposition: form-data; name="ptime" \r\n \r\n
1154   //   abcdef \r\n
1155   //   BOUNDARY \r\n
1156   //
1157   //   zero or one:
1158   //   Content-Disposition: form-data; name="ptype" \r\n \r\n
1159   //   abcdef \r\n
1160   //   BOUNDARY \r\n
1161   //
1162   //   zero or one:
1163   //   Content-Disposition: form-data; name="lsb-release" \r\n \r\n
1164   //   abcdef \r\n
1165   //   BOUNDARY \r\n
1166   //
1167   //   zero or one:
1168   //   Content-Disposition: form-data; name="oom-size" \r\n \r\n
1169   //   1234567890 \r\n
1170   //   BOUNDARY \r\n
1171   //
1172   //   zero or more (up to CrashKeyStorage::num_entries = 64):
1173   //   Content-Disposition: form-data; name=crash-key-name \r\n
1174   //   crash-key-value \r\n
1175   //   BOUNDARY \r\n
1176   //
1177   //   Content-Disposition: form-data; name="dump"; filename="dump" \r\n
1178   //   Content-Type: application/octet-stream \r\n \r\n
1179   //   <dump contents>
1180   //   \r\n BOUNDARY -- \r\n
1181
1182 #if defined(OS_CHROMEOS)
1183   CrashReporterWriter writer(temp_file_fd);
1184 #else
1185   MimeWriter writer(temp_file_fd, mime_boundary);
1186 #endif
1187   {
1188     std::string product_name;
1189     std::string version;
1190
1191     GetBreakpadClient()->GetProductNameAndVersion(&product_name, &version);
1192
1193     writer.AddBoundary();
1194     writer.AddPairString("prod", product_name.c_str());
1195     writer.AddBoundary();
1196     writer.AddPairString("ver", version.c_str());
1197     writer.AddBoundary();
1198     if (info.pid > 0) {
1199       char pid_value_buf[kUint64StringSize];
1200       uint64_t pid_value_len = my_uint64_len(info.pid);
1201       my_uint64tos(pid_value_buf, info.pid, pid_value_len);
1202       static const char pid_key_name[] = "pid";
1203       writer.AddPairData(pid_key_name, sizeof(pid_key_name) - 1,
1204                          pid_value_buf, pid_value_len);
1205       writer.AddBoundary();
1206     }
1207 #if defined(OS_ANDROID)
1208     // Addtional MIME blocks are added for logging on Android devices.
1209     static const char android_build_id[] = "android_build_id";
1210     static const char android_build_fp[] = "android_build_fp";
1211     static const char device[] = "device";
1212     static const char model[] = "model";
1213     static const char brand[] = "brand";
1214     static const char exception_info[] = "exception_info";
1215
1216     base::android::BuildInfo* android_build_info =
1217         base::android::BuildInfo::GetInstance();
1218     writer.AddPairString(
1219         android_build_id, android_build_info->android_build_id());
1220     writer.AddBoundary();
1221     writer.AddPairString(
1222         android_build_fp, android_build_info->android_build_fp());
1223     writer.AddBoundary();
1224     writer.AddPairString(device, android_build_info->device());
1225     writer.AddBoundary();
1226     writer.AddPairString(model, android_build_info->model());
1227     writer.AddBoundary();
1228     writer.AddPairString(brand, android_build_info->brand());
1229     writer.AddBoundary();
1230     if (android_build_info->java_exception_info() != NULL) {
1231       writer.AddPairString(exception_info,
1232                            android_build_info->java_exception_info());
1233       writer.AddBoundary();
1234     }
1235 #endif
1236     writer.Flush();
1237   }
1238
1239   if (info.process_start_time > 0) {
1240     struct kernel_timeval tv;
1241     if (!sys_gettimeofday(&tv, NULL)) {
1242       uint64_t time = kernel_timeval_to_ms(&tv);
1243       if (time > info.process_start_time) {
1244         time -= info.process_start_time;
1245         char time_str[kUint64StringSize];
1246         const unsigned time_len = my_uint64_len(time);
1247         my_uint64tos(time_str, time, time_len);
1248
1249         static const char process_time_msg[] = "ptime";
1250         writer.AddPairData(process_time_msg, sizeof(process_time_msg) - 1,
1251                            time_str, time_len);
1252         writer.AddBoundary();
1253         writer.Flush();
1254       }
1255     }
1256   }
1257
1258   if (info.process_type_length) {
1259     writer.AddPairString("ptype", info.process_type);
1260     writer.AddBoundary();
1261     writer.Flush();
1262   }
1263
1264   if (info.distro_length) {
1265     static const char distro_msg[] = "lsb-release";
1266     writer.AddPairString(distro_msg, info.distro);
1267     writer.AddBoundary();
1268     writer.Flush();
1269   }
1270
1271   if (info.oom_size) {
1272     char oom_size_str[kUint64StringSize];
1273     const unsigned oom_size_len = my_uint64_len(info.oom_size);
1274     my_uint64tos(oom_size_str, info.oom_size, oom_size_len);
1275     static const char oom_size_msg[] = "oom-size";
1276     writer.AddPairData(oom_size_msg, sizeof(oom_size_msg) - 1,
1277                        oom_size_str, oom_size_len);
1278     writer.AddBoundary();
1279     writer.Flush();
1280   }
1281
1282   if (info.crash_keys) {
1283     CrashKeyStorage::Iterator crash_key_iterator(*info.crash_keys);
1284     const CrashKeyStorage::Entry* entry;
1285     while ((entry = crash_key_iterator.Next())) {
1286       writer.AddPairString(entry->key, entry->value);
1287       writer.AddBoundary();
1288       writer.Flush();
1289     }
1290   }
1291
1292   writer.AddFileContents(g_dump_msg, dump_data, dump_size);
1293 #if defined(ADDRESS_SANITIZER)
1294   // Append a multipart boundary and the contents of the AddressSanitizer log.
1295   writer.AddBoundary();
1296   writer.AddFileContents(g_log_msg, log_data, log_size);
1297 #endif
1298   writer.AddEnd();
1299   writer.Flush();
1300
1301   IGNORE_RET(sys_close(temp_file_fd));
1302
1303 #if defined(OS_ANDROID)
1304   if (info.filename) {
1305     int filename_length = my_strlen(info.filename);
1306
1307     // If this was a file, we need to copy it to the right place and use the
1308     // right file name so it gets uploaded by the browser.
1309     const char msg[] = "Output crash dump file:";
1310     WriteLog(msg, sizeof(msg) - 1);
1311     WriteLog(info.filename, filename_length - 1);
1312
1313     char pid_buf[kUint64StringSize];
1314     uint64_t pid_str_length = my_uint64_len(info.pid);
1315     my_uint64tos(pid_buf, info.pid, pid_str_length);
1316
1317     // -1 because we won't need the null terminator on the original filename.
1318     unsigned done_filename_len = filename_length - 1 + pid_str_length;
1319     char* done_filename = reinterpret_cast<char*>(
1320         allocator.Alloc(done_filename_len));
1321     // Rename the file such that the pid is the suffix in order signal to other
1322     // processes that the minidump is complete. The advantage of using the pid
1323     // as the suffix is that it is trivial to associate the minidump with the
1324     // crashed process.
1325     // Finally, note strncpy prevents null terminators from
1326     // being copied. Pad the rest with 0's.
1327     my_strncpy(done_filename, info.filename, done_filename_len);
1328     // Append the suffix a null terminator should be added.
1329     my_strncat(done_filename, pid_buf, pid_str_length);
1330     // Rename the minidump file to signal that it is complete.
1331     if (rename(info.filename, done_filename)) {
1332       const char failed_msg[] = "Failed to rename:";
1333       WriteLog(failed_msg, sizeof(failed_msg) - 1);
1334       WriteLog(info.filename, filename_length - 1);
1335       const char to_msg[] = "to";
1336       WriteLog(to_msg, sizeof(to_msg) - 1);
1337       WriteLog(done_filename, done_filename_len - 1);
1338     }
1339   }
1340 #endif
1341
1342   if (!info.upload)
1343     return;
1344
1345   const pid_t child = sys_fork();
1346   if (!child) {
1347     // Spawned helper process.
1348     //
1349     // This code is called both when a browser is crashing (in which case,
1350     // nothing really matters any more) and when a renderer/plugin crashes, in
1351     // which case we need to continue.
1352     //
1353     // Since we are a multithreaded app, if we were just to fork(), we might
1354     // grab file descriptors which have just been created in another thread and
1355     // hold them open for too long.
1356     //
1357     // Thus, we have to loop and try and close everything.
1358     const int fd = sys_open("/proc/self/fd", O_DIRECTORY | O_RDONLY, 0);
1359     if (fd < 0) {
1360       for (unsigned i = 3; i < 8192; ++i)
1361         IGNORE_RET(sys_close(i));
1362     } else {
1363       google_breakpad::DirectoryReader reader(fd);
1364       const char* name;
1365       while (reader.GetNextEntry(&name)) {
1366         int i;
1367         if (my_strtoui(&i, name) && i > 2 && i != fd)
1368           IGNORE_RET(sys_close(i));
1369         reader.PopEntry();
1370       }
1371
1372       IGNORE_RET(sys_close(fd));
1373     }
1374
1375     IGNORE_RET(sys_setsid());
1376
1377     // Leave one end of a pipe in the upload process and watch for it getting
1378     // closed by the upload process exiting.
1379     int fds[2];
1380     if (sys_pipe(fds) >= 0) {
1381       const pid_t upload_child = sys_fork();
1382       if (!upload_child) {
1383         // Upload process.
1384         IGNORE_RET(sys_close(fds[0]));
1385         IGNORE_RET(sys_dup2(fds[1], 3));
1386         ExecUploadProcessOrTerminate(info, temp_file, mime_boundary, exe_buf,
1387                                      &allocator);
1388       }
1389
1390       // Helper process.
1391       if (upload_child > 0) {
1392         IGNORE_RET(sys_close(fds[1]));
1393         char id_buf[17];  // Crash report IDs are expected to be 16 chars.
1394         ssize_t len = -1;
1395         // Upload should finish in about 10 seconds. Add a few more 500 ms
1396         // internals to account for process startup time.
1397         for (size_t wait_count = 0; wait_count < 24; ++wait_count) {
1398           struct kernel_pollfd poll_fd;
1399           poll_fd.fd = fds[0];
1400           poll_fd.events = POLLIN | POLLPRI | POLLERR;
1401           int ret = sys_poll(&poll_fd, 1, 500);
1402           if (ret < 0) {
1403             // Error
1404             break;
1405           } else if (ret > 0) {
1406             // There is data to read.
1407             len = HANDLE_EINTR(sys_read(fds[0], id_buf, sizeof(id_buf) - 1));
1408             break;
1409           }
1410           // ret == 0 -> timed out, continue waiting.
1411         }
1412         if (len > 0) {
1413           // Write crash dump id to stderr.
1414           id_buf[len] = 0;
1415           static const char msg[] = "\nCrash dump id: ";
1416           WriteLog(msg, sizeof(msg) - 1);
1417           WriteLog(id_buf, my_strlen(id_buf));
1418           WriteLog("\n", 1);
1419
1420           // Write crash dump id to crash log as: seconds_since_epoch,crash_id
1421           struct kernel_timeval tv;
1422           if (g_crash_log_path && !sys_gettimeofday(&tv, NULL)) {
1423             uint64_t time = kernel_timeval_to_ms(&tv) / 1000;
1424             char time_str[kUint64StringSize];
1425             const unsigned time_len = my_uint64_len(time);
1426             my_uint64tos(time_str, time, time_len);
1427
1428             int log_fd = sys_open(g_crash_log_path,
1429                                   O_CREAT | O_WRONLY | O_APPEND,
1430                                   0600);
1431             if (log_fd > 0) {
1432               sys_write(log_fd, time_str, time_len);
1433               sys_write(log_fd, ",", 1);
1434               sys_write(log_fd, id_buf, my_strlen(id_buf));
1435               sys_write(log_fd, "\n", 1);
1436               IGNORE_RET(sys_close(log_fd));
1437             }
1438           }
1439         }
1440         if (sys_waitpid(upload_child, NULL, WNOHANG) == 0) {
1441           // Upload process is still around, kill it.
1442           sys_kill(upload_child, SIGKILL);
1443         }
1444       }
1445     }
1446
1447     // Helper process.
1448     IGNORE_RET(sys_unlink(info.filename));
1449 #if defined(ADDRESS_SANITIZER)
1450     IGNORE_RET(sys_unlink(info.log_filename));
1451 #endif
1452     IGNORE_RET(sys_unlink(temp_file));
1453     sys__exit(0);
1454   }
1455
1456   // Main browser process.
1457   if (child <= 0)
1458     return;
1459   (void) HANDLE_EINTR(sys_waitpid(child, NULL, 0));
1460 }
1461
1462 void InitCrashReporter(const std::string& process_type) {
1463 #if defined(OS_ANDROID)
1464   // This will guarantee that the BuildInfo has been initialized and subsequent
1465   // calls will not require memory allocation.
1466   base::android::BuildInfo::GetInstance();
1467 #endif
1468   // Determine the process type and take appropriate action.
1469   const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
1470   if (parsed_command_line.HasSwitch(switches::kDisableBreakpad))
1471     return;
1472
1473   if (process_type.empty()) {
1474     bool enable_breakpad = GetBreakpadClient()->GetCollectStatsConsent() ||
1475                            GetBreakpadClient()->IsRunningUnattended();
1476     enable_breakpad &=
1477         !parsed_command_line.HasSwitch(switches::kDisableBreakpad);
1478     if (!enable_breakpad) {
1479       enable_breakpad = parsed_command_line.HasSwitch(
1480           switches::kEnableCrashReporterForTesting);
1481     }
1482     if (!enable_breakpad) {
1483       VLOG(1) << "Breakpad disabled";
1484       return;
1485     }
1486
1487     EnableCrashDumping(GetBreakpadClient()->IsRunningUnattended());
1488   } else if (GetBreakpadClient()->EnableBreakpadForProcess(process_type)) {
1489 #if defined(OS_ANDROID)
1490     NOTREACHED() << "Breakpad initialized with InitCrashReporter() instead of "
1491       "InitNonBrowserCrashReporter in " << process_type << " process.";
1492     return;
1493 #else
1494     // We might be chrooted in a zygote or renderer process so we cannot call
1495     // GetCollectStatsConsent because that needs access the the user's home
1496     // dir. Instead, we set a command line flag for these processes.
1497     // Even though plugins are not chrooted, we share the same code path for
1498     // simplicity.
1499     if (!parsed_command_line.HasSwitch(switches::kEnableCrashReporter))
1500       return;
1501     SetClientIdFromCommandLine(parsed_command_line);
1502     EnableNonBrowserCrashDumping();
1503     VLOG(1) << "Non Browser crash dumping enabled for: " << process_type;
1504 #endif  // #if defined(OS_ANDROID)
1505   }
1506
1507   SetProcessStartTime();
1508   g_pid = getpid();
1509
1510   base::debug::SetDumpWithoutCrashingFunction(&DumpProcess);
1511 #if defined(ADDRESS_SANITIZER)
1512   // Register the callback for AddressSanitizer error reporting.
1513   __asan_set_error_report_callback(AsanLinuxBreakpadCallback);
1514 #endif
1515
1516   g_crash_keys = new CrashKeyStorage;
1517   GetBreakpadClient()->RegisterCrashKeys();
1518   base::debug::SetCrashKeyReportingFunctions(
1519       &SetCrashKeyValue, &ClearCrashKey);
1520 }
1521
1522 #if defined(OS_ANDROID)
1523 void InitNonBrowserCrashReporterForAndroid(const std::string& process_type) {
1524   const CommandLine* command_line = CommandLine::ForCurrentProcess();
1525   if (command_line->HasSwitch(switches::kEnableCrashReporter)) {
1526     // On Android we need to provide a FD to the file where the minidump is
1527     // generated as the renderer and browser run with different UIDs
1528     // (preventing the browser from inspecting the renderer process).
1529     int minidump_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
1530         GetBreakpadClient()->GetAndroidMinidumpDescriptor());
1531     if (minidump_fd == base::kInvalidPlatformFileValue) {
1532       NOTREACHED() << "Could not find minidump FD, crash reporting disabled.";
1533     } else {
1534       EnableNonBrowserCrashDumping(process_type, minidump_fd);
1535     }
1536   }
1537 }
1538 #endif  // OS_ANDROID
1539
1540 bool IsCrashReporterEnabled() {
1541   return g_is_crash_reporter_enabled;
1542 }
1543
1544 }  // namespace breakpad