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 "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>
50 #include "base/android/build_info.h"
51 #include "base/android/path_utils.h"
53 #include "third_party/lss/linux_syscall_support.h"
55 #if defined(ADDRESS_SANITIZER)
56 #include <ucontext.h> // for getcontext().
59 #if defined(OS_ANDROID)
60 #define STAT_STRUCT struct stat
61 #define FSTAT_FUNC fstat
63 #define STAT_STRUCT struct kernel_stat
64 #define FSTAT_FUNC sys_fstat
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
;
81 #if !defined(OS_CHROMEOS)
82 const char kUploadURL
[] = "https://clients2.google.com/cr/report";
85 bool g_is_crash_reporter_enabled
= false;
86 uint64_t g_process_start_time
= 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
;
95 #if defined(OS_ANDROID)
96 char* g_process_type
= NULL
;
99 CrashKeyStorage
* g_crash_keys
= NULL
;
101 // Writes the value |v| as 16 hex characters to the memory pointed at by
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];
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.
118 ret
+= tv
->tv_usec
/ 1000;
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.
126 ret
+= tv
->tv_usec
/ 1000;
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.
136 if (!gettimeofday(&tv
, NULL
))
137 g_process_start_time
= timeval_to_ms(&tv
);
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
) {
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
) {
172 while (i
!= 0 && *src
!= '\0') {
183 char* my_strncat(char *dest
, const char* src
, size_t len
) {
188 if (!(*dest
++ = *src
++))
195 #if !defined(OS_CHROMEOS)
196 bool my_isxdigit(char c
) {
197 return (c
>= '0' && c
<= '9') || ((c
| 0x20) >= 'a' && (c
| 0x20) <= 'f');
201 size_t LengthWithoutTrailingSpaces(const char* str
, size_t len
) {
202 while (len
> 0 && str
[len
- 1] == ' ') {
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
);
216 #if defined(OS_CHROMEOS)
217 const char g_sep
[] = ":";
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\"";
227 const char g_content_type_msg
[] = "Content-Type: application/octet-stream";
229 // MimeWriter manages an iovec for writing MIMEs to a file.
232 static const int kIovCapacity
= 30;
233 static const size_t kMaxCrashChunkSize
= 64;
235 MimeWriter(int fd
, const char* const mime_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
,
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
,
271 // Flush any pending iovecs to the output file.
273 IGNORE_RET(sys_writev(fd_
, iov_
, iov_index_
));
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
];
288 // Output file descriptor.
291 const char* const mime_boundary_
;
294 DISALLOW_COPY_AND_ASSIGN(MimeWriter
);
297 MimeWriter::MimeWriter(int fd
, const char* const mime_boundary
)
300 mime_boundary_(mime_boundary
) {
303 MimeWriter::~MimeWriter() {
306 void MimeWriter::AddBoundary() {
307 AddString(mime_boundary_
);
311 void MimeWriter::AddEnd() {
312 AddString(mime_boundary_
);
313 AddString(g_dashdash_msg
);
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
);
326 AddItem(msg_data
, msg_data_size
);
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
,
335 bool strip_trailing_spaces
) {
336 if (chunk_size
> kMaxCrashChunkSize
)
340 size_t done
= 0, msg_length
= msg_data_size
;
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
);
355 if (strip_trailing_spaces
) {
356 AddItemWithoutTrailingSpaces(msg_data
+ done
, chunk_len
);
358 AddItem(msg_data
+ done
, chunk_len
);
365 msg_length
-= chunk_len
;
369 void MimeWriter::AddFileContents(const char* filename_msg
, uint8_t* file_data
,
371 AddString(g_form_data_msg
);
372 AddString(filename_msg
);
374 AddString(g_content_type_msg
);
377 AddItem(file_data
, file_size
);
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
) {
386 iov_
[iov_index_
].iov_base
= const_cast<void*>(base
);
387 iov_
[iov_index_
].iov_len
= size
;
391 void MimeWriter::AddItemWithoutTrailingSpaces(const void* base
, size_t size
) {
392 AddItem(base
, LengthWithoutTrailingSpaces(static_cast<const char*>(base
),
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
{
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
,
418 bool strip_trailing_spaces
) override
;
420 void AddFileContents(const char* filename_msg
,
422 size_t file_size
) override
;
425 DISALLOW_COPY_AND_ASSIGN(CrashReporterWriter
);
429 CrashReporterWriter::CrashReporterWriter(int fd
) : MimeWriter(fd
, "") {}
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
);
445 AddItem(data
, data_len
);
447 AddItem(msg_data
, msg_data_size
);
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
,
456 bool strip_trailing_spaces
) {
457 if (chunk_size
> kMaxCrashChunkSize
)
462 size_t msg_length
= msg_data_size
;
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
);
485 AddItem(data
, data_len
);
487 AddItem(msg_data
+ done
, write_len
);
491 msg_length
-= chunk_len
;
495 void CrashReporterWriter::AddFileContents(const char* filename_msg
,
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
);
504 AddItem(data
, data_len
);
506 AddItem(file_data
, file_size
);
509 #endif // defined(OS_CHROMEOS)
513 g_breakpad
->WriteMinidump();
515 // If microdumps are enabled write also a microdump on the system log.
517 g_microdump
->WriteMinidump();
520 #if defined(OS_ANDROID)
521 const char kGoogleBreakpad
[] = "google-breakpad";
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
);
528 return sys_write(2, buf
, nbytes
);
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
,
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
,
574 "Tombstones are disabled on JB MR2+ user builds.");
575 AndroidLogWriteHorizontalRule();
582 bool CrashDone(const MinidumpDescriptor
& minidump
,
584 const bool succeeded
) {
585 // WARNING: this code runs in a compromised context. It may not call into
586 // libc nor allocate memory normally.
588 const char msg
[] = "Failed to generate minidump.";
589 WriteLog(msg
, sizeof(msg
) - 1);
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
;
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
;
615 info
.crash_keys
= g_crash_keys
;
616 HandleCrashDump(info
);
617 #if defined(OS_ANDROID)
618 return FinalizeCrashDoneAndroid(true /* is_browser_process */);
624 // Wrapper function, do not add more code here.
625 bool CrashDoneNoUpload(const MinidumpDescriptor
& minidump
,
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
,
636 return CrashDone(minidump
, true, succeeded
);
640 #if defined(ADDRESS_SANITIZER)
642 void __asan_set_error_report_callback(void (*cb
)(const char*));
645 void AsanLinuxBreakpadCallback(const char* report
) {
646 g_asan_report_str
= report
;
647 // Send minidump here.
648 g_breakpad
->SimulateSignalDelivery(SIGKILL
);
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
);
668 MinidumpDescriptor
minidump_descriptor(dumps_path
.value());
669 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
670 switches::kFullMemoryCrashReport
)) {
671 minidump_descriptor
.set_size_limit(-1); // unlimited.
673 minidump_descriptor
.set_size_limit(kMaxMinidumpFileSize
);
675 #if defined(OS_ANDROID)
676 unattended
= true; // Android never uploads directly.
679 g_breakpad
= new ExceptionHandler(
684 true, // Install handlers.
685 -1); // Server file descriptor. -1 for in-process.
689 #if !defined(OS_ANDROID)
691 g_breakpad
= new ExceptionHandler(
696 true, // Install handlers.
697 -1); // Server file descriptor. -1 for in-process.
701 #if defined(OS_ANDROID)
702 bool MicrodumpCrashDone(const MinidumpDescriptor
& minidump
,
705 // WARNING: this code runs in a compromised context. It may not call into
706 // libc nor allocate memory normally.
708 static const char msg
[] = "Microdump crash handler failed.\n";
709 WriteLog(msg
, sizeof(msg
) - 1);
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).
727 if (!GetCrashReporterClient()->ShouldEnableBreakpadMicrodumps())
730 VLOG(1) << "Enabling microdumps crash handler (process_type:"
731 << process_type
<< ")";
732 DCHECK(!g_microdump
);
733 bool is_browser_process
= process_type
.empty() || process_type
== "webview";
734 g_microdump
= new ExceptionHandler(
735 MinidumpDescriptor(MinidumpDescriptor::kMicrodumpOnConsole
),
738 reinterpret_cast<void*>(is_browser_process
),
739 true, // Install handlers.
740 -1); // Server file descriptor. -1 for in-process.
744 bool CrashDoneInProcessNoUpload(
745 const google_breakpad::MinidumpDescriptor
& descriptor
,
747 const bool succeeded
) {
748 // WARNING: this code runs in a compromised context. It may not call into
749 // libc nor allocate memory normally.
751 static const char msg
[] = "Crash dump generation failed.\n";
752 WriteLog(msg
, sizeof(msg
) - 1);
756 // Start constructing the message to send to the browser.
757 BreakpadInfo info
= {0};
758 info
.filename
= NULL
;
759 info
.fd
= descriptor
.fd();
760 info
.process_type
= g_process_type
;
761 info
.process_type_length
= my_strlen(g_process_type
);
763 info
.distro_length
= 0;
765 info
.process_start_time
= g_process_start_time
;
767 info
.crash_keys
= g_crash_keys
;
768 HandleCrashDump(info
);
769 return FinalizeCrashDoneAndroid(false /* is_browser_process */);
772 void EnableNonBrowserCrashDumping(const std::string
& process_type
,
774 // This will guarantee that the BuildInfo has been initialized and subsequent
775 // calls will not require memory allocation.
776 base::android::BuildInfo::GetInstance();
777 SetClientIdFromCommandLine(*base::CommandLine::ForCurrentProcess());
779 // On Android, the current sandboxing uses process isolation, in which the
780 // child process runs with a different UID. That breaks the normal crash
781 // reporting where the browser process generates the minidump by inspecting
782 // the child process. This is because the browser process now does not have
783 // the permission to access the states of the child process (as it has a
785 // TODO(jcivelli): http://b/issue?id=6776356 we should use a watchdog
786 // process forked from the renderer process that generates the minidump.
787 if (minidump_fd
== -1) {
788 LOG(ERROR
) << "Minidump file descriptor not found, crash reporting will "
792 SetProcessStartTime();
795 g_is_crash_reporter_enabled
= true;
796 // Save the process type (it is leaked).
797 const size_t process_type_len
= process_type
.size() + 1;
798 g_process_type
= new char[process_type_len
];
799 strncpy(g_process_type
, process_type
.c_str(), process_type_len
);
800 new google_breakpad::ExceptionHandler(MinidumpDescriptor(minidump_fd
),
801 NULL
, CrashDoneInProcessNoUpload
, NULL
, true, -1);
804 // Non-Browser = Extension, Gpu, Plugins, Ppapi and Renderer
805 class NonBrowserCrashHandler
: public google_breakpad::CrashGenerationClient
{
807 NonBrowserCrashHandler()
808 : server_fd_(base::GlobalDescriptors::GetInstance()->Get(
812 ~NonBrowserCrashHandler() override
{}
814 bool RequestDump(const void* crash_context
,
815 size_t crash_context_size
) override
{
816 int fds
[2] = { -1, -1 };
817 if (sys_socketpair(AF_UNIX
, SOCK_STREAM
, 0, fds
) < 0) {
818 static const char msg
[] = "Failed to create socket for crash dumping.\n";
819 WriteLog(msg
, sizeof(msg
) - 1);
823 // Start constructing the message to send to the browser.
824 char b
; // Dummy variable for sys_read below.
825 const char* b_addr
= &b
; // Get the address of |b| so we can create the
826 // expected /proc/[pid]/syscall content in the
827 // browser to convert namespace tids.
829 // The length of the control message:
830 static const unsigned kControlMsgSize
= sizeof(int);
831 static const unsigned kControlMsgSpaceSize
= CMSG_SPACE(kControlMsgSize
);
832 static const unsigned kControlMsgLenSize
= CMSG_LEN(kControlMsgSize
);
834 struct kernel_msghdr msg
;
835 my_memset(&msg
, 0, sizeof(struct kernel_msghdr
));
836 struct kernel_iovec iov
[kCrashIovSize
];
837 iov
[0].iov_base
= const_cast<void*>(crash_context
);
838 iov
[0].iov_len
= crash_context_size
;
839 iov
[1].iov_base
= &b_addr
;
840 iov
[1].iov_len
= sizeof(b_addr
);
841 iov
[2].iov_base
= &fds
[0];
842 iov
[2].iov_len
= sizeof(fds
[0]);
843 iov
[3].iov_base
= &g_process_start_time
;
844 iov
[3].iov_len
= sizeof(g_process_start_time
);
845 iov
[4].iov_base
= &base::g_oom_size
;
846 iov
[4].iov_len
= sizeof(base::g_oom_size
);
847 google_breakpad::SerializedNonAllocatingMap
* serialized_map
;
848 iov
[5].iov_len
= g_crash_keys
->Serialize(
849 const_cast<const google_breakpad::SerializedNonAllocatingMap
**>(
851 iov
[5].iov_base
= serialized_map
;
852 #if !defined(ADDRESS_SANITIZER)
853 static_assert(5 == kCrashIovSize
- 1, "kCrashIovSize should equal 6");
855 iov
[6].iov_base
= const_cast<char*>(g_asan_report_str
);
856 iov
[6].iov_len
= kMaxAsanReportSize
+ 1;
857 static_assert(6 == kCrashIovSize
- 1, "kCrashIovSize should equal 7");
861 msg
.msg_iovlen
= kCrashIovSize
;
862 char cmsg
[kControlMsgSpaceSize
];
863 my_memset(cmsg
, 0, kControlMsgSpaceSize
);
864 msg
.msg_control
= cmsg
;
865 msg
.msg_controllen
= sizeof(cmsg
);
867 struct cmsghdr
*hdr
= CMSG_FIRSTHDR(&msg
);
868 hdr
->cmsg_level
= SOL_SOCKET
;
869 hdr
->cmsg_type
= SCM_RIGHTS
;
870 hdr
->cmsg_len
= kControlMsgLenSize
;
871 ((int*)CMSG_DATA(hdr
))[0] = fds
[1];
873 if (HANDLE_EINTR(sys_sendmsg(server_fd_
, &msg
, 0)) < 0) {
874 static const char errmsg
[] = "Failed to tell parent about crash.\n";
875 WriteLog(errmsg
, sizeof(errmsg
) - 1);
876 IGNORE_RET(sys_close(fds
[0]));
877 IGNORE_RET(sys_close(fds
[1]));
880 IGNORE_RET(sys_close(fds
[1]));
882 if (HANDLE_EINTR(sys_read(fds
[0], &b
, 1)) != 1) {
883 static const char errmsg
[] = "Parent failed to complete crash dump.\n";
884 WriteLog(errmsg
, sizeof(errmsg
) - 1);
886 IGNORE_RET(sys_close(fds
[0]));
892 // The pipe FD to the browser process, which will handle the crash dumping.
893 const int server_fd_
;
895 DISALLOW_COPY_AND_ASSIGN(NonBrowserCrashHandler
);
898 void EnableNonBrowserCrashDumping() {
899 g_is_crash_reporter_enabled
= true;
900 // We deliberately leak this object.
903 g_breakpad
= new ExceptionHandler(
904 MinidumpDescriptor("/tmp"), // Unused but needed or Breakpad will assert.
910 g_breakpad
->set_crash_generation_client(new NonBrowserCrashHandler());
912 #endif // defined(OS_ANDROID)
914 void SetCrashKeyValue(const base::StringPiece
& key
,
915 const base::StringPiece
& value
) {
916 g_crash_keys
->SetKeyValue(key
.data(), value
.data());
919 void ClearCrashKey(const base::StringPiece
& key
) {
920 g_crash_keys
->RemoveKey(key
.data());
923 // GetCrashReporterClient() cannot call any Set methods until after
925 void InitCrashKeys() {
926 g_crash_keys
= new CrashKeyStorage
;
927 GetCrashReporterClient()->RegisterCrashKeys();
928 base::debug::SetCrashKeyReportingFunctions(&SetCrashKeyValue
, &ClearCrashKey
);
931 // Miscellaneous initialization functions to call after Breakpad has been
933 void PostEnableBreakpadInitialization() {
934 SetProcessStartTime();
937 base::debug::SetDumpWithoutCrashingFunction(&DumpProcess
);
938 #if defined(ADDRESS_SANITIZER)
939 // Register the callback for AddressSanitizer error reporting.
940 __asan_set_error_report_callback(AsanLinuxBreakpadCallback
);
946 void LoadDataFromFD(google_breakpad::PageAllocator
& allocator
,
947 int fd
, bool close_fd
, uint8_t** file_data
, size_t* size
) {
949 if (FSTAT_FUNC(fd
, &st
) != 0) {
950 static const char msg
[] = "Cannot upload crash dump: stat failed\n";
951 WriteLog(msg
, sizeof(msg
) - 1);
953 IGNORE_RET(sys_close(fd
));
957 *file_data
= reinterpret_cast<uint8_t*>(allocator
.Alloc(st
.st_size
));
959 static const char msg
[] = "Cannot upload crash dump: cannot alloc\n";
960 WriteLog(msg
, sizeof(msg
) - 1);
962 IGNORE_RET(sys_close(fd
));
965 my_memset(*file_data
, 0xf, st
.st_size
);
968 int byte_read
= sys_read(fd
, *file_data
, *size
);
969 if (byte_read
== -1) {
970 static const char msg
[] = "Cannot upload crash dump: read failed\n";
971 WriteLog(msg
, sizeof(msg
) - 1);
973 IGNORE_RET(sys_close(fd
));
978 IGNORE_RET(sys_close(fd
));
981 void LoadDataFromFile(google_breakpad::PageAllocator
& allocator
,
982 const char* filename
,
983 int* fd
, uint8_t** file_data
, size_t* size
) {
984 // WARNING: this code runs in a compromised context. It may not call into
985 // libc nor allocate memory normally.
986 *fd
= sys_open(filename
, O_RDONLY
, 0);
990 static const char msg
[] = "Cannot upload crash dump: failed to open\n";
991 WriteLog(msg
, sizeof(msg
) - 1);
995 LoadDataFromFD(allocator
, *fd
, true, file_data
, size
);
998 // Spawn the appropriate upload process for the current OS:
999 // - generic Linux invokes wget.
1000 // - ChromeOS invokes crash_reporter.
1001 // |dumpfile| is the path to the dump data file.
1002 // |mime_boundary| is only used on Linux.
1003 // |exe_buf| is only used on CrOS and is the crashing process' name.
1004 void ExecUploadProcessOrTerminate(const BreakpadInfo
& info
,
1005 const char* dumpfile
,
1006 const char* mime_boundary
,
1007 const char* exe_buf
,
1008 google_breakpad::PageAllocator
* allocator
) {
1009 #if defined(OS_CHROMEOS)
1010 // CrOS uses crash_reporter instead of wget to report crashes,
1011 // it needs to know where the crash dump lives and the pid and uid of the
1012 // crashing process.
1013 static const char kCrashReporterBinary
[] = "/sbin/crash_reporter";
1015 char pid_buf
[kUint64StringSize
];
1016 uint64_t pid_str_length
= my_uint64_len(info
.pid
);
1017 my_uint64tos(pid_buf
, info
.pid
, pid_str_length
);
1018 pid_buf
[pid_str_length
] = '\0';
1020 char uid_buf
[kUint64StringSize
];
1021 uid_t uid
= geteuid();
1022 uint64_t uid_str_length
= my_uint64_len(uid
);
1023 my_uint64tos(uid_buf
, uid
, uid_str_length
);
1024 uid_buf
[uid_str_length
] = '\0';
1026 const char kChromeFlag
[] = "--chrome=";
1027 size_t buf_len
= my_strlen(dumpfile
) + sizeof(kChromeFlag
);
1028 char* chrome_flag
= reinterpret_cast<char*>(allocator
->Alloc(buf_len
));
1029 chrome_flag
[0] = '\0';
1030 my_strlcat(chrome_flag
, kChromeFlag
, buf_len
);
1031 my_strlcat(chrome_flag
, dumpfile
, buf_len
);
1033 const char kPidFlag
[] = "--pid=";
1034 buf_len
= my_strlen(pid_buf
) + sizeof(kPidFlag
);
1035 char* pid_flag
= reinterpret_cast<char*>(allocator
->Alloc(buf_len
));
1037 my_strlcat(pid_flag
, kPidFlag
, buf_len
);
1038 my_strlcat(pid_flag
, pid_buf
, buf_len
);
1040 const char kUidFlag
[] = "--uid=";
1041 buf_len
= my_strlen(uid_buf
) + sizeof(kUidFlag
);
1042 char* uid_flag
= reinterpret_cast<char*>(allocator
->Alloc(buf_len
));
1044 my_strlcat(uid_flag
, kUidFlag
, buf_len
);
1045 my_strlcat(uid_flag
, uid_buf
, buf_len
);
1047 const char kExeBuf
[] = "--exe=";
1048 buf_len
= my_strlen(exe_buf
) + sizeof(kExeBuf
);
1049 char* exe_flag
= reinterpret_cast<char*>(allocator
->Alloc(buf_len
));
1051 my_strlcat(exe_flag
, kExeBuf
, buf_len
);
1052 my_strlcat(exe_flag
, exe_buf
, buf_len
);
1054 const char* args
[] = {
1055 kCrashReporterBinary
,
1062 static const char msg
[] = "Cannot upload crash dump: cannot exec "
1063 "/sbin/crash_reporter\n";
1065 // The --header argument to wget looks like:
1066 // --header=Content-Type: multipart/form-data; boundary=XYZ
1067 // where the boundary has two fewer leading '-' chars
1068 static const char header_msg
[] =
1069 "--header=Content-Type: multipart/form-data; boundary=";
1070 char* const header
= reinterpret_cast<char*>(allocator
->Alloc(
1071 sizeof(header_msg
) - 1 + strlen(mime_boundary
) - 2 + 1));
1072 memcpy(header
, header_msg
, sizeof(header_msg
) - 1);
1073 memcpy(header
+ sizeof(header_msg
) - 1, mime_boundary
+ 2,
1074 strlen(mime_boundary
) - 2);
1075 // We grab the NUL byte from the end of |mime_boundary|.
1077 // The --post-file argument to wget looks like:
1078 // --post-file=/tmp/...
1079 static const char post_file_msg
[] = "--post-file=";
1080 char* const post_file
= reinterpret_cast<char*>(allocator
->Alloc(
1081 sizeof(post_file_msg
) - 1 + strlen(dumpfile
) + 1));
1082 memcpy(post_file
, post_file_msg
, sizeof(post_file_msg
) - 1);
1083 memcpy(post_file
+ sizeof(post_file_msg
) - 1, dumpfile
, strlen(dumpfile
));
1085 static const char kWgetBinary
[] = "/usr/bin/wget";
1086 const char* args
[] = {
1091 "--timeout=10", // Set a timeout so we don't hang forever.
1092 "--tries=1", // Don't retry if the upload fails.
1093 "-O", // output reply to fd 3
1097 static const char msg
[] = "Cannot upload crash dump: cannot exec "
1100 execve(args
[0], const_cast<char**>(args
), environ
);
1101 WriteLog(msg
, sizeof(msg
) - 1);
1105 // Runs in the helper process to wait for the upload process running
1106 // ExecUploadProcessOrTerminate() to finish. Returns the number of bytes written
1107 // to |fd| and save the written contents to |buf|.
1108 // |buf| needs to be big enough to hold |bytes_to_read| + 1 characters.
1109 size_t WaitForCrashReportUploadProcess(int fd
, size_t bytes_to_read
,
1111 size_t bytes_read
= 0;
1113 // Upload should finish in about 10 seconds. Add a few more 500 ms
1114 // internals to account for process startup time.
1115 for (size_t wait_count
= 0; wait_count
< 24; ++wait_count
) {
1116 struct kernel_pollfd poll_fd
;
1118 poll_fd
.events
= POLLIN
| POLLPRI
| POLLERR
;
1119 int ret
= sys_poll(&poll_fd
, 1, 500);
1123 } else if (ret
> 0) {
1124 // There is data to read.
1125 ssize_t len
= HANDLE_EINTR(
1126 sys_read(fd
, buf
+ bytes_read
, bytes_to_read
- bytes_read
));
1130 if (bytes_read
== bytes_to_read
)
1133 // |ret| == 0 -> timed out, continue waiting.
1134 // or |bytes_read| < |bytes_to_read| still, keep reading.
1136 buf
[bytes_to_read
] = 0; // Always NUL terminate the buffer.
1140 // |buf| should be |expected_len| + 1 characters in size and NULL terminated.
1141 bool IsValidCrashReportId(const char* buf
, size_t bytes_read
,
1142 size_t expected_len
) {
1143 if (bytes_read
!= expected_len
)
1145 #if defined(OS_CHROMEOS)
1146 return my_strcmp(buf
, "_sys_cr_finished") == 0;
1148 for (size_t i
= 0; i
< bytes_read
; ++i
) {
1149 if (!my_isxdigit(buf
[i
]))
1156 // |buf| should be |expected_len| + 1 characters in size and NULL terminated.
1157 void HandleCrashReportId(const char* buf
, size_t bytes_read
,
1158 size_t expected_len
) {
1160 if (!IsValidCrashReportId(buf
, bytes_read
, expected_len
)) {
1161 #if defined(OS_CHROMEOS)
1162 static const char msg
[] =
1163 "System crash-reporter failed to process crash report.";
1165 static const char msg
[] = "Failed to get crash dump id.";
1167 WriteLog(msg
, sizeof(msg
) - 1);
1170 static const char id_msg
[] = "Report Id: ";
1171 WriteLog(id_msg
, sizeof(id_msg
) - 1);
1172 WriteLog(buf
, bytes_read
);
1177 #if defined(OS_CHROMEOS)
1178 static const char msg
[] = "Crash dump received by crash_reporter\n";
1179 WriteLog(msg
, sizeof(msg
) - 1);
1181 // Write crash dump id to stderr.
1182 static const char msg
[] = "Crash dump id: ";
1183 WriteLog(msg
, sizeof(msg
) - 1);
1184 WriteLog(buf
, my_strlen(buf
));
1187 // Write crash dump id to crash log as: seconds_since_epoch,crash_id
1188 struct kernel_timeval tv
;
1189 if (g_crash_log_path
&& !sys_gettimeofday(&tv
, NULL
)) {
1190 uint64_t time
= kernel_timeval_to_ms(&tv
) / 1000;
1191 char time_str
[kUint64StringSize
];
1192 const unsigned time_len
= my_uint64_len(time
);
1193 my_uint64tos(time_str
, time
, time_len
);
1195 const int kLogOpenFlags
= O_CREAT
| O_WRONLY
| O_APPEND
| O_CLOEXEC
;
1196 int log_fd
= sys_open(g_crash_log_path
, kLogOpenFlags
, 0600);
1198 sys_write(log_fd
, time_str
, time_len
);
1199 sys_write(log_fd
, ",", 1);
1200 sys_write(log_fd
, buf
, my_strlen(buf
));
1201 sys_write(log_fd
, "\n", 1);
1202 IGNORE_RET(sys_close(log_fd
));
1208 #if defined(OS_CHROMEOS)
1209 const char* GetCrashingProcessName(const BreakpadInfo
& info
,
1210 google_breakpad::PageAllocator
* allocator
) {
1211 // Symlink to process binary is at /proc/###/exe.
1212 char linkpath
[kUint64StringSize
+ sizeof("/proc/") + sizeof("/exe")] =
1214 uint64_t pid_value_len
= my_uint64_len(info
.pid
);
1215 my_uint64tos(linkpath
+ sizeof("/proc/") - 1, info
.pid
, pid_value_len
);
1216 linkpath
[sizeof("/proc/") - 1 + pid_value_len
] = '\0';
1217 my_strlcat(linkpath
, "/exe", sizeof(linkpath
));
1219 const int kMaxSize
= 4096;
1220 char* link
= reinterpret_cast<char*>(allocator
->Alloc(kMaxSize
));
1222 ssize_t size
= readlink(linkpath
, link
, kMaxSize
);
1223 if (size
< kMaxSize
&& size
> 0) {
1224 // readlink(2) doesn't add a terminating NUL, so do it now.
1227 const char* name
= my_strrchr(link
, '/');
1233 // Either way too long, or a read error.
1234 return "chrome-crash-unknown-process";
1238 void HandleCrashDump(const BreakpadInfo
& info
) {
1240 bool keep_fd
= false;
1243 google_breakpad::PageAllocator allocator
;
1244 const char* exe_buf
= NULL
;
1246 if (GetCrashReporterClient()->HandleCrashDump(info
.filename
)) {
1250 #if defined(OS_CHROMEOS)
1251 // Grab the crashing process' name now, when it should still be available.
1252 // If we try to do this later in our grandchild the crashing process has
1253 // already terminated.
1254 exe_buf
= GetCrashingProcessName(info
, &allocator
);
1257 if (info
.fd
!= -1) {
1258 // Dump is provided with an open FD.
1262 // The FD is pointing to the end of the file.
1263 // Rewind, we'll read the data next.
1264 if (lseek(dumpfd
, 0, SEEK_SET
) == -1) {
1265 static const char msg
[] = "Cannot upload crash dump: failed to "
1266 "reposition minidump FD\n";
1267 WriteLog(msg
, sizeof(msg
) - 1);
1268 IGNORE_RET(sys_close(dumpfd
));
1271 LoadDataFromFD(allocator
, info
.fd
, false, &dump_data
, &dump_size
);
1273 // Dump is provided with a path.
1275 LoadDataFromFile(allocator
, info
.filename
, &dumpfd
, &dump_data
, &dump_size
);
1278 // TODO(jcivelli): make log work when using FDs.
1279 #if defined(ADDRESS_SANITIZER)
1283 // Load the AddressSanitizer log into log_data.
1284 LoadDataFromFile(allocator
, info
.log_filename
, &logfd
, &log_data
, &log_size
);
1287 // We need to build a MIME block for uploading to the server. Since we are
1288 // going to fork and run wget, it needs to be written to a temp file.
1289 const int ufd
= sys_open("/dev/urandom", O_RDONLY
, 0);
1291 static const char msg
[] = "Cannot upload crash dump because /dev/urandom"
1293 WriteLog(msg
, sizeof(msg
) - 1);
1297 static const char temp_file_template
[] =
1298 "/tmp/chromium-upload-XXXXXXXXXXXXXXXX";
1299 char temp_file
[sizeof(temp_file_template
)];
1300 int temp_file_fd
= -1;
1302 temp_file_fd
= dumpfd
;
1303 // Rewind the destination, we are going to overwrite it.
1304 if (lseek(dumpfd
, 0, SEEK_SET
) == -1) {
1305 static const char msg
[] = "Cannot upload crash dump: failed to "
1306 "reposition minidump FD (2)\n";
1307 WriteLog(msg
, sizeof(msg
) - 1);
1308 IGNORE_RET(sys_close(dumpfd
));
1313 memcpy(temp_file
, temp_file_template
, sizeof(temp_file_template
));
1315 for (unsigned i
= 0; i
< 10; ++i
) {
1317 sys_read(ufd
, &t
, sizeof(t
));
1318 write_uint64_hex(temp_file
+ sizeof(temp_file
) - (16 + 1), t
);
1320 temp_file_fd
= sys_open(temp_file
, O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
1321 if (temp_file_fd
>= 0)
1325 if (temp_file_fd
< 0) {
1326 static const char msg
[] = "Failed to create temporary file in /tmp: "
1327 "cannot upload crash dump\n";
1328 WriteLog(msg
, sizeof(msg
) - 1);
1329 IGNORE_RET(sys_close(ufd
));
1333 temp_file_fd
= sys_open(info
.filename
, O_WRONLY
, 0600);
1334 if (temp_file_fd
< 0) {
1335 static const char msg
[] = "Failed to save crash dump: failed to open\n";
1336 WriteLog(msg
, sizeof(msg
) - 1);
1337 IGNORE_RET(sys_close(ufd
));
1343 // The MIME boundary is 28 hyphens, followed by a 64-bit nonce and a NUL.
1344 char mime_boundary
[28 + 16 + 1];
1345 my_memset(mime_boundary
, '-', 28);
1346 uint64_t boundary_rand
;
1347 sys_read(ufd
, &boundary_rand
, sizeof(boundary_rand
));
1348 write_uint64_hex(mime_boundary
+ 28, boundary_rand
);
1349 mime_boundary
[28 + 16] = 0;
1350 IGNORE_RET(sys_close(ufd
));
1352 // The MIME block looks like this:
1354 // Content-Disposition: form-data; name="prod" \r\n \r\n
1355 // Chrome_Linux \r\n
1357 // Content-Disposition: form-data; name="ver" \r\n \r\n
1362 // Content-Disposition: form-data; name="ptime" \r\n \r\n
1367 // Content-Disposition: form-data; name="ptype" \r\n \r\n
1372 // Content-Disposition: form-data; name="lsb-release" \r\n \r\n
1377 // Content-Disposition: form-data; name="oom-size" \r\n \r\n
1381 // zero or more (up to CrashKeyStorage::num_entries = 64):
1382 // Content-Disposition: form-data; name=crash-key-name \r\n
1383 // crash-key-value \r\n
1386 // Content-Disposition: form-data; name="dump"; filename="dump" \r\n
1387 // Content-Type: application/octet-stream \r\n \r\n
1389 // \r\n BOUNDARY -- \r\n
1391 #if defined(OS_CHROMEOS)
1392 CrashReporterWriter
writer(temp_file_fd
);
1394 MimeWriter
writer(temp_file_fd
, mime_boundary
);
1397 const char* product_name
= "";
1398 const char* version
= "";
1400 GetCrashReporterClient()->GetProductNameAndVersion(&product_name
, &version
);
1402 writer
.AddBoundary();
1403 writer
.AddPairString("prod", product_name
);
1404 writer
.AddBoundary();
1405 writer
.AddPairString("ver", version
);
1406 writer
.AddBoundary();
1408 char pid_value_buf
[kUint64StringSize
];
1409 uint64_t pid_value_len
= my_uint64_len(info
.pid
);
1410 my_uint64tos(pid_value_buf
, info
.pid
, pid_value_len
);
1411 static const char pid_key_name
[] = "pid";
1412 writer
.AddPairData(pid_key_name
, sizeof(pid_key_name
) - 1,
1413 pid_value_buf
, pid_value_len
);
1414 writer
.AddBoundary();
1416 #if defined(OS_ANDROID)
1417 // Addtional MIME blocks are added for logging on Android devices.
1418 static const char android_build_id
[] = "android_build_id";
1419 static const char android_build_fp
[] = "android_build_fp";
1420 static const char device
[] = "device";
1421 static const char model
[] = "model";
1422 static const char brand
[] = "brand";
1423 static const char exception_info
[] = "exception_info";
1425 base::android::BuildInfo
* android_build_info
=
1426 base::android::BuildInfo::GetInstance();
1427 writer
.AddPairString(
1428 android_build_id
, android_build_info
->android_build_id());
1429 writer
.AddBoundary();
1430 writer
.AddPairString(
1431 android_build_fp
, android_build_info
->android_build_fp());
1432 writer
.AddBoundary();
1433 writer
.AddPairString(device
, android_build_info
->device());
1434 writer
.AddBoundary();
1435 writer
.AddPairString(model
, android_build_info
->model());
1436 writer
.AddBoundary();
1437 writer
.AddPairString(brand
, android_build_info
->brand());
1438 writer
.AddBoundary();
1439 if (android_build_info
->java_exception_info() != NULL
) {
1440 writer
.AddPairString(exception_info
,
1441 android_build_info
->java_exception_info());
1442 writer
.AddBoundary();
1448 if (info
.process_start_time
> 0) {
1449 struct kernel_timeval tv
;
1450 if (!sys_gettimeofday(&tv
, NULL
)) {
1451 uint64_t time
= kernel_timeval_to_ms(&tv
);
1452 if (time
> info
.process_start_time
) {
1453 time
-= info
.process_start_time
;
1454 char time_str
[kUint64StringSize
];
1455 const unsigned time_len
= my_uint64_len(time
);
1456 my_uint64tos(time_str
, time
, time_len
);
1458 static const char process_time_msg
[] = "ptime";
1459 writer
.AddPairData(process_time_msg
, sizeof(process_time_msg
) - 1,
1460 time_str
, time_len
);
1461 writer
.AddBoundary();
1467 if (info
.process_type_length
) {
1468 writer
.AddPairString("ptype", info
.process_type
);
1469 writer
.AddBoundary();
1473 if (info
.distro_length
) {
1474 static const char distro_msg
[] = "lsb-release";
1475 writer
.AddPairString(distro_msg
, info
.distro
);
1476 writer
.AddBoundary();
1480 if (info
.oom_size
) {
1481 char oom_size_str
[kUint64StringSize
];
1482 const unsigned oom_size_len
= my_uint64_len(info
.oom_size
);
1483 my_uint64tos(oom_size_str
, info
.oom_size
, oom_size_len
);
1484 static const char oom_size_msg
[] = "oom-size";
1485 writer
.AddPairData(oom_size_msg
, sizeof(oom_size_msg
) - 1,
1486 oom_size_str
, oom_size_len
);
1487 writer
.AddBoundary();
1491 if (info
.crash_keys
) {
1492 CrashKeyStorage::Iterator
crash_key_iterator(*info
.crash_keys
);
1493 const CrashKeyStorage::Entry
* entry
;
1494 while ((entry
= crash_key_iterator
.Next())) {
1495 writer
.AddPairString(entry
->key
, entry
->value
);
1496 writer
.AddBoundary();
1501 writer
.AddFileContents(g_dump_msg
, dump_data
, dump_size
);
1502 #if defined(ADDRESS_SANITIZER)
1503 // Append a multipart boundary and the contents of the AddressSanitizer log.
1504 writer
.AddBoundary();
1505 writer
.AddFileContents(g_log_msg
, log_data
, log_size
);
1510 IGNORE_RET(sys_close(temp_file_fd
));
1512 #if defined(OS_ANDROID)
1513 if (info
.filename
) {
1514 int filename_length
= my_strlen(info
.filename
);
1516 // If this was a file, we need to copy it to the right place and use the
1517 // right file name so it gets uploaded by the browser.
1518 const char msg
[] = "Output crash dump file:";
1519 WriteLog(msg
, sizeof(msg
) - 1);
1520 WriteLog(info
.filename
, filename_length
- 1);
1522 char pid_buf
[kUint64StringSize
];
1523 uint64_t pid_str_length
= my_uint64_len(info
.pid
);
1524 my_uint64tos(pid_buf
, info
.pid
, pid_str_length
);
1526 // -1 because we won't need the null terminator on the original filename.
1527 unsigned done_filename_len
= filename_length
- 1 + pid_str_length
;
1528 char* done_filename
= reinterpret_cast<char*>(
1529 allocator
.Alloc(done_filename_len
));
1530 // Rename the file such that the pid is the suffix in order signal to other
1531 // processes that the minidump is complete. The advantage of using the pid
1532 // as the suffix is that it is trivial to associate the minidump with the
1534 // Finally, note strncpy prevents null terminators from
1535 // being copied. Pad the rest with 0's.
1536 my_strncpy(done_filename
, info
.filename
, done_filename_len
);
1537 // Append the suffix a null terminator should be added.
1538 my_strncat(done_filename
, pid_buf
, pid_str_length
);
1539 // Rename the minidump file to signal that it is complete.
1540 if (rename(info
.filename
, done_filename
)) {
1541 const char failed_msg
[] = "Failed to rename:";
1542 WriteLog(failed_msg
, sizeof(failed_msg
) - 1);
1543 WriteLog(info
.filename
, filename_length
- 1);
1544 const char to_msg
[] = "to";
1545 WriteLog(to_msg
, sizeof(to_msg
) - 1);
1546 WriteLog(done_filename
, done_filename_len
- 1);
1554 const pid_t child
= sys_fork();
1556 // Spawned helper process.
1558 // This code is called both when a browser is crashing (in which case,
1559 // nothing really matters any more) and when a renderer/plugin crashes, in
1560 // which case we need to continue.
1562 // Since we are a multithreaded app, if we were just to fork(), we might
1563 // grab file descriptors which have just been created in another thread and
1564 // hold them open for too long.
1566 // Thus, we have to loop and try and close everything.
1567 const int fd
= sys_open("/proc/self/fd", O_DIRECTORY
| O_RDONLY
, 0);
1569 for (unsigned i
= 3; i
< 8192; ++i
)
1570 IGNORE_RET(sys_close(i
));
1572 google_breakpad::DirectoryReader
reader(fd
);
1574 while (reader
.GetNextEntry(&name
)) {
1576 if (my_strtoui(&i
, name
) && i
> 2 && i
!= fd
)
1577 IGNORE_RET(sys_close(i
));
1581 IGNORE_RET(sys_close(fd
));
1584 IGNORE_RET(sys_setsid());
1586 // Leave one end of a pipe in the upload process and watch for it getting
1587 // closed by the upload process exiting.
1589 if (sys_pipe(fds
) >= 0) {
1590 const pid_t upload_child
= sys_fork();
1591 if (!upload_child
) {
1593 IGNORE_RET(sys_close(fds
[0]));
1594 IGNORE_RET(sys_dup2(fds
[1], 3));
1595 ExecUploadProcessOrTerminate(info
, temp_file
, mime_boundary
, exe_buf
,
1600 if (upload_child
> 0) {
1601 IGNORE_RET(sys_close(fds
[1]));
1603 const size_t kCrashIdLength
= 16;
1604 char id_buf
[kCrashIdLength
+ 1];
1606 WaitForCrashReportUploadProcess(fds
[0], kCrashIdLength
, id_buf
);
1607 HandleCrashReportId(id_buf
, bytes_read
, kCrashIdLength
);
1609 if (sys_waitpid(upload_child
, NULL
, WNOHANG
) == 0) {
1610 // Upload process is still around, kill it.
1611 sys_kill(upload_child
, SIGKILL
);
1617 IGNORE_RET(sys_unlink(info
.filename
));
1618 #if defined(ADDRESS_SANITIZER)
1619 IGNORE_RET(sys_unlink(info
.log_filename
));
1621 IGNORE_RET(sys_unlink(temp_file
));
1625 // Main browser process.
1628 (void) HANDLE_EINTR(sys_waitpid(child
, NULL
, 0));
1631 void InitCrashReporter(const std::string
& process_type
) {
1632 #if defined(OS_ANDROID)
1633 // This will guarantee that the BuildInfo has been initialized and subsequent
1634 // calls will not require memory allocation.
1635 base::android::BuildInfo::GetInstance();
1637 // Handler registration is LIFO. Install the microdump handler first, such
1638 // that if conventional minidump crash reporting is enabled below, it takes
1639 // precedence (i.e. its handler is run first) over the microdump handler.
1640 InitMicrodumpCrashHandlerIfNecessary(process_type
);
1642 // Determine the process type and take appropriate action.
1643 const base::CommandLine
& parsed_command_line
=
1644 *base::CommandLine::ForCurrentProcess();
1645 if (parsed_command_line
.HasSwitch(switches::kDisableBreakpad
))
1648 if (process_type
.empty()) {
1649 bool enable_breakpad
= GetCrashReporterClient()->GetCollectStatsConsent() ||
1650 GetCrashReporterClient()->IsRunningUnattended();
1652 !parsed_command_line
.HasSwitch(switches::kDisableBreakpad
);
1653 if (!enable_breakpad
) {
1654 enable_breakpad
= parsed_command_line
.HasSwitch(
1655 switches::kEnableCrashReporterForTesting
);
1657 if (!enable_breakpad
) {
1658 VLOG(1) << "Breakpad disabled";
1663 EnableCrashDumping(GetCrashReporterClient()->IsRunningUnattended());
1664 } else if (GetCrashReporterClient()->EnableBreakpadForProcess(process_type
)) {
1665 #if defined(OS_ANDROID)
1666 NOTREACHED() << "Breakpad initialized with InitCrashReporter() instead of "
1667 "InitNonBrowserCrashReporter in " << process_type
<< " process.";
1670 // We might be chrooted in a zygote or renderer process so we cannot call
1671 // GetCollectStatsConsent because that needs access the the user's home
1672 // dir. Instead, we set a command line flag for these processes.
1673 // Even though plugins are not chrooted, we share the same code path for
1675 if (!parsed_command_line
.HasSwitch(switches::kEnableCrashReporter
))
1678 SetClientIdFromCommandLine(parsed_command_line
);
1679 EnableNonBrowserCrashDumping();
1680 VLOG(1) << "Non Browser crash dumping enabled for: " << process_type
;
1681 #endif // #if defined(OS_ANDROID)
1684 PostEnableBreakpadInitialization();
1687 #if defined(OS_ANDROID)
1688 void InitNonBrowserCrashReporterForAndroid(const std::string
& process_type
) {
1689 const base::CommandLine
* command_line
=
1690 base::CommandLine::ForCurrentProcess();
1692 // Handler registration is LIFO. Install the microdump handler first, such
1693 // that if conventional minidump crash reporting is enabled below, it takes
1694 // precedence (i.e. its handler is run first) over the microdump handler.
1695 InitMicrodumpCrashHandlerIfNecessary(process_type
);
1697 if (command_line
->HasSwitch(switches::kEnableCrashReporter
)) {
1698 // On Android we need to provide a FD to the file where the minidump is
1699 // generated as the renderer and browser run with different UIDs
1700 // (preventing the browser from inspecting the renderer process).
1701 int minidump_fd
= base::GlobalDescriptors::GetInstance()->MaybeGet(
1702 GetCrashReporterClient()->GetAndroidMinidumpDescriptor());
1703 if (minidump_fd
< 0) {
1704 NOTREACHED() << "Could not find minidump FD, crash reporting disabled.";
1707 EnableNonBrowserCrashDumping(process_type
, minidump_fd
);
1711 #endif // OS_ANDROID
1713 bool IsCrashReporterEnabled() {
1714 return g_is_crash_reporter_enabled
;
1717 } // namespace breakpad