Allow the externalfile scheme to be whitelisted as an allowed scheme for component...
[chromium-blink-merge.git] / components / crash / app / breakpad_linux.cc
blobc6fef0da0c0b48a23bfb26ae35e00043f167aa3b
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.
5 // For linux_syscall_support.h. This makes it safe to call embedded system
6 // calls when in seccomp mode.
8 #include "components/crash/app/breakpad_linux.h"
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>
22 #include <algorithm>
23 #include <string>
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 "build/build_config.h"
42 #include "components/crash/app/breakpad_linux_impl.h"
43 #include "components/crash/app/crash_reporter_client.h"
44 #include "content/public/common/content_descriptors.h"
46 #if defined(OS_ANDROID)
47 #include <android/log.h>
48 #include <sys/stat.h>
50 #include "base/android/build_info.h"
51 #include "base/android/path_utils.h"
52 #endif
53 #include "third_party/lss/linux_syscall_support.h"
55 #if defined(ADDRESS_SANITIZER)
56 #include <ucontext.h> // for getcontext().
57 #endif
59 #if defined(OS_ANDROID)
60 #define STAT_STRUCT struct stat
61 #define FSTAT_FUNC fstat
62 #else
63 #define STAT_STRUCT struct kernel_stat
64 #define FSTAT_FUNC sys_fstat
65 #endif
67 // Some versions of gcc are prone to warn about unused return values. In cases
68 // where we either a) know the call cannot fail, or b) there is nothing we
69 // can do when a call fails, we mark the return code as ignored. This avoids
70 // spurious compiler warnings.
71 #define IGNORE_RET(x) do { if (x); } while (0)
73 using crash_reporter::GetCrashReporterClient;
74 using google_breakpad::ExceptionHandler;
75 using google_breakpad::MinidumpDescriptor;
77 namespace breakpad {
79 namespace {
81 #if !defined(OS_CHROMEOS)
82 const char kUploadURL[] = "https://clients2.google.com/cr/report";
83 #endif
85 bool g_is_crash_reporter_enabled = false;
86 uint64_t g_process_start_time = 0;
87 pid_t g_pid = 0;
88 char* g_crash_log_path = NULL;
89 ExceptionHandler* g_breakpad = NULL;
90 ExceptionHandler* g_microdump = NULL;
92 #if defined(ADDRESS_SANITIZER)
93 const char* g_asan_report_str = NULL;
94 #endif
95 #if defined(OS_ANDROID)
96 char* g_process_type = NULL;
97 #endif
99 CrashKeyStorage* g_crash_keys = NULL;
101 // Writes the value |v| as 16 hex characters to the memory pointed at by
102 // |output|.
103 void write_uint64_hex(char* output, uint64_t v) {
104 static const char hextable[] = "0123456789abcdef";
106 for (int i = 15; i >= 0; --i) {
107 output[i] = hextable[v & 15];
108 v >>= 4;
112 // The following helper functions are for calculating uptime.
114 // Converts a struct timeval to milliseconds.
115 uint64_t timeval_to_ms(struct timeval *tv) {
116 uint64_t ret = tv->tv_sec; // Avoid overflow by explicitly using a uint64_t.
117 ret *= 1000;
118 ret += tv->tv_usec / 1000;
119 return ret;
122 // Converts a struct timeval to milliseconds.
123 uint64_t kernel_timeval_to_ms(struct kernel_timeval *tv) {
124 uint64_t ret = tv->tv_sec; // Avoid overflow by explicitly using a uint64_t.
125 ret *= 1000;
126 ret += tv->tv_usec / 1000;
127 return ret;
130 // String buffer size to use to convert a uint64_t to string.
131 const size_t kUint64StringSize = 21;
133 void SetProcessStartTime() {
134 // Set the base process start time value.
135 struct timeval tv;
136 if (!gettimeofday(&tv, NULL))
137 g_process_start_time = timeval_to_ms(&tv);
138 else
139 g_process_start_time = 0;
142 // uint64_t version of my_int_len() from
143 // breakpad/src/common/linux/linux_libc_support.h. Return the length of the
144 // given, non-negative integer when expressed in base 10.
145 unsigned my_uint64_len(uint64_t i) {
146 if (!i)
147 return 1;
149 unsigned len = 0;
150 while (i) {
151 len++;
152 i /= 10;
155 return len;
158 // uint64_t version of my_uitos() from
159 // breakpad/src/common/linux/linux_libc_support.h. Convert a non-negative
160 // integer to a string (not null-terminated).
161 void my_uint64tos(char* output, uint64_t i, unsigned i_len) {
162 for (unsigned index = i_len; index; --index, i /= 10)
163 output[index - 1] = '0' + (i % 10);
166 #if defined(OS_ANDROID)
167 char* my_strncpy(char* dst, const char* src, size_t len) {
168 int i = len;
169 char* p = dst;
170 if (!dst || !src)
171 return dst;
172 while (i != 0 && *src != '\0') {
173 *p++ = *src++;
174 i--;
176 while (i != 0) {
177 *p++ = '\0';
178 i--;
180 return dst;
183 char* my_strncat(char *dest, const char* src, size_t len) {
184 char* ret = dest;
185 while (*dest)
186 dest++;
187 while (len--)
188 if (!(*dest++ = *src++))
189 return ret;
190 *dest = 0;
191 return ret;
193 #endif
195 #if !defined(OS_CHROMEOS)
196 bool my_isxdigit(char c) {
197 return (c >= '0' && c <= '9') || ((c | 0x20) >= 'a' && (c | 0x20) <= 'f');
199 #endif
201 size_t LengthWithoutTrailingSpaces(const char* str, size_t len) {
202 while (len > 0 && str[len - 1] == ' ') {
203 len--;
205 return len;
208 void SetClientIdFromCommandLine(const base::CommandLine& command_line) {
209 // Get the guid from the command line switch.
210 std::string switch_value =
211 command_line.GetSwitchValueASCII(switches::kEnableCrashReporter);
212 GetCrashReporterClient()->SetCrashReporterClientIdFromGUID(switch_value);
215 // MIME substrings.
216 #if defined(OS_CHROMEOS)
217 const char g_sep[] = ":";
218 #endif
219 const char g_rn[] = "\r\n";
220 const char g_form_data_msg[] = "Content-Disposition: form-data; name=\"";
221 const char g_quote_msg[] = "\"";
222 const char g_dashdash_msg[] = "--";
223 const char g_dump_msg[] = "upload_file_minidump\"; filename=\"dump\"";
224 #if defined(ADDRESS_SANITIZER)
225 const char g_log_msg[] = "upload_file_log\"; filename=\"log\"";
226 #endif
227 const char g_content_type_msg[] = "Content-Type: application/octet-stream";
229 // MimeWriter manages an iovec for writing MIMEs to a file.
230 class MimeWriter {
231 public:
232 static const int kIovCapacity = 30;
233 static const size_t kMaxCrashChunkSize = 64;
235 MimeWriter(int fd, const char* const mime_boundary);
236 ~MimeWriter();
238 // Append boundary.
239 virtual void AddBoundary();
241 // Append end of file boundary.
242 virtual void AddEnd();
244 // Append key/value pair with specified sizes.
245 virtual void AddPairData(const char* msg_type,
246 size_t msg_type_size,
247 const char* msg_data,
248 size_t msg_data_size);
250 // Append key/value pair.
251 void AddPairString(const char* msg_type,
252 const char* msg_data) {
253 AddPairData(msg_type, my_strlen(msg_type), msg_data, my_strlen(msg_data));
256 // Append key/value pair, splitting value into chunks no larger than
257 // |chunk_size|. |chunk_size| cannot be greater than |kMaxCrashChunkSize|.
258 // The msg_type string will have a counter suffix to distinguish each chunk.
259 virtual void AddPairDataInChunks(const char* msg_type,
260 size_t msg_type_size,
261 const char* msg_data,
262 size_t msg_data_size,
263 size_t chunk_size,
264 bool strip_trailing_spaces);
266 // Add binary file contents to be uploaded with the specified filename.
267 virtual void AddFileContents(const char* filename_msg,
268 uint8_t* file_data,
269 size_t file_size);
271 // Flush any pending iovecs to the output file.
272 void Flush() {
273 IGNORE_RET(sys_writev(fd_, iov_, iov_index_));
274 iov_index_ = 0;
277 protected:
278 void AddItem(const void* base, size_t size);
279 // Minor performance trade-off for easier-to-maintain code.
280 void AddString(const char* str) {
281 AddItem(str, my_strlen(str));
283 void AddItemWithoutTrailingSpaces(const void* base, size_t size);
285 struct kernel_iovec iov_[kIovCapacity];
286 int iov_index_;
288 // Output file descriptor.
289 int fd_;
291 const char* const mime_boundary_;
293 private:
294 DISALLOW_COPY_AND_ASSIGN(MimeWriter);
297 MimeWriter::MimeWriter(int fd, const char* const mime_boundary)
298 : iov_index_(0),
299 fd_(fd),
300 mime_boundary_(mime_boundary) {
303 MimeWriter::~MimeWriter() {
306 void MimeWriter::AddBoundary() {
307 AddString(mime_boundary_);
308 AddString(g_rn);
311 void MimeWriter::AddEnd() {
312 AddString(mime_boundary_);
313 AddString(g_dashdash_msg);
314 AddString(g_rn);
317 void MimeWriter::AddPairData(const char* msg_type,
318 size_t msg_type_size,
319 const char* msg_data,
320 size_t msg_data_size) {
321 AddString(g_form_data_msg);
322 AddItem(msg_type, msg_type_size);
323 AddString(g_quote_msg);
324 AddString(g_rn);
325 AddString(g_rn);
326 AddItem(msg_data, msg_data_size);
327 AddString(g_rn);
330 void MimeWriter::AddPairDataInChunks(const char* msg_type,
331 size_t msg_type_size,
332 const char* msg_data,
333 size_t msg_data_size,
334 size_t chunk_size,
335 bool strip_trailing_spaces) {
336 if (chunk_size > kMaxCrashChunkSize)
337 return;
339 unsigned i = 0;
340 size_t done = 0, msg_length = msg_data_size;
342 while (msg_length) {
343 char num[kUint64StringSize];
344 const unsigned num_len = my_uint_len(++i);
345 my_uitos(num, i, num_len);
347 size_t chunk_len = std::min(chunk_size, msg_length);
349 AddString(g_form_data_msg);
350 AddItem(msg_type, msg_type_size);
351 AddItem(num, num_len);
352 AddString(g_quote_msg);
353 AddString(g_rn);
354 AddString(g_rn);
355 if (strip_trailing_spaces) {
356 AddItemWithoutTrailingSpaces(msg_data + done, chunk_len);
357 } else {
358 AddItem(msg_data + done, chunk_len);
360 AddString(g_rn);
361 AddBoundary();
362 Flush();
364 done += chunk_len;
365 msg_length -= chunk_len;
369 void MimeWriter::AddFileContents(const char* filename_msg, uint8_t* file_data,
370 size_t file_size) {
371 AddString(g_form_data_msg);
372 AddString(filename_msg);
373 AddString(g_rn);
374 AddString(g_content_type_msg);
375 AddString(g_rn);
376 AddString(g_rn);
377 AddItem(file_data, file_size);
378 AddString(g_rn);
381 void MimeWriter::AddItem(const void* base, size_t size) {
382 // Check if the iovec is full and needs to be flushed to output file.
383 if (iov_index_ == kIovCapacity) {
384 Flush();
386 iov_[iov_index_].iov_base = const_cast<void*>(base);
387 iov_[iov_index_].iov_len = size;
388 ++iov_index_;
391 void MimeWriter::AddItemWithoutTrailingSpaces(const void* base, size_t size) {
392 AddItem(base, LengthWithoutTrailingSpaces(static_cast<const char*>(base),
393 size));
396 #if defined(OS_CHROMEOS)
397 // This subclass is used on Chromium OS to report crashes in a format easy for
398 // the central crash reporting facility to understand.
399 // Format is <name>:<data length in decimal>:<data>
400 class CrashReporterWriter : public MimeWriter {
401 public:
402 explicit CrashReporterWriter(int fd);
404 void AddBoundary() override;
406 void AddEnd() override;
408 void AddPairData(const char* msg_type,
409 size_t msg_type_size,
410 const char* msg_data,
411 size_t msg_data_size) override;
413 void AddPairDataInChunks(const char* msg_type,
414 size_t msg_type_size,
415 const char* msg_data,
416 size_t msg_data_size,
417 size_t chunk_size,
418 bool strip_trailing_spaces) override;
420 void AddFileContents(const char* filename_msg,
421 uint8_t* file_data,
422 size_t file_size) override;
424 private:
425 DISALLOW_COPY_AND_ASSIGN(CrashReporterWriter);
429 CrashReporterWriter::CrashReporterWriter(int fd) : MimeWriter(fd, "") {}
431 // No-ops.
432 void CrashReporterWriter::AddBoundary() {}
433 void CrashReporterWriter::AddEnd() {}
435 void CrashReporterWriter::AddPairData(const char* msg_type,
436 size_t msg_type_size,
437 const char* msg_data,
438 size_t msg_data_size) {
439 char data[kUint64StringSize];
440 const unsigned data_len = my_uint_len(msg_data_size);
441 my_uitos(data, msg_data_size, data_len);
443 AddItem(msg_type, msg_type_size);
444 AddString(g_sep);
445 AddItem(data, data_len);
446 AddString(g_sep);
447 AddItem(msg_data, msg_data_size);
448 Flush();
451 void CrashReporterWriter::AddPairDataInChunks(const char* msg_type,
452 size_t msg_type_size,
453 const char* msg_data,
454 size_t msg_data_size,
455 size_t chunk_size,
456 bool strip_trailing_spaces) {
457 if (chunk_size > kMaxCrashChunkSize)
458 return;
460 unsigned i = 0;
461 size_t done = 0;
462 size_t msg_length = msg_data_size;
464 while (msg_length) {
465 char num[kUint64StringSize];
466 const unsigned num_len = my_uint_len(++i);
467 my_uitos(num, i, num_len);
469 size_t chunk_len = std::min(chunk_size, msg_length);
471 size_t write_len = chunk_len;
472 if (strip_trailing_spaces) {
473 // Take care of this here because we need to know the exact length of
474 // what is going to be written.
475 write_len = LengthWithoutTrailingSpaces(msg_data + done, write_len);
478 char data[kUint64StringSize];
479 const unsigned data_len = my_uint_len(write_len);
480 my_uitos(data, write_len, data_len);
482 AddItem(msg_type, msg_type_size);
483 AddItem(num, num_len);
484 AddString(g_sep);
485 AddItem(data, data_len);
486 AddString(g_sep);
487 AddItem(msg_data + done, write_len);
488 Flush();
490 done += chunk_len;
491 msg_length -= chunk_len;
495 void CrashReporterWriter::AddFileContents(const char* filename_msg,
496 uint8_t* file_data,
497 size_t file_size) {
498 char data[kUint64StringSize];
499 const unsigned data_len = my_uint_len(file_size);
500 my_uitos(data, file_size, data_len);
502 AddString(filename_msg);
503 AddString(g_sep);
504 AddItem(data, data_len);
505 AddString(g_sep);
506 AddItem(file_data, file_size);
507 Flush();
509 #endif // defined(OS_CHROMEOS)
511 void DumpProcess() {
512 if (g_breakpad)
513 g_breakpad->WriteMinidump();
515 // If microdumps are enabled write also a microdump on the system log.
516 if (g_microdump)
517 g_microdump->WriteMinidump();
520 #if defined(OS_ANDROID)
521 const char kGoogleBreakpad[] = "google-breakpad";
522 #endif
524 size_t WriteLog(const char* buf, size_t nbytes) {
525 #if defined(OS_ANDROID)
526 return __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad, buf);
527 #else
528 return sys_write(2, buf, nbytes);
529 #endif
532 size_t WriteNewline() {
533 return WriteLog("\n", 1);
536 #if defined(OS_ANDROID)
537 void AndroidLogWriteHorizontalRule() {
538 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
539 "### ### ### ### ### ### ### ### ### ### ### ### ###");
542 // Android's native crash handler outputs a diagnostic tombstone to the device
543 // log. By returning false from the HandlerCallbacks, breakpad will reinstall
544 // the previous (i.e. native) signal handlers before returning from its own
545 // handler. A Chrome build fingerprint is written to the log, so that the
546 // specific build of Chrome and the location of the archived Chrome symbols can
547 // be determined directly from it.
548 bool FinalizeCrashDoneAndroid(bool is_browser_process) {
549 base::android::BuildInfo* android_build_info =
550 base::android::BuildInfo::GetInstance();
552 AndroidLogWriteHorizontalRule();
553 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
554 "Chrome build fingerprint:");
555 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
556 android_build_info->package_version_name());
557 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
558 android_build_info->package_version_code());
559 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
560 CHROME_BUILD_ID);
561 AndroidLogWriteHorizontalRule();
563 if (!is_browser_process &&
564 android_build_info->sdk_int() >= 18 &&
565 my_strcmp(android_build_info->build_type(), "eng") != 0 &&
566 my_strcmp(android_build_info->build_type(), "userdebug") != 0) {
567 // On JB MR2 and later, the system crash handler displays a dialog. For
568 // renderer crashes, this is a bad user experience and so this is disabled
569 // for user builds of Android.
570 // TODO(cjhopman): There should be some way to recover the crash stack from
571 // non-uploading user clients. See http://crbug.com/273706.
572 __android_log_write(ANDROID_LOG_WARN,
573 kGoogleBreakpad,
574 "Tombstones are disabled on JB MR2+ user builds.");
575 AndroidLogWriteHorizontalRule();
576 return true;
578 return false;
580 #endif
582 bool CrashDone(const MinidumpDescriptor& minidump,
583 const bool upload,
584 const bool succeeded) {
585 // WARNING: this code runs in a compromised context. It may not call into
586 // libc nor allocate memory normally.
587 if (!succeeded) {
588 const char msg[] = "Failed to generate minidump.";
589 WriteLog(msg, sizeof(msg) - 1);
590 return false;
593 DCHECK(!minidump.IsFD());
595 BreakpadInfo info = {0};
596 info.filename = minidump.path();
597 info.fd = minidump.fd();
598 #if defined(ADDRESS_SANITIZER)
599 google_breakpad::PageAllocator allocator;
600 const size_t log_path_len = my_strlen(minidump.path());
601 char* log_path = reinterpret_cast<char*>(allocator.Alloc(log_path_len + 1));
602 my_memcpy(log_path, minidump.path(), log_path_len);
603 my_memcpy(log_path + log_path_len - 4, ".log", 4);
604 log_path[log_path_len] = '\0';
605 info.log_filename = log_path;
606 #endif
607 info.process_type = "browser";
608 info.process_type_length = 7;
609 info.distro = base::g_linux_distro;
610 info.distro_length = my_strlen(base::g_linux_distro);
611 info.upload = upload;
612 info.process_start_time = g_process_start_time;
613 info.oom_size = base::g_oom_size;
614 info.pid = g_pid;
615 info.crash_keys = g_crash_keys;
616 HandleCrashDump(info);
617 #if defined(OS_ANDROID)
618 return FinalizeCrashDoneAndroid(true /* is_browser_process */);
619 #else
620 return true;
621 #endif
624 // Wrapper function, do not add more code here.
625 bool CrashDoneNoUpload(const MinidumpDescriptor& minidump,
626 void* context,
627 bool succeeded) {
628 return CrashDone(minidump, false, succeeded);
631 #if !defined(OS_ANDROID)
632 // Wrapper function, do not add more code here.
633 bool CrashDoneUpload(const MinidumpDescriptor& minidump,
634 void* context,
635 bool succeeded) {
636 return CrashDone(minidump, true, succeeded);
638 #endif
640 #if defined(ADDRESS_SANITIZER)
641 extern "C"
642 void __asan_set_error_report_callback(void (*cb)(const char*));
644 extern "C"
645 void AsanLinuxBreakpadCallback(const char* report) {
646 g_asan_report_str = report;
647 // Send minidump here.
648 g_breakpad->SimulateSignalDelivery(SIGKILL);
650 #endif
652 void EnableCrashDumping(bool unattended) {
653 g_is_crash_reporter_enabled = true;
655 base::FilePath tmp_path("/tmp");
656 PathService::Get(base::DIR_TEMP, &tmp_path);
658 base::FilePath dumps_path(tmp_path);
659 if (GetCrashReporterClient()->GetCrashDumpLocation(&dumps_path)) {
660 base::FilePath logfile =
661 dumps_path.Append(GetCrashReporterClient()->GetReporterLogFilename());
662 std::string logfile_str = logfile.value();
663 const size_t crash_log_path_len = logfile_str.size() + 1;
664 g_crash_log_path = new char[crash_log_path_len];
665 strncpy(g_crash_log_path, logfile_str.c_str(), crash_log_path_len);
667 DCHECK(!g_breakpad);
668 MinidumpDescriptor minidump_descriptor(dumps_path.value());
669 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
670 switches::kFullMemoryCrashReport)) {
671 minidump_descriptor.set_size_limit(-1); // unlimited.
672 } else {
673 minidump_descriptor.set_size_limit(kMaxMinidumpFileSize);
675 #if defined(OS_ANDROID)
676 unattended = true; // Android never uploads directly.
677 #endif
678 if (unattended) {
679 g_breakpad = new ExceptionHandler(
680 minidump_descriptor,
681 NULL,
682 CrashDoneNoUpload,
683 NULL,
684 true, // Install handlers.
685 -1); // Server file descriptor. -1 for in-process.
686 return;
689 #if !defined(OS_ANDROID)
690 // Attended mode
691 g_breakpad = new ExceptionHandler(
692 minidump_descriptor,
693 NULL,
694 CrashDoneUpload,
695 NULL,
696 true, // Install handlers.
697 -1); // Server file descriptor. -1 for in-process.
698 #endif
701 #if defined(OS_ANDROID)
702 bool MicrodumpCrashDone(const MinidumpDescriptor& minidump,
703 void* context,
704 bool succeeded) {
705 // WARNING: this code runs in a compromised context. It may not call into
706 // libc nor allocate memory normally.
707 if (!succeeded) {
708 static const char msg[] = "Microdump crash handler failed.\n";
709 WriteLog(msg, sizeof(msg) - 1);
710 return false;
713 const bool is_browser_process = (context != NULL);
714 return FinalizeCrashDoneAndroid(is_browser_process);
717 // The microdump handler does NOT upload anything. It just dumps out on the
718 // system console (logcat) a restricted and serialized variant of a minidump.
719 // See crbug.com/410294 for more details.
720 void InitMicrodumpCrashHandlerIfNecessary(const std::string& process_type) {
721 #if (!defined(ARCH_CPU_ARMEL) && !defined(ARCH_CPU_ARM64))
722 // TODO(primiano): For the moment microdumps are enabled only on arm (32/64).
723 // Extend support to other architectures (requires some breakpad changes).
724 return;
725 #endif
727 if (!GetCrashReporterClient()->ShouldEnableBreakpadMicrodumps())
728 return;
730 VLOG(1) << "Enabling microdumps crash handler (process_type:"
731 << process_type << ")";
732 DCHECK(!g_microdump);
733 g_microdump = new ExceptionHandler(
734 MinidumpDescriptor(MinidumpDescriptor::kMicrodumpOnConsole),
735 NULL,
736 MicrodumpCrashDone,
737 reinterpret_cast<void*>(process_type.empty()),
738 true, // Install handlers.
739 -1); // Server file descriptor. -1 for in-process.
740 return;
743 bool CrashDoneInProcessNoUpload(
744 const google_breakpad::MinidumpDescriptor& descriptor,
745 void* context,
746 const bool succeeded) {
747 // WARNING: this code runs in a compromised context. It may not call into
748 // libc nor allocate memory normally.
749 if (!succeeded) {
750 static const char msg[] = "Crash dump generation failed.\n";
751 WriteLog(msg, sizeof(msg) - 1);
752 return false;
755 // Start constructing the message to send to the browser.
756 BreakpadInfo info = {0};
757 info.filename = NULL;
758 info.fd = descriptor.fd();
759 info.process_type = g_process_type;
760 info.process_type_length = my_strlen(g_process_type);
761 info.distro = NULL;
762 info.distro_length = 0;
763 info.upload = false;
764 info.process_start_time = g_process_start_time;
765 info.pid = g_pid;
766 info.crash_keys = g_crash_keys;
767 HandleCrashDump(info);
768 return FinalizeCrashDoneAndroid(false /* is_browser_process */);
771 void EnableNonBrowserCrashDumping(const std::string& process_type,
772 int minidump_fd) {
773 // This will guarantee that the BuildInfo has been initialized and subsequent
774 // calls will not require memory allocation.
775 base::android::BuildInfo::GetInstance();
776 SetClientIdFromCommandLine(*base::CommandLine::ForCurrentProcess());
778 // On Android, the current sandboxing uses process isolation, in which the
779 // child process runs with a different UID. That breaks the normal crash
780 // reporting where the browser process generates the minidump by inspecting
781 // the child process. This is because the browser process now does not have
782 // the permission to access the states of the child process (as it has a
783 // different UID).
784 // TODO(jcivelli): http://b/issue?id=6776356 we should use a watchdog
785 // process forked from the renderer process that generates the minidump.
786 if (minidump_fd == -1) {
787 LOG(ERROR) << "Minidump file descriptor not found, crash reporting will "
788 " not work.";
789 return;
791 SetProcessStartTime();
792 g_pid = getpid();
794 g_is_crash_reporter_enabled = true;
795 // Save the process type (it is leaked).
796 const size_t process_type_len = process_type.size() + 1;
797 g_process_type = new char[process_type_len];
798 strncpy(g_process_type, process_type.c_str(), process_type_len);
799 new google_breakpad::ExceptionHandler(MinidumpDescriptor(minidump_fd),
800 NULL, CrashDoneInProcessNoUpload, NULL, true, -1);
802 #else
803 // Non-Browser = Extension, Gpu, Plugins, Ppapi and Renderer
804 class NonBrowserCrashHandler : public google_breakpad::CrashGenerationClient {
805 public:
806 NonBrowserCrashHandler()
807 : server_fd_(base::GlobalDescriptors::GetInstance()->Get(
808 kCrashDumpSignal)) {
811 ~NonBrowserCrashHandler() override {}
813 bool RequestDump(const void* crash_context,
814 size_t crash_context_size) override {
815 int fds[2] = { -1, -1 };
816 if (sys_socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
817 static const char msg[] = "Failed to create socket for crash dumping.\n";
818 WriteLog(msg, sizeof(msg) - 1);
819 return false;
822 // Start constructing the message to send to the browser.
823 char b; // Dummy variable for sys_read below.
824 const char* b_addr = &b; // Get the address of |b| so we can create the
825 // expected /proc/[pid]/syscall content in the
826 // browser to convert namespace tids.
828 // The length of the control message:
829 static const unsigned kControlMsgSize = sizeof(int);
830 static const unsigned kControlMsgSpaceSize = CMSG_SPACE(kControlMsgSize);
831 static const unsigned kControlMsgLenSize = CMSG_LEN(kControlMsgSize);
833 struct kernel_msghdr msg;
834 my_memset(&msg, 0, sizeof(struct kernel_msghdr));
835 struct kernel_iovec iov[kCrashIovSize];
836 iov[0].iov_base = const_cast<void*>(crash_context);
837 iov[0].iov_len = crash_context_size;
838 iov[1].iov_base = &b_addr;
839 iov[1].iov_len = sizeof(b_addr);
840 iov[2].iov_base = &fds[0];
841 iov[2].iov_len = sizeof(fds[0]);
842 iov[3].iov_base = &g_process_start_time;
843 iov[3].iov_len = sizeof(g_process_start_time);
844 iov[4].iov_base = &base::g_oom_size;
845 iov[4].iov_len = sizeof(base::g_oom_size);
846 google_breakpad::SerializedNonAllocatingMap* serialized_map;
847 iov[5].iov_len = g_crash_keys->Serialize(
848 const_cast<const google_breakpad::SerializedNonAllocatingMap**>(
849 &serialized_map));
850 iov[5].iov_base = serialized_map;
851 #if !defined(ADDRESS_SANITIZER)
852 static_assert(5 == kCrashIovSize - 1, "kCrashIovSize should equal 6");
853 #else
854 iov[6].iov_base = const_cast<char*>(g_asan_report_str);
855 iov[6].iov_len = kMaxAsanReportSize + 1;
856 static_assert(6 == kCrashIovSize - 1, "kCrashIovSize should equal 7");
857 #endif
859 msg.msg_iov = iov;
860 msg.msg_iovlen = kCrashIovSize;
861 char cmsg[kControlMsgSpaceSize];
862 my_memset(cmsg, 0, kControlMsgSpaceSize);
863 msg.msg_control = cmsg;
864 msg.msg_controllen = sizeof(cmsg);
866 struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg);
867 hdr->cmsg_level = SOL_SOCKET;
868 hdr->cmsg_type = SCM_RIGHTS;
869 hdr->cmsg_len = kControlMsgLenSize;
870 ((int*)CMSG_DATA(hdr))[0] = fds[1];
872 if (HANDLE_EINTR(sys_sendmsg(server_fd_, &msg, 0)) < 0) {
873 static const char errmsg[] = "Failed to tell parent about crash.\n";
874 WriteLog(errmsg, sizeof(errmsg) - 1);
875 IGNORE_RET(sys_close(fds[0]));
876 IGNORE_RET(sys_close(fds[1]));
877 return false;
879 IGNORE_RET(sys_close(fds[1]));
881 if (HANDLE_EINTR(sys_read(fds[0], &b, 1)) != 1) {
882 static const char errmsg[] = "Parent failed to complete crash dump.\n";
883 WriteLog(errmsg, sizeof(errmsg) - 1);
885 IGNORE_RET(sys_close(fds[0]));
887 return true;
890 private:
891 // The pipe FD to the browser process, which will handle the crash dumping.
892 const int server_fd_;
894 DISALLOW_COPY_AND_ASSIGN(NonBrowserCrashHandler);
897 void EnableNonBrowserCrashDumping() {
898 g_is_crash_reporter_enabled = true;
899 // We deliberately leak this object.
900 DCHECK(!g_breakpad);
902 g_breakpad = new ExceptionHandler(
903 MinidumpDescriptor("/tmp"), // Unused but needed or Breakpad will assert.
904 NULL,
905 NULL,
906 NULL,
907 true,
908 -1);
909 g_breakpad->set_crash_generation_client(new NonBrowserCrashHandler());
911 #endif // defined(OS_ANDROID)
913 void SetCrashKeyValue(const base::StringPiece& key,
914 const base::StringPiece& value) {
915 g_crash_keys->SetKeyValue(key.data(), value.data());
918 void ClearCrashKey(const base::StringPiece& key) {
919 g_crash_keys->RemoveKey(key.data());
922 // GetCrashReporterClient() cannot call any Set methods until after
923 // InitCrashKeys().
924 void InitCrashKeys() {
925 g_crash_keys = new CrashKeyStorage;
926 GetCrashReporterClient()->RegisterCrashKeys();
927 base::debug::SetCrashKeyReportingFunctions(&SetCrashKeyValue, &ClearCrashKey);
930 // Miscellaneous initialization functions to call after Breakpad has been
931 // enabled.
932 void PostEnableBreakpadInitialization() {
933 SetProcessStartTime();
934 g_pid = getpid();
936 base::debug::SetDumpWithoutCrashingFunction(&DumpProcess);
937 #if defined(ADDRESS_SANITIZER)
938 // Register the callback for AddressSanitizer error reporting.
939 __asan_set_error_report_callback(AsanLinuxBreakpadCallback);
940 #endif
943 } // namespace
945 void LoadDataFromFD(google_breakpad::PageAllocator& allocator,
946 int fd, bool close_fd, uint8_t** file_data, size_t* size) {
947 STAT_STRUCT st;
948 if (FSTAT_FUNC(fd, &st) != 0) {
949 static const char msg[] = "Cannot upload crash dump: stat failed\n";
950 WriteLog(msg, sizeof(msg) - 1);
951 if (close_fd)
952 IGNORE_RET(sys_close(fd));
953 return;
956 *file_data = reinterpret_cast<uint8_t*>(allocator.Alloc(st.st_size));
957 if (!(*file_data)) {
958 static const char msg[] = "Cannot upload crash dump: cannot alloc\n";
959 WriteLog(msg, sizeof(msg) - 1);
960 if (close_fd)
961 IGNORE_RET(sys_close(fd));
962 return;
964 my_memset(*file_data, 0xf, st.st_size);
966 *size = st.st_size;
967 int byte_read = sys_read(fd, *file_data, *size);
968 if (byte_read == -1) {
969 static const char msg[] = "Cannot upload crash dump: read failed\n";
970 WriteLog(msg, sizeof(msg) - 1);
971 if (close_fd)
972 IGNORE_RET(sys_close(fd));
973 return;
976 if (close_fd)
977 IGNORE_RET(sys_close(fd));
980 void LoadDataFromFile(google_breakpad::PageAllocator& allocator,
981 const char* filename,
982 int* fd, uint8_t** file_data, size_t* size) {
983 // WARNING: this code runs in a compromised context. It may not call into
984 // libc nor allocate memory normally.
985 *fd = sys_open(filename, O_RDONLY, 0);
986 *size = 0;
988 if (*fd < 0) {
989 static const char msg[] = "Cannot upload crash dump: failed to open\n";
990 WriteLog(msg, sizeof(msg) - 1);
991 return;
994 LoadDataFromFD(allocator, *fd, true, file_data, size);
997 // Spawn the appropriate upload process for the current OS:
998 // - generic Linux invokes wget.
999 // - ChromeOS invokes crash_reporter.
1000 // |dumpfile| is the path to the dump data file.
1001 // |mime_boundary| is only used on Linux.
1002 // |exe_buf| is only used on CrOS and is the crashing process' name.
1003 void ExecUploadProcessOrTerminate(const BreakpadInfo& info,
1004 const char* dumpfile,
1005 const char* mime_boundary,
1006 const char* exe_buf,
1007 google_breakpad::PageAllocator* allocator) {
1008 #if defined(OS_CHROMEOS)
1009 // CrOS uses crash_reporter instead of wget to report crashes,
1010 // it needs to know where the crash dump lives and the pid and uid of the
1011 // crashing process.
1012 static const char kCrashReporterBinary[] = "/sbin/crash_reporter";
1014 char pid_buf[kUint64StringSize];
1015 uint64_t pid_str_length = my_uint64_len(info.pid);
1016 my_uint64tos(pid_buf, info.pid, pid_str_length);
1017 pid_buf[pid_str_length] = '\0';
1019 char uid_buf[kUint64StringSize];
1020 uid_t uid = geteuid();
1021 uint64_t uid_str_length = my_uint64_len(uid);
1022 my_uint64tos(uid_buf, uid, uid_str_length);
1023 uid_buf[uid_str_length] = '\0';
1025 const char kChromeFlag[] = "--chrome=";
1026 size_t buf_len = my_strlen(dumpfile) + sizeof(kChromeFlag);
1027 char* chrome_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
1028 chrome_flag[0] = '\0';
1029 my_strlcat(chrome_flag, kChromeFlag, buf_len);
1030 my_strlcat(chrome_flag, dumpfile, buf_len);
1032 const char kPidFlag[] = "--pid=";
1033 buf_len = my_strlen(pid_buf) + sizeof(kPidFlag);
1034 char* pid_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
1035 pid_flag[0] = '\0';
1036 my_strlcat(pid_flag, kPidFlag, buf_len);
1037 my_strlcat(pid_flag, pid_buf, buf_len);
1039 const char kUidFlag[] = "--uid=";
1040 buf_len = my_strlen(uid_buf) + sizeof(kUidFlag);
1041 char* uid_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
1042 uid_flag[0] = '\0';
1043 my_strlcat(uid_flag, kUidFlag, buf_len);
1044 my_strlcat(uid_flag, uid_buf, buf_len);
1046 const char kExeBuf[] = "--exe=";
1047 buf_len = my_strlen(exe_buf) + sizeof(kExeBuf);
1048 char* exe_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
1049 exe_flag[0] = '\0';
1050 my_strlcat(exe_flag, kExeBuf, buf_len);
1051 my_strlcat(exe_flag, exe_buf, buf_len);
1053 const char* args[] = {
1054 kCrashReporterBinary,
1055 chrome_flag,
1056 pid_flag,
1057 uid_flag,
1058 exe_flag,
1059 NULL,
1061 static const char msg[] = "Cannot upload crash dump: cannot exec "
1062 "/sbin/crash_reporter\n";
1063 #else
1064 // The --header argument to wget looks like:
1065 // --header=Content-Type: multipart/form-data; boundary=XYZ
1066 // where the boundary has two fewer leading '-' chars
1067 static const char header_msg[] =
1068 "--header=Content-Type: multipart/form-data; boundary=";
1069 char* const header = reinterpret_cast<char*>(allocator->Alloc(
1070 sizeof(header_msg) - 1 + strlen(mime_boundary) - 2 + 1));
1071 memcpy(header, header_msg, sizeof(header_msg) - 1);
1072 memcpy(header + sizeof(header_msg) - 1, mime_boundary + 2,
1073 strlen(mime_boundary) - 2);
1074 // We grab the NUL byte from the end of |mime_boundary|.
1076 // The --post-file argument to wget looks like:
1077 // --post-file=/tmp/...
1078 static const char post_file_msg[] = "--post-file=";
1079 char* const post_file = reinterpret_cast<char*>(allocator->Alloc(
1080 sizeof(post_file_msg) - 1 + strlen(dumpfile) + 1));
1081 memcpy(post_file, post_file_msg, sizeof(post_file_msg) - 1);
1082 memcpy(post_file + sizeof(post_file_msg) - 1, dumpfile, strlen(dumpfile));
1084 static const char kWgetBinary[] = "/usr/bin/wget";
1085 const char* args[] = {
1086 kWgetBinary,
1087 header,
1088 post_file,
1089 kUploadURL,
1090 "--timeout=10", // Set a timeout so we don't hang forever.
1091 "--tries=1", // Don't retry if the upload fails.
1092 "-O", // output reply to fd 3
1093 "/dev/fd/3",
1094 NULL,
1096 static const char msg[] = "Cannot upload crash dump: cannot exec "
1097 "/usr/bin/wget\n";
1098 #endif
1099 execve(args[0], const_cast<char**>(args), environ);
1100 WriteLog(msg, sizeof(msg) - 1);
1101 sys__exit(1);
1104 // Runs in the helper process to wait for the upload process running
1105 // ExecUploadProcessOrTerminate() to finish. Returns the number of bytes written
1106 // to |fd| and save the written contents to |buf|.
1107 // |buf| needs to be big enough to hold |bytes_to_read| + 1 characters.
1108 size_t WaitForCrashReportUploadProcess(int fd, size_t bytes_to_read,
1109 char* buf) {
1110 size_t bytes_read = 0;
1112 // Upload should finish in about 10 seconds. Add a few more 500 ms
1113 // internals to account for process startup time.
1114 for (size_t wait_count = 0; wait_count < 24; ++wait_count) {
1115 struct kernel_pollfd poll_fd;
1116 poll_fd.fd = fd;
1117 poll_fd.events = POLLIN | POLLPRI | POLLERR;
1118 int ret = sys_poll(&poll_fd, 1, 500);
1119 if (ret < 0) {
1120 // Error
1121 break;
1122 } else if (ret > 0) {
1123 // There is data to read.
1124 ssize_t len = HANDLE_EINTR(
1125 sys_read(fd, buf + bytes_read, bytes_to_read - bytes_read));
1126 if (len < 0)
1127 break;
1128 bytes_read += len;
1129 if (bytes_read == bytes_to_read)
1130 break;
1132 // |ret| == 0 -> timed out, continue waiting.
1133 // or |bytes_read| < |bytes_to_read| still, keep reading.
1135 buf[bytes_to_read] = 0; // Always NUL terminate the buffer.
1136 return bytes_read;
1139 // |buf| should be |expected_len| + 1 characters in size and NULL terminated.
1140 bool IsValidCrashReportId(const char* buf, size_t bytes_read,
1141 size_t expected_len) {
1142 if (bytes_read != expected_len)
1143 return false;
1144 #if defined(OS_CHROMEOS)
1145 return my_strcmp(buf, "_sys_cr_finished") == 0;
1146 #else
1147 for (size_t i = 0; i < bytes_read; ++i) {
1148 if (!my_isxdigit(buf[i]))
1149 return false;
1151 return true;
1152 #endif
1155 // |buf| should be |expected_len| + 1 characters in size and NULL terminated.
1156 void HandleCrashReportId(const char* buf, size_t bytes_read,
1157 size_t expected_len) {
1158 WriteNewline();
1159 if (!IsValidCrashReportId(buf, bytes_read, expected_len)) {
1160 #if defined(OS_CHROMEOS)
1161 static const char msg[] =
1162 "System crash-reporter failed to process crash report.";
1163 #else
1164 static const char msg[] = "Failed to get crash dump id.";
1165 #endif
1166 WriteLog(msg, sizeof(msg) - 1);
1167 WriteNewline();
1169 static const char id_msg[] = "Report Id: ";
1170 WriteLog(id_msg, sizeof(id_msg) - 1);
1171 WriteLog(buf, bytes_read);
1172 WriteNewline();
1173 return;
1176 #if defined(OS_CHROMEOS)
1177 static const char msg[] = "Crash dump received by crash_reporter\n";
1178 WriteLog(msg, sizeof(msg) - 1);
1179 #else
1180 // Write crash dump id to stderr.
1181 static const char msg[] = "Crash dump id: ";
1182 WriteLog(msg, sizeof(msg) - 1);
1183 WriteLog(buf, my_strlen(buf));
1184 WriteNewline();
1186 // Write crash dump id to crash log as: seconds_since_epoch,crash_id
1187 struct kernel_timeval tv;
1188 if (g_crash_log_path && !sys_gettimeofday(&tv, NULL)) {
1189 uint64_t time = kernel_timeval_to_ms(&tv) / 1000;
1190 char time_str[kUint64StringSize];
1191 const unsigned time_len = my_uint64_len(time);
1192 my_uint64tos(time_str, time, time_len);
1194 const int kLogOpenFlags = O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC;
1195 int log_fd = sys_open(g_crash_log_path, kLogOpenFlags, 0600);
1196 if (log_fd > 0) {
1197 sys_write(log_fd, time_str, time_len);
1198 sys_write(log_fd, ",", 1);
1199 sys_write(log_fd, buf, my_strlen(buf));
1200 sys_write(log_fd, "\n", 1);
1201 IGNORE_RET(sys_close(log_fd));
1204 #endif
1207 #if defined(OS_CHROMEOS)
1208 const char* GetCrashingProcessName(const BreakpadInfo& info,
1209 google_breakpad::PageAllocator* allocator) {
1210 // Symlink to process binary is at /proc/###/exe.
1211 char linkpath[kUint64StringSize + sizeof("/proc/") + sizeof("/exe")] =
1212 "/proc/";
1213 uint64_t pid_value_len = my_uint64_len(info.pid);
1214 my_uint64tos(linkpath + sizeof("/proc/") - 1, info.pid, pid_value_len);
1215 linkpath[sizeof("/proc/") - 1 + pid_value_len] = '\0';
1216 my_strlcat(linkpath, "/exe", sizeof(linkpath));
1218 const int kMaxSize = 4096;
1219 char* link = reinterpret_cast<char*>(allocator->Alloc(kMaxSize));
1220 if (link) {
1221 ssize_t size = readlink(linkpath, link, kMaxSize);
1222 if (size < kMaxSize && size > 0) {
1223 // readlink(2) doesn't add a terminating NUL, so do it now.
1224 link[size] = '\0';
1226 const char* name = my_strrchr(link, '/');
1227 if (name)
1228 return name + 1;
1229 return link;
1232 // Either way too long, or a read error.
1233 return "chrome-crash-unknown-process";
1235 #endif
1237 void HandleCrashDump(const BreakpadInfo& info) {
1238 int dumpfd;
1239 bool keep_fd = false;
1240 size_t dump_size;
1241 uint8_t* dump_data;
1242 google_breakpad::PageAllocator allocator;
1243 const char* exe_buf = NULL;
1245 if (GetCrashReporterClient()->HandleCrashDump(info.filename)) {
1246 return;
1249 #if defined(OS_CHROMEOS)
1250 // Grab the crashing process' name now, when it should still be available.
1251 // If we try to do this later in our grandchild the crashing process has
1252 // already terminated.
1253 exe_buf = GetCrashingProcessName(info, &allocator);
1254 #endif
1256 if (info.fd != -1) {
1257 // Dump is provided with an open FD.
1258 keep_fd = true;
1259 dumpfd = info.fd;
1261 // The FD is pointing to the end of the file.
1262 // Rewind, we'll read the data next.
1263 if (lseek(dumpfd, 0, SEEK_SET) == -1) {
1264 static const char msg[] = "Cannot upload crash dump: failed to "
1265 "reposition minidump FD\n";
1266 WriteLog(msg, sizeof(msg) - 1);
1267 IGNORE_RET(sys_close(dumpfd));
1268 return;
1270 LoadDataFromFD(allocator, info.fd, false, &dump_data, &dump_size);
1271 } else {
1272 // Dump is provided with a path.
1273 keep_fd = false;
1274 LoadDataFromFile(allocator, info.filename, &dumpfd, &dump_data, &dump_size);
1277 // TODO(jcivelli): make log work when using FDs.
1278 #if defined(ADDRESS_SANITIZER)
1279 int logfd;
1280 size_t log_size;
1281 uint8_t* log_data;
1282 // Load the AddressSanitizer log into log_data.
1283 LoadDataFromFile(allocator, info.log_filename, &logfd, &log_data, &log_size);
1284 #endif
1286 // We need to build a MIME block for uploading to the server. Since we are
1287 // going to fork and run wget, it needs to be written to a temp file.
1288 const int ufd = sys_open("/dev/urandom", O_RDONLY, 0);
1289 if (ufd < 0) {
1290 static const char msg[] = "Cannot upload crash dump because /dev/urandom"
1291 " is missing\n";
1292 WriteLog(msg, sizeof(msg) - 1);
1293 return;
1296 static const char temp_file_template[] =
1297 "/tmp/chromium-upload-XXXXXXXXXXXXXXXX";
1298 char temp_file[sizeof(temp_file_template)];
1299 int temp_file_fd = -1;
1300 if (keep_fd) {
1301 temp_file_fd = dumpfd;
1302 // Rewind the destination, we are going to overwrite it.
1303 if (lseek(dumpfd, 0, SEEK_SET) == -1) {
1304 static const char msg[] = "Cannot upload crash dump: failed to "
1305 "reposition minidump FD (2)\n";
1306 WriteLog(msg, sizeof(msg) - 1);
1307 IGNORE_RET(sys_close(dumpfd));
1308 return;
1310 } else {
1311 if (info.upload) {
1312 memcpy(temp_file, temp_file_template, sizeof(temp_file_template));
1314 for (unsigned i = 0; i < 10; ++i) {
1315 uint64_t t;
1316 sys_read(ufd, &t, sizeof(t));
1317 write_uint64_hex(temp_file + sizeof(temp_file) - (16 + 1), t);
1319 temp_file_fd = sys_open(temp_file, O_WRONLY | O_CREAT | O_EXCL, 0600);
1320 if (temp_file_fd >= 0)
1321 break;
1324 if (temp_file_fd < 0) {
1325 static const char msg[] = "Failed to create temporary file in /tmp: "
1326 "cannot upload crash dump\n";
1327 WriteLog(msg, sizeof(msg) - 1);
1328 IGNORE_RET(sys_close(ufd));
1329 return;
1331 } else {
1332 temp_file_fd = sys_open(info.filename, O_WRONLY, 0600);
1333 if (temp_file_fd < 0) {
1334 static const char msg[] = "Failed to save crash dump: failed to open\n";
1335 WriteLog(msg, sizeof(msg) - 1);
1336 IGNORE_RET(sys_close(ufd));
1337 return;
1342 // The MIME boundary is 28 hyphens, followed by a 64-bit nonce and a NUL.
1343 char mime_boundary[28 + 16 + 1];
1344 my_memset(mime_boundary, '-', 28);
1345 uint64_t boundary_rand;
1346 sys_read(ufd, &boundary_rand, sizeof(boundary_rand));
1347 write_uint64_hex(mime_boundary + 28, boundary_rand);
1348 mime_boundary[28 + 16] = 0;
1349 IGNORE_RET(sys_close(ufd));
1351 // The MIME block looks like this:
1352 // BOUNDARY \r\n
1353 // Content-Disposition: form-data; name="prod" \r\n \r\n
1354 // Chrome_Linux \r\n
1355 // BOUNDARY \r\n
1356 // Content-Disposition: form-data; name="ver" \r\n \r\n
1357 // 1.2.3.4 \r\n
1358 // BOUNDARY \r\n
1360 // zero or one:
1361 // Content-Disposition: form-data; name="ptime" \r\n \r\n
1362 // abcdef \r\n
1363 // BOUNDARY \r\n
1365 // zero or one:
1366 // Content-Disposition: form-data; name="ptype" \r\n \r\n
1367 // abcdef \r\n
1368 // BOUNDARY \r\n
1370 // zero or one:
1371 // Content-Disposition: form-data; name="lsb-release" \r\n \r\n
1372 // abcdef \r\n
1373 // BOUNDARY \r\n
1375 // zero or one:
1376 // Content-Disposition: form-data; name="oom-size" \r\n \r\n
1377 // 1234567890 \r\n
1378 // BOUNDARY \r\n
1380 // zero or more (up to CrashKeyStorage::num_entries = 64):
1381 // Content-Disposition: form-data; name=crash-key-name \r\n
1382 // crash-key-value \r\n
1383 // BOUNDARY \r\n
1385 // Content-Disposition: form-data; name="dump"; filename="dump" \r\n
1386 // Content-Type: application/octet-stream \r\n \r\n
1387 // <dump contents>
1388 // \r\n BOUNDARY -- \r\n
1390 #if defined(OS_CHROMEOS)
1391 CrashReporterWriter writer(temp_file_fd);
1392 #else
1393 MimeWriter writer(temp_file_fd, mime_boundary);
1394 #endif
1396 const char* product_name = "";
1397 const char* version = "";
1399 GetCrashReporterClient()->GetProductNameAndVersion(&product_name, &version);
1401 writer.AddBoundary();
1402 writer.AddPairString("prod", product_name);
1403 writer.AddBoundary();
1404 writer.AddPairString("ver", version);
1405 writer.AddBoundary();
1406 if (info.pid > 0) {
1407 char pid_value_buf[kUint64StringSize];
1408 uint64_t pid_value_len = my_uint64_len(info.pid);
1409 my_uint64tos(pid_value_buf, info.pid, pid_value_len);
1410 static const char pid_key_name[] = "pid";
1411 writer.AddPairData(pid_key_name, sizeof(pid_key_name) - 1,
1412 pid_value_buf, pid_value_len);
1413 writer.AddBoundary();
1415 #if defined(OS_ANDROID)
1416 // Addtional MIME blocks are added for logging on Android devices.
1417 static const char android_build_id[] = "android_build_id";
1418 static const char android_build_fp[] = "android_build_fp";
1419 static const char device[] = "device";
1420 static const char model[] = "model";
1421 static const char brand[] = "brand";
1422 static const char exception_info[] = "exception_info";
1424 base::android::BuildInfo* android_build_info =
1425 base::android::BuildInfo::GetInstance();
1426 writer.AddPairString(
1427 android_build_id, android_build_info->android_build_id());
1428 writer.AddBoundary();
1429 writer.AddPairString(
1430 android_build_fp, android_build_info->android_build_fp());
1431 writer.AddBoundary();
1432 writer.AddPairString(device, android_build_info->device());
1433 writer.AddBoundary();
1434 writer.AddPairString(model, android_build_info->model());
1435 writer.AddBoundary();
1436 writer.AddPairString(brand, android_build_info->brand());
1437 writer.AddBoundary();
1438 if (android_build_info->java_exception_info() != NULL) {
1439 writer.AddPairString(exception_info,
1440 android_build_info->java_exception_info());
1441 writer.AddBoundary();
1443 #endif
1444 writer.Flush();
1447 if (info.process_start_time > 0) {
1448 struct kernel_timeval tv;
1449 if (!sys_gettimeofday(&tv, NULL)) {
1450 uint64_t time = kernel_timeval_to_ms(&tv);
1451 if (time > info.process_start_time) {
1452 time -= info.process_start_time;
1453 char time_str[kUint64StringSize];
1454 const unsigned time_len = my_uint64_len(time);
1455 my_uint64tos(time_str, time, time_len);
1457 static const char process_time_msg[] = "ptime";
1458 writer.AddPairData(process_time_msg, sizeof(process_time_msg) - 1,
1459 time_str, time_len);
1460 writer.AddBoundary();
1461 writer.Flush();
1466 if (info.process_type_length) {
1467 writer.AddPairString("ptype", info.process_type);
1468 writer.AddBoundary();
1469 writer.Flush();
1472 if (info.distro_length) {
1473 static const char distro_msg[] = "lsb-release";
1474 writer.AddPairString(distro_msg, info.distro);
1475 writer.AddBoundary();
1476 writer.Flush();
1479 if (info.oom_size) {
1480 char oom_size_str[kUint64StringSize];
1481 const unsigned oom_size_len = my_uint64_len(info.oom_size);
1482 my_uint64tos(oom_size_str, info.oom_size, oom_size_len);
1483 static const char oom_size_msg[] = "oom-size";
1484 writer.AddPairData(oom_size_msg, sizeof(oom_size_msg) - 1,
1485 oom_size_str, oom_size_len);
1486 writer.AddBoundary();
1487 writer.Flush();
1490 if (info.crash_keys) {
1491 CrashKeyStorage::Iterator crash_key_iterator(*info.crash_keys);
1492 const CrashKeyStorage::Entry* entry;
1493 while ((entry = crash_key_iterator.Next())) {
1494 writer.AddPairString(entry->key, entry->value);
1495 writer.AddBoundary();
1496 writer.Flush();
1500 writer.AddFileContents(g_dump_msg, dump_data, dump_size);
1501 #if defined(ADDRESS_SANITIZER)
1502 // Append a multipart boundary and the contents of the AddressSanitizer log.
1503 writer.AddBoundary();
1504 writer.AddFileContents(g_log_msg, log_data, log_size);
1505 #endif
1506 writer.AddEnd();
1507 writer.Flush();
1509 IGNORE_RET(sys_close(temp_file_fd));
1511 #if defined(OS_ANDROID)
1512 if (info.filename) {
1513 int filename_length = my_strlen(info.filename);
1515 // If this was a file, we need to copy it to the right place and use the
1516 // right file name so it gets uploaded by the browser.
1517 const char msg[] = "Output crash dump file:";
1518 WriteLog(msg, sizeof(msg) - 1);
1519 WriteLog(info.filename, filename_length - 1);
1521 char pid_buf[kUint64StringSize];
1522 uint64_t pid_str_length = my_uint64_len(info.pid);
1523 my_uint64tos(pid_buf, info.pid, pid_str_length);
1525 // -1 because we won't need the null terminator on the original filename.
1526 unsigned done_filename_len = filename_length - 1 + pid_str_length;
1527 char* done_filename = reinterpret_cast<char*>(
1528 allocator.Alloc(done_filename_len));
1529 // Rename the file such that the pid is the suffix in order signal to other
1530 // processes that the minidump is complete. The advantage of using the pid
1531 // as the suffix is that it is trivial to associate the minidump with the
1532 // crashed process.
1533 // Finally, note strncpy prevents null terminators from
1534 // being copied. Pad the rest with 0's.
1535 my_strncpy(done_filename, info.filename, done_filename_len);
1536 // Append the suffix a null terminator should be added.
1537 my_strncat(done_filename, pid_buf, pid_str_length);
1538 // Rename the minidump file to signal that it is complete.
1539 if (rename(info.filename, done_filename)) {
1540 const char failed_msg[] = "Failed to rename:";
1541 WriteLog(failed_msg, sizeof(failed_msg) - 1);
1542 WriteLog(info.filename, filename_length - 1);
1543 const char to_msg[] = "to";
1544 WriteLog(to_msg, sizeof(to_msg) - 1);
1545 WriteLog(done_filename, done_filename_len - 1);
1548 #endif
1550 if (!info.upload)
1551 return;
1553 const pid_t child = sys_fork();
1554 if (!child) {
1555 // Spawned helper process.
1557 // This code is called both when a browser is crashing (in which case,
1558 // nothing really matters any more) and when a renderer/plugin crashes, in
1559 // which case we need to continue.
1561 // Since we are a multithreaded app, if we were just to fork(), we might
1562 // grab file descriptors which have just been created in another thread and
1563 // hold them open for too long.
1565 // Thus, we have to loop and try and close everything.
1566 const int fd = sys_open("/proc/self/fd", O_DIRECTORY | O_RDONLY, 0);
1567 if (fd < 0) {
1568 for (unsigned i = 3; i < 8192; ++i)
1569 IGNORE_RET(sys_close(i));
1570 } else {
1571 google_breakpad::DirectoryReader reader(fd);
1572 const char* name;
1573 while (reader.GetNextEntry(&name)) {
1574 int i;
1575 if (my_strtoui(&i, name) && i > 2 && i != fd)
1576 IGNORE_RET(sys_close(i));
1577 reader.PopEntry();
1580 IGNORE_RET(sys_close(fd));
1583 IGNORE_RET(sys_setsid());
1585 // Leave one end of a pipe in the upload process and watch for it getting
1586 // closed by the upload process exiting.
1587 int fds[2];
1588 if (sys_pipe(fds) >= 0) {
1589 const pid_t upload_child = sys_fork();
1590 if (!upload_child) {
1591 // Upload process.
1592 IGNORE_RET(sys_close(fds[0]));
1593 IGNORE_RET(sys_dup2(fds[1], 3));
1594 ExecUploadProcessOrTerminate(info, temp_file, mime_boundary, exe_buf,
1595 &allocator);
1598 // Helper process.
1599 if (upload_child > 0) {
1600 IGNORE_RET(sys_close(fds[1]));
1602 const size_t kCrashIdLength = 16;
1603 char id_buf[kCrashIdLength + 1];
1604 size_t bytes_read =
1605 WaitForCrashReportUploadProcess(fds[0], kCrashIdLength, id_buf);
1606 HandleCrashReportId(id_buf, bytes_read, kCrashIdLength);
1608 if (sys_waitpid(upload_child, NULL, WNOHANG) == 0) {
1609 // Upload process is still around, kill it.
1610 sys_kill(upload_child, SIGKILL);
1615 // Helper process.
1616 IGNORE_RET(sys_unlink(info.filename));
1617 #if defined(ADDRESS_SANITIZER)
1618 IGNORE_RET(sys_unlink(info.log_filename));
1619 #endif
1620 IGNORE_RET(sys_unlink(temp_file));
1621 sys__exit(0);
1624 // Main browser process.
1625 if (child <= 0)
1626 return;
1627 (void) HANDLE_EINTR(sys_waitpid(child, NULL, 0));
1630 void InitCrashReporter(const std::string& process_type) {
1631 #if defined(OS_ANDROID)
1632 // This will guarantee that the BuildInfo has been initialized and subsequent
1633 // calls will not require memory allocation.
1634 base::android::BuildInfo::GetInstance();
1636 // Handler registration is LIFO. Install the microdump handler first, such
1637 // that if conventional minidump crash reporting is enabled below, it takes
1638 // precedence (i.e. its handler is run first) over the microdump handler.
1639 InitMicrodumpCrashHandlerIfNecessary(process_type);
1640 #endif
1641 // Determine the process type and take appropriate action.
1642 const base::CommandLine& parsed_command_line =
1643 *base::CommandLine::ForCurrentProcess();
1644 if (parsed_command_line.HasSwitch(switches::kDisableBreakpad))
1645 return;
1647 if (process_type.empty()) {
1648 bool enable_breakpad = GetCrashReporterClient()->GetCollectStatsConsent() ||
1649 GetCrashReporterClient()->IsRunningUnattended();
1650 enable_breakpad &=
1651 !parsed_command_line.HasSwitch(switches::kDisableBreakpad);
1652 if (!enable_breakpad) {
1653 enable_breakpad = parsed_command_line.HasSwitch(
1654 switches::kEnableCrashReporterForTesting);
1656 if (!enable_breakpad) {
1657 VLOG(1) << "Breakpad disabled";
1658 return;
1661 InitCrashKeys();
1662 EnableCrashDumping(GetCrashReporterClient()->IsRunningUnattended());
1663 } else if (GetCrashReporterClient()->EnableBreakpadForProcess(process_type)) {
1664 #if defined(OS_ANDROID)
1665 NOTREACHED() << "Breakpad initialized with InitCrashReporter() instead of "
1666 "InitNonBrowserCrashReporter in " << process_type << " process.";
1667 return;
1668 #else
1669 // We might be chrooted in a zygote or renderer process so we cannot call
1670 // GetCollectStatsConsent because that needs access the the user's home
1671 // dir. Instead, we set a command line flag for these processes.
1672 // Even though plugins are not chrooted, we share the same code path for
1673 // simplicity.
1674 if (!parsed_command_line.HasSwitch(switches::kEnableCrashReporter))
1675 return;
1676 InitCrashKeys();
1677 SetClientIdFromCommandLine(parsed_command_line);
1678 EnableNonBrowserCrashDumping();
1679 VLOG(1) << "Non Browser crash dumping enabled for: " << process_type;
1680 #endif // #if defined(OS_ANDROID)
1683 PostEnableBreakpadInitialization();
1686 #if defined(OS_ANDROID)
1687 void InitNonBrowserCrashReporterForAndroid(const std::string& process_type) {
1688 const base::CommandLine* command_line =
1689 base::CommandLine::ForCurrentProcess();
1691 // Handler registration is LIFO. Install the microdump handler first, such
1692 // that if conventional minidump crash reporting is enabled below, it takes
1693 // precedence (i.e. its handler is run first) over the microdump handler.
1694 InitMicrodumpCrashHandlerIfNecessary(process_type);
1696 if (command_line->HasSwitch(switches::kEnableCrashReporter)) {
1697 // On Android we need to provide a FD to the file where the minidump is
1698 // generated as the renderer and browser run with different UIDs
1699 // (preventing the browser from inspecting the renderer process).
1700 int minidump_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
1701 GetCrashReporterClient()->GetAndroidMinidumpDescriptor());
1702 if (minidump_fd < 0) {
1703 NOTREACHED() << "Could not find minidump FD, crash reporting disabled.";
1704 } else {
1705 InitCrashKeys();
1706 EnableNonBrowserCrashDumping(process_type, minidump_fd);
1710 #endif // OS_ANDROID
1712 bool IsCrashReporterEnabled() {
1713 return g_is_crash_reporter_enabled;
1716 } // namespace breakpad