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"
14 #include <sys/socket.h>
16 #include <sys/types.h>
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/crash/app/breakpad_linux_impl.h"
42 #include "components/crash/app/crash_reporter_client.h"
43 #include "content/public/common/content_descriptors.h"
45 #if defined(OS_ANDROID)
46 #include <android/log.h>
49 #include "base/android/build_info.h"
50 #include "base/android/path_utils.h"
52 #include "third_party/lss/linux_syscall_support.h"
54 #if defined(ADDRESS_SANITIZER)
55 #include <ucontext.h> // for getcontext().
58 #if defined(OS_ANDROID)
59 #define STAT_STRUCT struct stat
60 #define FSTAT_FUNC fstat
62 #define STAT_STRUCT struct kernel_stat
63 #define FSTAT_FUNC sys_fstat
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)
72 using crash_reporter::GetCrashReporterClient;
73 using google_breakpad::ExceptionHandler;
74 using google_breakpad::MinidumpDescriptor;
80 #if !defined(OS_CHROMEOS)
81 const char kUploadURL[] = "https://clients2.google.com/cr/report";
84 bool g_is_crash_reporter_enabled = false;
85 uint64_t g_process_start_time = 0;
87 char* g_crash_log_path = NULL;
88 ExceptionHandler* g_breakpad = NULL;
90 #if defined(ADDRESS_SANITIZER)
91 const char* g_asan_report_str = NULL;
93 #if defined(OS_ANDROID)
94 char* g_process_type = NULL;
97 CrashKeyStorage* g_crash_keys = NULL;
99 // Writes the value |v| as 16 hex characters to the memory pointed at by
101 void write_uint64_hex(char* output, uint64_t v) {
102 static const char hextable[] = "0123456789abcdef";
104 for (int i = 15; i >= 0; --i) {
105 output[i] = hextable[v & 15];
110 // The following helper functions are for calculating uptime.
112 // Converts a struct timeval to milliseconds.
113 uint64_t timeval_to_ms(struct timeval *tv) {
114 uint64_t ret = tv->tv_sec; // Avoid overflow by explicitly using a uint64_t.
116 ret += tv->tv_usec / 1000;
120 // Converts a struct timeval to milliseconds.
121 uint64_t kernel_timeval_to_ms(struct kernel_timeval *tv) {
122 uint64_t ret = tv->tv_sec; // Avoid overflow by explicitly using a uint64_t.
124 ret += tv->tv_usec / 1000;
128 // String buffer size to use to convert a uint64_t to string.
129 const size_t kUint64StringSize = 21;
131 void SetProcessStartTime() {
132 // Set the base process start time value.
134 if (!gettimeofday(&tv, NULL))
135 g_process_start_time = timeval_to_ms(&tv);
137 g_process_start_time = 0;
140 // uint64_t version of my_int_len() from
141 // breakpad/src/common/linux/linux_libc_support.h. Return the length of the
142 // given, non-negative integer when expressed in base 10.
143 unsigned my_uint64_len(uint64_t i) {
156 // uint64_t version of my_uitos() from
157 // breakpad/src/common/linux/linux_libc_support.h. Convert a non-negative
158 // integer to a string (not null-terminated).
159 void my_uint64tos(char* output, uint64_t i, unsigned i_len) {
160 for (unsigned index = i_len; index; --index, i /= 10)
161 output[index - 1] = '0' + (i % 10);
164 #if defined(OS_ANDROID)
165 char* my_strncpy(char* dst, const char* src, size_t len) {
170 while (i != 0 && *src != '\0') {
181 char* my_strncat(char *dest, const char* src, size_t len) {
186 if (!(*dest++ = *src++))
193 #if !defined(OS_CHROMEOS)
194 bool my_isxdigit(char c) {
195 return (c >= '0' && c <= '9') || ((c | 0x20) >= 'a' && (c | 0x20) <= 'f');
199 size_t LengthWithoutTrailingSpaces(const char* str, size_t len) {
200 while (len > 0 && str[len - 1] == ' ') {
206 void SetClientIdFromCommandLine(const CommandLine& command_line) {
207 // Get the guid from the command line switch.
208 std::string switch_value =
209 command_line.GetSwitchValueASCII(switches::kEnableCrashReporter);
210 GetCrashReporterClient()->SetCrashReporterClientIdFromGUID(switch_value);
214 #if defined(OS_CHROMEOS)
215 const char g_sep[] = ":";
217 const char g_rn[] = "\r\n";
218 const char g_form_data_msg[] = "Content-Disposition: form-data; name=\"";
219 const char g_quote_msg[] = "\"";
220 const char g_dashdash_msg[] = "--";
221 const char g_dump_msg[] = "upload_file_minidump\"; filename=\"dump\"";
222 #if defined(ADDRESS_SANITIZER)
223 const char g_log_msg[] = "upload_file_log\"; filename=\"log\"";
225 const char g_content_type_msg[] = "Content-Type: application/octet-stream";
227 // MimeWriter manages an iovec for writing MIMEs to a file.
230 static const int kIovCapacity = 30;
231 static const size_t kMaxCrashChunkSize = 64;
233 MimeWriter(int fd, const char* const mime_boundary);
237 virtual void AddBoundary();
239 // Append end of file boundary.
240 virtual void AddEnd();
242 // Append key/value pair with specified sizes.
243 virtual void AddPairData(const char* msg_type,
244 size_t msg_type_size,
245 const char* msg_data,
246 size_t msg_data_size);
248 // Append key/value pair.
249 void AddPairString(const char* msg_type,
250 const char* msg_data) {
251 AddPairData(msg_type, my_strlen(msg_type), msg_data, my_strlen(msg_data));
254 // Append key/value pair, splitting value into chunks no larger than
255 // |chunk_size|. |chunk_size| cannot be greater than |kMaxCrashChunkSize|.
256 // The msg_type string will have a counter suffix to distinguish each chunk.
257 virtual void AddPairDataInChunks(const char* msg_type,
258 size_t msg_type_size,
259 const char* msg_data,
260 size_t msg_data_size,
262 bool strip_trailing_spaces);
264 // Add binary file contents to be uploaded with the specified filename.
265 virtual void AddFileContents(const char* filename_msg,
269 // Flush any pending iovecs to the output file.
271 IGNORE_RET(sys_writev(fd_, iov_, iov_index_));
276 void AddItem(const void* base, size_t size);
277 // Minor performance trade-off for easier-to-maintain code.
278 void AddString(const char* str) {
279 AddItem(str, my_strlen(str));
281 void AddItemWithoutTrailingSpaces(const void* base, size_t size);
283 struct kernel_iovec iov_[kIovCapacity];
286 // Output file descriptor.
289 const char* const mime_boundary_;
292 DISALLOW_COPY_AND_ASSIGN(MimeWriter);
295 MimeWriter::MimeWriter(int fd, const char* const mime_boundary)
298 mime_boundary_(mime_boundary) {
301 MimeWriter::~MimeWriter() {
304 void MimeWriter::AddBoundary() {
305 AddString(mime_boundary_);
309 void MimeWriter::AddEnd() {
310 AddString(mime_boundary_);
311 AddString(g_dashdash_msg);
315 void MimeWriter::AddPairData(const char* msg_type,
316 size_t msg_type_size,
317 const char* msg_data,
318 size_t msg_data_size) {
319 AddString(g_form_data_msg);
320 AddItem(msg_type, msg_type_size);
321 AddString(g_quote_msg);
324 AddItem(msg_data, msg_data_size);
328 void MimeWriter::AddPairDataInChunks(const char* msg_type,
329 size_t msg_type_size,
330 const char* msg_data,
331 size_t msg_data_size,
333 bool strip_trailing_spaces) {
334 if (chunk_size > kMaxCrashChunkSize)
338 size_t done = 0, msg_length = msg_data_size;
341 char num[kUint64StringSize];
342 const unsigned num_len = my_uint_len(++i);
343 my_uitos(num, i, num_len);
345 size_t chunk_len = std::min(chunk_size, msg_length);
347 AddString(g_form_data_msg);
348 AddItem(msg_type, msg_type_size);
349 AddItem(num, num_len);
350 AddString(g_quote_msg);
353 if (strip_trailing_spaces) {
354 AddItemWithoutTrailingSpaces(msg_data + done, chunk_len);
356 AddItem(msg_data + done, chunk_len);
363 msg_length -= chunk_len;
367 void MimeWriter::AddFileContents(const char* filename_msg, uint8_t* file_data,
369 AddString(g_form_data_msg);
370 AddString(filename_msg);
372 AddString(g_content_type_msg);
375 AddItem(file_data, file_size);
379 void MimeWriter::AddItem(const void* base, size_t size) {
380 // Check if the iovec is full and needs to be flushed to output file.
381 if (iov_index_ == kIovCapacity) {
384 iov_[iov_index_].iov_base = const_cast<void*>(base);
385 iov_[iov_index_].iov_len = size;
389 void MimeWriter::AddItemWithoutTrailingSpaces(const void* base, size_t size) {
390 AddItem(base, LengthWithoutTrailingSpaces(static_cast<const char*>(base),
394 #if defined(OS_CHROMEOS)
395 // This subclass is used on Chromium OS to report crashes in a format easy for
396 // the central crash reporting facility to understand.
397 // Format is <name>:<data length in decimal>:<data>
398 class CrashReporterWriter : public MimeWriter {
400 explicit CrashReporterWriter(int fd);
402 virtual void AddBoundary() override;
404 virtual void AddEnd() override;
406 virtual void AddPairData(const char* msg_type,
407 size_t msg_type_size,
408 const char* msg_data,
409 size_t msg_data_size) override;
411 virtual void AddPairDataInChunks(const char* msg_type,
412 size_t msg_type_size,
413 const char* msg_data,
414 size_t msg_data_size,
416 bool strip_trailing_spaces) override;
418 virtual void AddFileContents(const char* filename_msg,
420 size_t file_size) override;
423 DISALLOW_COPY_AND_ASSIGN(CrashReporterWriter);
427 CrashReporterWriter::CrashReporterWriter(int fd) : MimeWriter(fd, "") {}
430 void CrashReporterWriter::AddBoundary() {}
431 void CrashReporterWriter::AddEnd() {}
433 void CrashReporterWriter::AddPairData(const char* msg_type,
434 size_t msg_type_size,
435 const char* msg_data,
436 size_t msg_data_size) {
437 char data[kUint64StringSize];
438 const unsigned data_len = my_uint_len(msg_data_size);
439 my_uitos(data, msg_data_size, data_len);
441 AddItem(msg_type, msg_type_size);
443 AddItem(data, data_len);
445 AddItem(msg_data, msg_data_size);
449 void CrashReporterWriter::AddPairDataInChunks(const char* msg_type,
450 size_t msg_type_size,
451 const char* msg_data,
452 size_t msg_data_size,
454 bool strip_trailing_spaces) {
455 if (chunk_size > kMaxCrashChunkSize)
460 size_t msg_length = msg_data_size;
463 char num[kUint64StringSize];
464 const unsigned num_len = my_uint_len(++i);
465 my_uitos(num, i, num_len);
467 size_t chunk_len = std::min(chunk_size, msg_length);
469 size_t write_len = chunk_len;
470 if (strip_trailing_spaces) {
471 // Take care of this here because we need to know the exact length of
472 // what is going to be written.
473 write_len = LengthWithoutTrailingSpaces(msg_data + done, write_len);
476 char data[kUint64StringSize];
477 const unsigned data_len = my_uint_len(write_len);
478 my_uitos(data, write_len, data_len);
480 AddItem(msg_type, msg_type_size);
481 AddItem(num, num_len);
483 AddItem(data, data_len);
485 AddItem(msg_data + done, write_len);
489 msg_length -= chunk_len;
493 void CrashReporterWriter::AddFileContents(const char* filename_msg,
496 char data[kUint64StringSize];
497 const unsigned data_len = my_uint_len(file_size);
498 my_uitos(data, file_size, data_len);
500 AddString(filename_msg);
502 AddItem(data, data_len);
504 AddItem(file_data, file_size);
507 #endif // defined(OS_CHROMEOS)
511 g_breakpad->WriteMinidump();
514 #if defined(OS_ANDROID)
515 const char kGoogleBreakpad[] = "google-breakpad";
518 size_t WriteLog(const char* buf, size_t nbytes) {
519 #if defined(OS_ANDROID)
520 return __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad, buf);
522 return sys_write(2, buf, nbytes);
526 size_t WriteNewline() {
527 return WriteLog("\n", 1);
530 #if defined(OS_ANDROID)
531 // Android's native crash handler outputs a diagnostic tombstone to the device
532 // log. By returning false from the HandlerCallbacks, breakpad will reinstall
533 // the previous (i.e. native) signal handlers before returning from its own
534 // handler. A Chrome build fingerprint is written to the log, so that the
535 // specific build of Chrome and the location of the archived Chrome symbols can
536 // be determined directly from it.
537 bool FinalizeCrashDoneAndroid() {
538 base::android::BuildInfo* android_build_info =
539 base::android::BuildInfo::GetInstance();
541 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
542 "### ### ### ### ### ### ### ### ### ### ### ### ###");
543 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
544 "Chrome build fingerprint:");
545 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
546 android_build_info->package_version_name());
547 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
548 android_build_info->package_version_code());
549 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
551 __android_log_write(ANDROID_LOG_WARN, kGoogleBreakpad,
552 "### ### ### ### ### ### ### ### ### ### ### ### ###");
557 bool CrashDone(const MinidumpDescriptor& minidump,
559 const bool succeeded) {
560 // WARNING: this code runs in a compromised context. It may not call into
561 // libc nor allocate memory normally.
563 const char msg[] = "Failed to generate minidump.";
564 WriteLog(msg, sizeof(msg) - 1);
568 DCHECK(!minidump.IsFD());
570 BreakpadInfo info = {0};
571 info.filename = minidump.path();
572 info.fd = minidump.fd();
573 #if defined(ADDRESS_SANITIZER)
574 google_breakpad::PageAllocator allocator;
575 const size_t log_path_len = my_strlen(minidump.path());
576 char* log_path = reinterpret_cast<char*>(allocator.Alloc(log_path_len + 1));
577 my_memcpy(log_path, minidump.path(), log_path_len);
578 my_memcpy(log_path + log_path_len - 4, ".log", 4);
579 log_path[log_path_len] = '\0';
580 info.log_filename = log_path;
582 info.process_type = "browser";
583 info.process_type_length = 7;
584 info.distro = base::g_linux_distro;
585 info.distro_length = my_strlen(base::g_linux_distro);
586 info.upload = upload;
587 info.process_start_time = g_process_start_time;
588 info.oom_size = base::g_oom_size;
590 info.crash_keys = g_crash_keys;
591 HandleCrashDump(info);
592 #if defined(OS_ANDROID)
593 return FinalizeCrashDoneAndroid();
599 // Wrapper function, do not add more code here.
600 bool CrashDoneNoUpload(const MinidumpDescriptor& minidump,
603 return CrashDone(minidump, false, succeeded);
606 #if !defined(OS_ANDROID)
607 // Wrapper function, do not add more code here.
608 bool CrashDoneUpload(const MinidumpDescriptor& minidump,
611 return CrashDone(minidump, true, succeeded);
615 #if defined(ADDRESS_SANITIZER)
617 void __asan_set_error_report_callback(void (*cb)(const char*));
620 void AsanLinuxBreakpadCallback(const char* report) {
621 g_asan_report_str = report;
622 // Send minidump here.
623 g_breakpad->SimulateSignalDelivery(SIGKILL);
627 void EnableCrashDumping(bool unattended) {
628 g_is_crash_reporter_enabled = true;
630 base::FilePath tmp_path("/tmp");
631 PathService::Get(base::DIR_TEMP, &tmp_path);
633 base::FilePath dumps_path(tmp_path);
634 if (GetCrashReporterClient()->GetCrashDumpLocation(&dumps_path)) {
635 base::FilePath logfile =
636 dumps_path.Append(GetCrashReporterClient()->GetReporterLogFilename());
637 std::string logfile_str = logfile.value();
638 const size_t crash_log_path_len = logfile_str.size() + 1;
639 g_crash_log_path = new char[crash_log_path_len];
640 strncpy(g_crash_log_path, logfile_str.c_str(), crash_log_path_len);
643 MinidumpDescriptor minidump_descriptor(dumps_path.value());
644 minidump_descriptor.set_size_limit(kMaxMinidumpFileSize);
645 #if defined(OS_ANDROID)
646 unattended = true; // Android never uploads directly.
649 g_breakpad = new ExceptionHandler(
654 true, // Install handlers.
655 -1); // Server file descriptor. -1 for in-process.
659 #if !defined(OS_ANDROID)
661 g_breakpad = new ExceptionHandler(
666 true, // Install handlers.
667 -1); // Server file descriptor. -1 for in-process.
671 #if defined(OS_ANDROID)
672 bool CrashDoneInProcessNoUpload(
673 const google_breakpad::MinidumpDescriptor& descriptor,
675 const bool succeeded) {
676 // WARNING: this code runs in a compromised context. It may not call into
677 // libc nor allocate memory normally.
679 static const char msg[] = "Crash dump generation failed.\n";
680 WriteLog(msg, sizeof(msg) - 1);
684 // Start constructing the message to send to the browser.
685 BreakpadInfo info = {0};
686 info.filename = NULL;
687 info.fd = descriptor.fd();
688 info.process_type = g_process_type;
689 info.process_type_length = my_strlen(g_process_type);
691 info.distro_length = 0;
693 info.process_start_time = g_process_start_time;
695 info.crash_keys = g_crash_keys;
696 HandleCrashDump(info);
697 bool finalize_result = FinalizeCrashDoneAndroid();
698 base::android::BuildInfo* android_build_info =
699 base::android::BuildInfo::GetInstance();
700 if (android_build_info->sdk_int() >= 18 &&
701 my_strcmp(android_build_info->build_type(), "eng") != 0 &&
702 my_strcmp(android_build_info->build_type(), "userdebug") != 0) {
703 // On JB MR2 and later, the system crash handler displays a dialog. For
704 // renderer crashes, this is a bad user experience and so this is disabled
705 // for user builds of Android.
706 // TODO(cjhopman): There should be some way to recover the crash stack from
707 // non-uploading user clients. See http://crbug.com/273706.
708 __android_log_write(ANDROID_LOG_WARN,
710 "Tombstones are disabled on JB MR2+ user builds.");
711 __android_log_write(ANDROID_LOG_WARN,
713 "### ### ### ### ### ### ### ### ### ### ### ### ###");
716 return finalize_result;
720 void EnableNonBrowserCrashDumping(const std::string& process_type,
722 // This will guarantee that the BuildInfo has been initialized and subsequent
723 // calls will not require memory allocation.
724 base::android::BuildInfo::GetInstance();
725 SetClientIdFromCommandLine(*CommandLine::ForCurrentProcess());
727 // On Android, the current sandboxing uses process isolation, in which the
728 // child process runs with a different UID. That breaks the normal crash
729 // reporting where the browser process generates the minidump by inspecting
730 // the child process. This is because the browser process now does not have
731 // the permission to access the states of the child process (as it has a
733 // TODO(jcivelli): http://b/issue?id=6776356 we should use a watchdog
734 // process forked from the renderer process that generates the minidump.
735 if (minidump_fd == -1) {
736 LOG(ERROR) << "Minidump file descriptor not found, crash reporting will "
740 SetProcessStartTime();
743 g_is_crash_reporter_enabled = true;
744 // Save the process type (it is leaked).
745 const size_t process_type_len = process_type.size() + 1;
746 g_process_type = new char[process_type_len];
747 strncpy(g_process_type, process_type.c_str(), process_type_len);
748 new google_breakpad::ExceptionHandler(MinidumpDescriptor(minidump_fd),
749 NULL, CrashDoneInProcessNoUpload, NULL, true, -1);
752 // Non-Browser = Extension, Gpu, Plugins, Ppapi and Renderer
753 class NonBrowserCrashHandler : public google_breakpad::CrashGenerationClient {
755 NonBrowserCrashHandler()
756 : server_fd_(base::GlobalDescriptors::GetInstance()->Get(
760 ~NonBrowserCrashHandler() override {}
762 bool RequestDump(const void* crash_context,
763 size_t crash_context_size) override {
764 int fds[2] = { -1, -1 };
765 if (sys_socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
766 static const char msg[] = "Failed to create socket for crash dumping.\n";
767 WriteLog(msg, sizeof(msg) - 1);
771 // Start constructing the message to send to the browser.
772 char b; // Dummy variable for sys_read below.
773 const char* b_addr = &b; // Get the address of |b| so we can create the
774 // expected /proc/[pid]/syscall content in the
775 // browser to convert namespace tids.
777 // The length of the control message:
778 static const unsigned kControlMsgSize = sizeof(int);
779 static const unsigned kControlMsgSpaceSize = CMSG_SPACE(kControlMsgSize);
780 static const unsigned kControlMsgLenSize = CMSG_LEN(kControlMsgSize);
782 struct kernel_msghdr msg;
783 my_memset(&msg, 0, sizeof(struct kernel_msghdr));
784 struct kernel_iovec iov[kCrashIovSize];
785 iov[0].iov_base = const_cast<void*>(crash_context);
786 iov[0].iov_len = crash_context_size;
787 iov[1].iov_base = &b_addr;
788 iov[1].iov_len = sizeof(b_addr);
789 iov[2].iov_base = &fds[0];
790 iov[2].iov_len = sizeof(fds[0]);
791 iov[3].iov_base = &g_process_start_time;
792 iov[3].iov_len = sizeof(g_process_start_time);
793 iov[4].iov_base = &base::g_oom_size;
794 iov[4].iov_len = sizeof(base::g_oom_size);
795 google_breakpad::SerializedNonAllocatingMap* serialized_map;
796 iov[5].iov_len = g_crash_keys->Serialize(
797 const_cast<const google_breakpad::SerializedNonAllocatingMap**>(
799 iov[5].iov_base = serialized_map;
800 #if !defined(ADDRESS_SANITIZER)
801 COMPILE_ASSERT(5 == kCrashIovSize - 1, Incorrect_Number_Of_Iovec_Members);
803 iov[6].iov_base = const_cast<char*>(g_asan_report_str);
804 iov[6].iov_len = kMaxAsanReportSize + 1;
805 COMPILE_ASSERT(6 == kCrashIovSize - 1, Incorrect_Number_Of_Iovec_Members);
809 msg.msg_iovlen = kCrashIovSize;
810 char cmsg[kControlMsgSpaceSize];
811 my_memset(cmsg, 0, kControlMsgSpaceSize);
812 msg.msg_control = cmsg;
813 msg.msg_controllen = sizeof(cmsg);
815 struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg);
816 hdr->cmsg_level = SOL_SOCKET;
817 hdr->cmsg_type = SCM_RIGHTS;
818 hdr->cmsg_len = kControlMsgLenSize;
819 ((int*)CMSG_DATA(hdr))[0] = fds[1];
821 if (HANDLE_EINTR(sys_sendmsg(server_fd_, &msg, 0)) < 0) {
822 static const char errmsg[] = "Failed to tell parent about crash.\n";
823 WriteLog(errmsg, sizeof(errmsg) - 1);
824 IGNORE_RET(sys_close(fds[0]));
825 IGNORE_RET(sys_close(fds[1]));
828 IGNORE_RET(sys_close(fds[1]));
830 if (HANDLE_EINTR(sys_read(fds[0], &b, 1)) != 1) {
831 static const char errmsg[] = "Parent failed to complete crash dump.\n";
832 WriteLog(errmsg, sizeof(errmsg) - 1);
834 IGNORE_RET(sys_close(fds[0]));
840 // The pipe FD to the browser process, which will handle the crash dumping.
841 const int server_fd_;
843 DISALLOW_COPY_AND_ASSIGN(NonBrowserCrashHandler);
846 void EnableNonBrowserCrashDumping() {
847 g_is_crash_reporter_enabled = true;
848 // We deliberately leak this object.
851 g_breakpad = new ExceptionHandler(
852 MinidumpDescriptor("/tmp"), // Unused but needed or Breakpad will assert.
858 g_breakpad->set_crash_generation_client(new NonBrowserCrashHandler());
860 #endif // defined(OS_ANDROID)
862 void SetCrashKeyValue(const base::StringPiece& key,
863 const base::StringPiece& value) {
864 g_crash_keys->SetKeyValue(key.data(), value.data());
867 void ClearCrashKey(const base::StringPiece& key) {
868 g_crash_keys->RemoveKey(key.data());
871 // GetCrashReporterClient() cannot call any Set methods until after
873 void InitCrashKeys() {
874 g_crash_keys = new CrashKeyStorage;
875 GetCrashReporterClient()->RegisterCrashKeys();
876 base::debug::SetCrashKeyReportingFunctions(&SetCrashKeyValue, &ClearCrashKey);
879 // Miscellaneous initialization functions to call after Breakpad has been
881 void PostEnableBreakpadInitialization() {
882 SetProcessStartTime();
885 base::debug::SetDumpWithoutCrashingFunction(&DumpProcess);
886 #if defined(ADDRESS_SANITIZER)
887 // Register the callback for AddressSanitizer error reporting.
888 __asan_set_error_report_callback(AsanLinuxBreakpadCallback);
894 void LoadDataFromFD(google_breakpad::PageAllocator& allocator,
895 int fd, bool close_fd, uint8_t** file_data, size_t* size) {
897 if (FSTAT_FUNC(fd, &st) != 0) {
898 static const char msg[] = "Cannot upload crash dump: stat failed\n";
899 WriteLog(msg, sizeof(msg) - 1);
901 IGNORE_RET(sys_close(fd));
905 *file_data = reinterpret_cast<uint8_t*>(allocator.Alloc(st.st_size));
907 static const char msg[] = "Cannot upload crash dump: cannot alloc\n";
908 WriteLog(msg, sizeof(msg) - 1);
910 IGNORE_RET(sys_close(fd));
913 my_memset(*file_data, 0xf, st.st_size);
916 int byte_read = sys_read(fd, *file_data, *size);
917 if (byte_read == -1) {
918 static const char msg[] = "Cannot upload crash dump: read failed\n";
919 WriteLog(msg, sizeof(msg) - 1);
921 IGNORE_RET(sys_close(fd));
926 IGNORE_RET(sys_close(fd));
929 void LoadDataFromFile(google_breakpad::PageAllocator& allocator,
930 const char* filename,
931 int* fd, uint8_t** file_data, size_t* size) {
932 // WARNING: this code runs in a compromised context. It may not call into
933 // libc nor allocate memory normally.
934 *fd = sys_open(filename, O_RDONLY, 0);
938 static const char msg[] = "Cannot upload crash dump: failed to open\n";
939 WriteLog(msg, sizeof(msg) - 1);
943 LoadDataFromFD(allocator, *fd, true, file_data, size);
946 // Spawn the appropriate upload process for the current OS:
947 // - generic Linux invokes wget.
948 // - ChromeOS invokes crash_reporter.
949 // |dumpfile| is the path to the dump data file.
950 // |mime_boundary| is only used on Linux.
951 // |exe_buf| is only used on CrOS and is the crashing process' name.
952 void ExecUploadProcessOrTerminate(const BreakpadInfo& info,
953 const char* dumpfile,
954 const char* mime_boundary,
956 google_breakpad::PageAllocator* allocator) {
957 #if defined(OS_CHROMEOS)
958 // CrOS uses crash_reporter instead of wget to report crashes,
959 // it needs to know where the crash dump lives and the pid and uid of the
961 static const char kCrashReporterBinary[] = "/sbin/crash_reporter";
963 char pid_buf[kUint64StringSize];
964 uint64_t pid_str_length = my_uint64_len(info.pid);
965 my_uint64tos(pid_buf, info.pid, pid_str_length);
966 pid_buf[pid_str_length] = '\0';
968 char uid_buf[kUint64StringSize];
969 uid_t uid = geteuid();
970 uint64_t uid_str_length = my_uint64_len(uid);
971 my_uint64tos(uid_buf, uid, uid_str_length);
972 uid_buf[uid_str_length] = '\0';
974 const char kChromeFlag[] = "--chrome=";
975 size_t buf_len = my_strlen(dumpfile) + sizeof(kChromeFlag);
976 char* chrome_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
977 chrome_flag[0] = '\0';
978 my_strlcat(chrome_flag, kChromeFlag, buf_len);
979 my_strlcat(chrome_flag, dumpfile, buf_len);
981 const char kPidFlag[] = "--pid=";
982 buf_len = my_strlen(pid_buf) + sizeof(kPidFlag);
983 char* pid_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
985 my_strlcat(pid_flag, kPidFlag, buf_len);
986 my_strlcat(pid_flag, pid_buf, buf_len);
988 const char kUidFlag[] = "--uid=";
989 buf_len = my_strlen(uid_buf) + sizeof(kUidFlag);
990 char* uid_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
992 my_strlcat(uid_flag, kUidFlag, buf_len);
993 my_strlcat(uid_flag, uid_buf, buf_len);
995 const char kExeBuf[] = "--exe=";
996 buf_len = my_strlen(exe_buf) + sizeof(kExeBuf);
997 char* exe_flag = reinterpret_cast<char*>(allocator->Alloc(buf_len));
999 my_strlcat(exe_flag, kExeBuf, buf_len);
1000 my_strlcat(exe_flag, exe_buf, buf_len);
1002 const char* args[] = {
1003 kCrashReporterBinary,
1010 static const char msg[] = "Cannot upload crash dump: cannot exec "
1011 "/sbin/crash_reporter\n";
1013 // The --header argument to wget looks like:
1014 // --header=Content-Type: multipart/form-data; boundary=XYZ
1015 // where the boundary has two fewer leading '-' chars
1016 static const char header_msg[] =
1017 "--header=Content-Type: multipart/form-data; boundary=";
1018 char* const header = reinterpret_cast<char*>(allocator->Alloc(
1019 sizeof(header_msg) - 1 + strlen(mime_boundary) - 2 + 1));
1020 memcpy(header, header_msg, sizeof(header_msg) - 1);
1021 memcpy(header + sizeof(header_msg) - 1, mime_boundary + 2,
1022 strlen(mime_boundary) - 2);
1023 // We grab the NUL byte from the end of |mime_boundary|.
1025 // The --post-file argument to wget looks like:
1026 // --post-file=/tmp/...
1027 static const char post_file_msg[] = "--post-file=";
1028 char* const post_file = reinterpret_cast<char*>(allocator->Alloc(
1029 sizeof(post_file_msg) - 1 + strlen(dumpfile) + 1));
1030 memcpy(post_file, post_file_msg, sizeof(post_file_msg) - 1);
1031 memcpy(post_file + sizeof(post_file_msg) - 1, dumpfile, strlen(dumpfile));
1033 static const char kWgetBinary[] = "/usr/bin/wget";
1034 const char* args[] = {
1039 "--timeout=10", // Set a timeout so we don't hang forever.
1040 "--tries=1", // Don't retry if the upload fails.
1041 "-O", // output reply to fd 3
1045 static const char msg[] = "Cannot upload crash dump: cannot exec "
1048 execve(args[0], const_cast<char**>(args), environ);
1049 WriteLog(msg, sizeof(msg) - 1);
1053 // Runs in the helper process to wait for the upload process running
1054 // ExecUploadProcessOrTerminate() to finish. Returns the number of bytes written
1055 // to |fd| and save the written contents to |buf|.
1056 // |buf| needs to be big enough to hold |bytes_to_read| + 1 characters.
1057 size_t WaitForCrashReportUploadProcess(int fd, size_t bytes_to_read,
1059 size_t bytes_read = 0;
1061 // Upload should finish in about 10 seconds. Add a few more 500 ms
1062 // internals to account for process startup time.
1063 for (size_t wait_count = 0; wait_count < 24; ++wait_count) {
1064 struct kernel_pollfd poll_fd;
1066 poll_fd.events = POLLIN | POLLPRI | POLLERR;
1067 int ret = sys_poll(&poll_fd, 1, 500);
1071 } else if (ret > 0) {
1072 // There is data to read.
1073 ssize_t len = HANDLE_EINTR(
1074 sys_read(fd, buf + bytes_read, bytes_to_read - bytes_read));
1078 if (bytes_read == bytes_to_read)
1081 // |ret| == 0 -> timed out, continue waiting.
1082 // or |bytes_read| < |bytes_to_read| still, keep reading.
1084 buf[bytes_to_read] = 0; // Always NUL terminate the buffer.
1088 // |buf| should be |expected_len| + 1 characters in size and NULL terminated.
1089 bool IsValidCrashReportId(const char* buf, size_t bytes_read,
1090 size_t expected_len) {
1091 if (bytes_read != expected_len)
1093 #if defined(OS_CHROMEOS)
1094 return my_strcmp(buf, "_sys_cr_finished") == 0;
1096 for (size_t i = 0; i < bytes_read; ++i) {
1097 if (!my_isxdigit(buf[i]))
1104 // |buf| should be |expected_len| + 1 characters in size and NULL terminated.
1105 void HandleCrashReportId(const char* buf, size_t bytes_read,
1106 size_t expected_len) {
1108 if (!IsValidCrashReportId(buf, bytes_read, expected_len)) {
1109 #if defined(OS_CHROMEOS)
1110 static const char msg[] =
1111 "System crash-reporter failed to process crash report.";
1113 static const char msg[] = "Failed to get crash dump id.";
1115 WriteLog(msg, sizeof(msg) - 1);
1118 static const char id_msg[] = "Report Id: ";
1119 WriteLog(id_msg, sizeof(id_msg) - 1);
1120 WriteLog(buf, bytes_read);
1125 #if defined(OS_CHROMEOS)
1126 static const char msg[] = "Crash dump received by crash_reporter\n";
1127 WriteLog(msg, sizeof(msg) - 1);
1129 // Write crash dump id to stderr.
1130 static const char msg[] = "Crash dump id: ";
1131 WriteLog(msg, sizeof(msg) - 1);
1132 WriteLog(buf, my_strlen(buf));
1135 // Write crash dump id to crash log as: seconds_since_epoch,crash_id
1136 struct kernel_timeval tv;
1137 if (g_crash_log_path && !sys_gettimeofday(&tv, NULL)) {
1138 uint64_t time = kernel_timeval_to_ms(&tv) / 1000;
1139 char time_str[kUint64StringSize];
1140 const unsigned time_len = my_uint64_len(time);
1141 my_uint64tos(time_str, time, time_len);
1143 const int kLogOpenFlags = O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC;
1144 int log_fd = sys_open(g_crash_log_path, kLogOpenFlags, 0600);
1146 sys_write(log_fd, time_str, time_len);
1147 sys_write(log_fd, ",", 1);
1148 sys_write(log_fd, buf, my_strlen(buf));
1149 sys_write(log_fd, "\n", 1);
1150 IGNORE_RET(sys_close(log_fd));
1156 #if defined(OS_CHROMEOS)
1157 const char* GetCrashingProcessName(const BreakpadInfo& info,
1158 google_breakpad::PageAllocator* allocator) {
1159 // Symlink to process binary is at /proc/###/exe.
1160 char linkpath[kUint64StringSize + sizeof("/proc/") + sizeof("/exe")] =
1162 uint64_t pid_value_len = my_uint64_len(info.pid);
1163 my_uint64tos(linkpath + sizeof("/proc/") - 1, info.pid, pid_value_len);
1164 linkpath[sizeof("/proc/") - 1 + pid_value_len] = '\0';
1165 my_strlcat(linkpath, "/exe", sizeof(linkpath));
1167 const int kMaxSize = 4096;
1168 char* link = reinterpret_cast<char*>(allocator->Alloc(kMaxSize));
1170 ssize_t size = readlink(linkpath, link, kMaxSize);
1171 if (size < kMaxSize && size > 0) {
1172 // readlink(2) doesn't add a terminating NUL, so do it now.
1175 const char* name = my_strrchr(link, '/');
1181 // Either way too long, or a read error.
1182 return "chrome-crash-unknown-process";
1186 void HandleCrashDump(const BreakpadInfo& info) {
1188 bool keep_fd = false;
1191 google_breakpad::PageAllocator allocator;
1192 const char* exe_buf = NULL;
1194 if (GetCrashReporterClient()->HandleCrashDump(info.filename)) {
1198 #if defined(OS_CHROMEOS)
1199 // Grab the crashing process' name now, when it should still be available.
1200 // If we try to do this later in our grandchild the crashing process has
1201 // already terminated.
1202 exe_buf = GetCrashingProcessName(info, &allocator);
1205 if (info.fd != -1) {
1206 // Dump is provided with an open FD.
1210 // The FD is pointing to the end of the file.
1211 // Rewind, we'll read the data next.
1212 if (lseek(dumpfd, 0, SEEK_SET) == -1) {
1213 static const char msg[] = "Cannot upload crash dump: failed to "
1214 "reposition minidump FD\n";
1215 WriteLog(msg, sizeof(msg) - 1);
1216 IGNORE_RET(sys_close(dumpfd));
1219 LoadDataFromFD(allocator, info.fd, false, &dump_data, &dump_size);
1221 // Dump is provided with a path.
1223 LoadDataFromFile(allocator, info.filename, &dumpfd, &dump_data, &dump_size);
1226 // TODO(jcivelli): make log work when using FDs.
1227 #if defined(ADDRESS_SANITIZER)
1231 // Load the AddressSanitizer log into log_data.
1232 LoadDataFromFile(allocator, info.log_filename, &logfd, &log_data, &log_size);
1235 // We need to build a MIME block for uploading to the server. Since we are
1236 // going to fork and run wget, it needs to be written to a temp file.
1237 const int ufd = sys_open("/dev/urandom", O_RDONLY, 0);
1239 static const char msg[] = "Cannot upload crash dump because /dev/urandom"
1241 WriteLog(msg, sizeof(msg) - 1);
1245 static const char temp_file_template[] =
1246 "/tmp/chromium-upload-XXXXXXXXXXXXXXXX";
1247 char temp_file[sizeof(temp_file_template)];
1248 int temp_file_fd = -1;
1250 temp_file_fd = dumpfd;
1251 // Rewind the destination, we are going to overwrite it.
1252 if (lseek(dumpfd, 0, SEEK_SET) == -1) {
1253 static const char msg[] = "Cannot upload crash dump: failed to "
1254 "reposition minidump FD (2)\n";
1255 WriteLog(msg, sizeof(msg) - 1);
1256 IGNORE_RET(sys_close(dumpfd));
1261 memcpy(temp_file, temp_file_template, sizeof(temp_file_template));
1263 for (unsigned i = 0; i < 10; ++i) {
1265 sys_read(ufd, &t, sizeof(t));
1266 write_uint64_hex(temp_file + sizeof(temp_file) - (16 + 1), t);
1268 temp_file_fd = sys_open(temp_file, O_WRONLY | O_CREAT | O_EXCL, 0600);
1269 if (temp_file_fd >= 0)
1273 if (temp_file_fd < 0) {
1274 static const char msg[] = "Failed to create temporary file in /tmp: "
1275 "cannot upload crash dump\n";
1276 WriteLog(msg, sizeof(msg) - 1);
1277 IGNORE_RET(sys_close(ufd));
1281 temp_file_fd = sys_open(info.filename, O_WRONLY, 0600);
1282 if (temp_file_fd < 0) {
1283 static const char msg[] = "Failed to save crash dump: failed to open\n";
1284 WriteLog(msg, sizeof(msg) - 1);
1285 IGNORE_RET(sys_close(ufd));
1291 // The MIME boundary is 28 hyphens, followed by a 64-bit nonce and a NUL.
1292 char mime_boundary[28 + 16 + 1];
1293 my_memset(mime_boundary, '-', 28);
1294 uint64_t boundary_rand;
1295 sys_read(ufd, &boundary_rand, sizeof(boundary_rand));
1296 write_uint64_hex(mime_boundary + 28, boundary_rand);
1297 mime_boundary[28 + 16] = 0;
1298 IGNORE_RET(sys_close(ufd));
1300 // The MIME block looks like this:
1302 // Content-Disposition: form-data; name="prod" \r\n \r\n
1303 // Chrome_Linux \r\n
1305 // Content-Disposition: form-data; name="ver" \r\n \r\n
1310 // Content-Disposition: form-data; name="ptime" \r\n \r\n
1315 // Content-Disposition: form-data; name="ptype" \r\n \r\n
1320 // Content-Disposition: form-data; name="lsb-release" \r\n \r\n
1325 // Content-Disposition: form-data; name="oom-size" \r\n \r\n
1329 // zero or more (up to CrashKeyStorage::num_entries = 64):
1330 // Content-Disposition: form-data; name=crash-key-name \r\n
1331 // crash-key-value \r\n
1334 // Content-Disposition: form-data; name="dump"; filename="dump" \r\n
1335 // Content-Type: application/octet-stream \r\n \r\n
1337 // \r\n BOUNDARY -- \r\n
1339 #if defined(OS_CHROMEOS)
1340 CrashReporterWriter writer(temp_file_fd);
1342 MimeWriter writer(temp_file_fd, mime_boundary);
1345 const char* product_name = "";
1346 const char* version = "";
1348 GetCrashReporterClient()->GetProductNameAndVersion(&product_name, &version);
1350 writer.AddBoundary();
1351 writer.AddPairString("prod", product_name);
1352 writer.AddBoundary();
1353 writer.AddPairString("ver", version);
1354 writer.AddBoundary();
1356 char pid_value_buf[kUint64StringSize];
1357 uint64_t pid_value_len = my_uint64_len(info.pid);
1358 my_uint64tos(pid_value_buf, info.pid, pid_value_len);
1359 static const char pid_key_name[] = "pid";
1360 writer.AddPairData(pid_key_name, sizeof(pid_key_name) - 1,
1361 pid_value_buf, pid_value_len);
1362 writer.AddBoundary();
1364 #if defined(OS_ANDROID)
1365 // Addtional MIME blocks are added for logging on Android devices.
1366 static const char android_build_id[] = "android_build_id";
1367 static const char android_build_fp[] = "android_build_fp";
1368 static const char device[] = "device";
1369 static const char model[] = "model";
1370 static const char brand[] = "brand";
1371 static const char exception_info[] = "exception_info";
1373 base::android::BuildInfo* android_build_info =
1374 base::android::BuildInfo::GetInstance();
1375 writer.AddPairString(
1376 android_build_id, android_build_info->android_build_id());
1377 writer.AddBoundary();
1378 writer.AddPairString(
1379 android_build_fp, android_build_info->android_build_fp());
1380 writer.AddBoundary();
1381 writer.AddPairString(device, android_build_info->device());
1382 writer.AddBoundary();
1383 writer.AddPairString(model, android_build_info->model());
1384 writer.AddBoundary();
1385 writer.AddPairString(brand, android_build_info->brand());
1386 writer.AddBoundary();
1387 if (android_build_info->java_exception_info() != NULL) {
1388 writer.AddPairString(exception_info,
1389 android_build_info->java_exception_info());
1390 writer.AddBoundary();
1396 if (info.process_start_time > 0) {
1397 struct kernel_timeval tv;
1398 if (!sys_gettimeofday(&tv, NULL)) {
1399 uint64_t time = kernel_timeval_to_ms(&tv);
1400 if (time > info.process_start_time) {
1401 time -= info.process_start_time;
1402 char time_str[kUint64StringSize];
1403 const unsigned time_len = my_uint64_len(time);
1404 my_uint64tos(time_str, time, time_len);
1406 static const char process_time_msg[] = "ptime";
1407 writer.AddPairData(process_time_msg, sizeof(process_time_msg) - 1,
1408 time_str, time_len);
1409 writer.AddBoundary();
1415 if (info.process_type_length) {
1416 writer.AddPairString("ptype", info.process_type);
1417 writer.AddBoundary();
1421 if (info.distro_length) {
1422 static const char distro_msg[] = "lsb-release";
1423 writer.AddPairString(distro_msg, info.distro);
1424 writer.AddBoundary();
1428 if (info.oom_size) {
1429 char oom_size_str[kUint64StringSize];
1430 const unsigned oom_size_len = my_uint64_len(info.oom_size);
1431 my_uint64tos(oom_size_str, info.oom_size, oom_size_len);
1432 static const char oom_size_msg[] = "oom-size";
1433 writer.AddPairData(oom_size_msg, sizeof(oom_size_msg) - 1,
1434 oom_size_str, oom_size_len);
1435 writer.AddBoundary();
1439 if (info.crash_keys) {
1440 CrashKeyStorage::Iterator crash_key_iterator(*info.crash_keys);
1441 const CrashKeyStorage::Entry* entry;
1442 while ((entry = crash_key_iterator.Next())) {
1443 writer.AddPairString(entry->key, entry->value);
1444 writer.AddBoundary();
1449 writer.AddFileContents(g_dump_msg, dump_data, dump_size);
1450 #if defined(ADDRESS_SANITIZER)
1451 // Append a multipart boundary and the contents of the AddressSanitizer log.
1452 writer.AddBoundary();
1453 writer.AddFileContents(g_log_msg, log_data, log_size);
1458 IGNORE_RET(sys_close(temp_file_fd));
1460 #if defined(OS_ANDROID)
1461 if (info.filename) {
1462 int filename_length = my_strlen(info.filename);
1464 // If this was a file, we need to copy it to the right place and use the
1465 // right file name so it gets uploaded by the browser.
1466 const char msg[] = "Output crash dump file:";
1467 WriteLog(msg, sizeof(msg) - 1);
1468 WriteLog(info.filename, filename_length - 1);
1470 char pid_buf[kUint64StringSize];
1471 uint64_t pid_str_length = my_uint64_len(info.pid);
1472 my_uint64tos(pid_buf, info.pid, pid_str_length);
1474 // -1 because we won't need the null terminator on the original filename.
1475 unsigned done_filename_len = filename_length - 1 + pid_str_length;
1476 char* done_filename = reinterpret_cast<char*>(
1477 allocator.Alloc(done_filename_len));
1478 // Rename the file such that the pid is the suffix in order signal to other
1479 // processes that the minidump is complete. The advantage of using the pid
1480 // as the suffix is that it is trivial to associate the minidump with the
1482 // Finally, note strncpy prevents null terminators from
1483 // being copied. Pad the rest with 0's.
1484 my_strncpy(done_filename, info.filename, done_filename_len);
1485 // Append the suffix a null terminator should be added.
1486 my_strncat(done_filename, pid_buf, pid_str_length);
1487 // Rename the minidump file to signal that it is complete.
1488 if (rename(info.filename, done_filename)) {
1489 const char failed_msg[] = "Failed to rename:";
1490 WriteLog(failed_msg, sizeof(failed_msg) - 1);
1491 WriteLog(info.filename, filename_length - 1);
1492 const char to_msg[] = "to";
1493 WriteLog(to_msg, sizeof(to_msg) - 1);
1494 WriteLog(done_filename, done_filename_len - 1);
1502 const pid_t child = sys_fork();
1504 // Spawned helper process.
1506 // This code is called both when a browser is crashing (in which case,
1507 // nothing really matters any more) and when a renderer/plugin crashes, in
1508 // which case we need to continue.
1510 // Since we are a multithreaded app, if we were just to fork(), we might
1511 // grab file descriptors which have just been created in another thread and
1512 // hold them open for too long.
1514 // Thus, we have to loop and try and close everything.
1515 const int fd = sys_open("/proc/self/fd", O_DIRECTORY | O_RDONLY, 0);
1517 for (unsigned i = 3; i < 8192; ++i)
1518 IGNORE_RET(sys_close(i));
1520 google_breakpad::DirectoryReader reader(fd);
1522 while (reader.GetNextEntry(&name)) {
1524 if (my_strtoui(&i, name) && i > 2 && i != fd)
1525 IGNORE_RET(sys_close(i));
1529 IGNORE_RET(sys_close(fd));
1532 IGNORE_RET(sys_setsid());
1534 // Leave one end of a pipe in the upload process and watch for it getting
1535 // closed by the upload process exiting.
1537 if (sys_pipe(fds) >= 0) {
1538 const pid_t upload_child = sys_fork();
1539 if (!upload_child) {
1541 IGNORE_RET(sys_close(fds[0]));
1542 IGNORE_RET(sys_dup2(fds[1], 3));
1543 ExecUploadProcessOrTerminate(info, temp_file, mime_boundary, exe_buf,
1548 if (upload_child > 0) {
1549 IGNORE_RET(sys_close(fds[1]));
1551 const size_t kCrashIdLength = 16;
1552 char id_buf[kCrashIdLength + 1];
1554 WaitForCrashReportUploadProcess(fds[0], kCrashIdLength, id_buf);
1555 HandleCrashReportId(id_buf, bytes_read, kCrashIdLength);
1557 if (sys_waitpid(upload_child, NULL, WNOHANG) == 0) {
1558 // Upload process is still around, kill it.
1559 sys_kill(upload_child, SIGKILL);
1565 IGNORE_RET(sys_unlink(info.filename));
1566 #if defined(ADDRESS_SANITIZER)
1567 IGNORE_RET(sys_unlink(info.log_filename));
1569 IGNORE_RET(sys_unlink(temp_file));
1573 // Main browser process.
1576 (void) HANDLE_EINTR(sys_waitpid(child, NULL, 0));
1579 void InitCrashReporter(const std::string& process_type) {
1580 #if defined(OS_ANDROID)
1581 // This will guarantee that the BuildInfo has been initialized and subsequent
1582 // calls will not require memory allocation.
1583 base::android::BuildInfo::GetInstance();
1585 // Determine the process type and take appropriate action.
1586 const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
1587 if (parsed_command_line.HasSwitch(switches::kDisableBreakpad))
1590 if (process_type.empty()) {
1591 bool enable_breakpad = GetCrashReporterClient()->GetCollectStatsConsent() ||
1592 GetCrashReporterClient()->IsRunningUnattended();
1594 !parsed_command_line.HasSwitch(switches::kDisableBreakpad);
1595 if (!enable_breakpad) {
1596 enable_breakpad = parsed_command_line.HasSwitch(
1597 switches::kEnableCrashReporterForTesting);
1599 if (!enable_breakpad) {
1600 VLOG(1) << "Breakpad disabled";
1605 EnableCrashDumping(GetCrashReporterClient()->IsRunningUnattended());
1606 } else if (GetCrashReporterClient()->EnableBreakpadForProcess(process_type)) {
1607 #if defined(OS_ANDROID)
1608 NOTREACHED() << "Breakpad initialized with InitCrashReporter() instead of "
1609 "InitNonBrowserCrashReporter in " << process_type << " process.";
1612 // We might be chrooted in a zygote or renderer process so we cannot call
1613 // GetCollectStatsConsent because that needs access the the user's home
1614 // dir. Instead, we set a command line flag for these processes.
1615 // Even though plugins are not chrooted, we share the same code path for
1617 if (!parsed_command_line.HasSwitch(switches::kEnableCrashReporter))
1620 SetClientIdFromCommandLine(parsed_command_line);
1621 EnableNonBrowserCrashDumping();
1622 VLOG(1) << "Non Browser crash dumping enabled for: " << process_type;
1623 #endif // #if defined(OS_ANDROID)
1626 PostEnableBreakpadInitialization();
1629 #if defined(OS_ANDROID)
1630 void InitNonBrowserCrashReporterForAndroid(const std::string& process_type) {
1631 const CommandLine* command_line = CommandLine::ForCurrentProcess();
1632 if (command_line->HasSwitch(switches::kEnableCrashReporter)) {
1633 // On Android we need to provide a FD to the file where the minidump is
1634 // generated as the renderer and browser run with different UIDs
1635 // (preventing the browser from inspecting the renderer process).
1636 int minidump_fd = base::GlobalDescriptors::GetInstance()->MaybeGet(
1637 GetCrashReporterClient()->GetAndroidMinidumpDescriptor());
1638 if (minidump_fd < 0) {
1639 NOTREACHED() << "Could not find minidump FD, crash reporting disabled.";
1642 EnableNonBrowserCrashDumping(process_type, minidump_fd);
1646 #endif // OS_ANDROID
1648 bool IsCrashReporterEnabled() {
1649 return g_is_crash_reporter_enabled;
1652 } // namespace breakpad