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