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 #include "components/breakpad/app/breakpad_win.h"
16 #include "base/base_switches.h"
17 #include "base/basictypes.h"
18 #include "base/command_line.h"
19 #include "base/debug/crash_logging.h"
20 #include "base/environment.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/string_split.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/win/metro.h"
28 #include "base/win/pe_image.h"
29 #include "base/win/registry.h"
30 #include "base/win/win_util.h"
31 #include "breakpad/src/client/windows/handler/exception_handler.h"
32 #include "components/breakpad/app/breakpad_client.h"
33 #include "components/breakpad/app/hard_error_handler_win.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/result_codes.h"
36 #include "sandbox/win/src/nt_internals.h"
37 #include "sandbox/win/src/sidestep/preamble_patcher.h"
39 // userenv.dll is required for GetProfileType().
40 #pragma comment(lib, "userenv.lib")
42 #pragma intrinsic(_AddressOfReturnAddress)
43 #pragma intrinsic(_ReturnAddress)
47 // TODO(raymes): Modify the way custom crash info is stored. g_custom_entries
48 // is way too too fragile. See
49 // https://code.google.com/p/chromium/issues/detail?id=137062.
50 std::vector<google_breakpad::CustomInfoEntry>* g_custom_entries = NULL;
51 bool g_deferred_crash_uploads = false;
55 // Minidump with stacks, PEB, TEB, and unloaded module list.
56 const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(
57 MiniDumpWithProcessThreadData | // Get PEB and TEB.
58 MiniDumpWithUnloadedModules); // Get unloaded modules when available.
60 // Minidump with all of the above, plus memory referenced from stack.
61 const MINIDUMP_TYPE kLargerDumpType = static_cast<MINIDUMP_TYPE>(
62 MiniDumpWithProcessThreadData | // Get PEB and TEB.
63 MiniDumpWithUnloadedModules | // Get unloaded modules when available.
64 MiniDumpWithIndirectlyReferencedMemory); // Get memory referenced by stack.
66 // Large dump with all process memory.
67 const MINIDUMP_TYPE kFullDumpType = static_cast<MINIDUMP_TYPE>(
68 MiniDumpWithFullMemory | // Full memory from process.
69 MiniDumpWithProcessThreadData | // Get PEB and TEB.
70 MiniDumpWithHandleData | // Get all handle information.
71 MiniDumpWithUnloadedModules); // Get unloaded modules when available.
73 const char kPipeNameVar[] = "CHROME_BREAKPAD_PIPE_NAME";
75 const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
76 const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
78 // This is the well known SID for the system principal.
79 const wchar_t kSystemPrincipalSid[] =L"S-1-5-18";
81 google_breakpad::ExceptionHandler* g_breakpad = NULL;
82 google_breakpad::ExceptionHandler* g_dumphandler_no_crash = NULL;
84 EXCEPTION_POINTERS g_surrogate_exception_pointers = {0};
85 EXCEPTION_RECORD g_surrogate_exception_record = {0};
86 CONTEXT g_surrogate_context = {0};
88 typedef NTSTATUS (WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle,
90 char* g_real_terminate_process_stub = NULL;
92 static size_t g_dynamic_keys_offset = 0;
93 typedef std::map<std::wstring, google_breakpad::CustomInfoEntry*>
95 DynamicEntriesMap* g_dynamic_entries = NULL;
96 // Allow for 128 entries. POSIX uses 64 entries of 256 bytes, so Windows needs
97 // 256 entries of 64 bytes to match. See CustomInfoEntry::kValueMaxLength in
99 const size_t kMaxDynamicEntries = 256;
101 // Maximum length for plugin path to include in plugin crash reports.
102 const size_t kMaxPluginPathLength = 256;
104 // Dumps the current process memory.
105 extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
107 g_breakpad->WriteMinidump();
111 // Used for dumping a process state when there is no crash.
112 extern "C" void __declspec(dllexport) __cdecl DumpProcessWithoutCrash() {
113 if (g_dumphandler_no_crash) {
114 g_dumphandler_no_crash->WriteMinidump();
118 // We need to prevent ICF from folding DumpForHangDebuggingThread() and
119 // DumpProcessWithoutCrashThread() together, since that makes them
120 // indistinguishable in crash dumps. We do this by making the function
121 // bodies unique, and prevent optimization from shuffling things around.
122 MSVC_DISABLE_OPTIMIZE()
123 MSVC_PUSH_DISABLE_WARNING(4748)
125 DWORD WINAPI DumpProcessWithoutCrashThread(void*) {
126 DumpProcessWithoutCrash();
130 // The following two functions do exactly the same thing as the two above. But
131 // we want the signatures to be different so that we can easily track them in
133 // TODO(yzshen): Remove when enough information is collected and the hang rate
134 // of pepper/renderer processes is reduced.
135 DWORD WINAPI DumpForHangDebuggingThread(void*) {
136 DumpProcessWithoutCrash();
137 LOG(INFO) << "dumped for hang debugging";
142 MSVC_ENABLE_OPTIMIZE()
144 // Injects a thread into a remote process to dump state when there is no crash.
145 extern "C" HANDLE __declspec(dllexport) __cdecl
146 InjectDumpProcessWithoutCrash(HANDLE process) {
147 return CreateRemoteThread(process, NULL, 0, DumpProcessWithoutCrashThread,
151 extern "C" HANDLE __declspec(dllexport) __cdecl
152 InjectDumpForHangDebugging(HANDLE process) {
153 return CreateRemoteThread(process, NULL, 0, DumpForHangDebuggingThread,
157 extern "C" void DumpProcessAbnormalSignature() {
160 g_custom_entries->push_back(
161 google_breakpad::CustomInfoEntry(L"unusual-crash-signature", L""));
162 g_breakpad->WriteMinidump();
165 // Reduces the size of the string |str| to a max of 64 chars. Required because
166 // breakpad's CustomInfoEntry raises an invalid_parameter error if the string
167 // we want to set is longer.
168 std::wstring TrimToBreakpadMax(const std::wstring& str) {
169 std::wstring shorter(str);
170 return shorter.substr(0,
171 google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
174 static void SetIntegerValue(size_t offset, int value) {
175 if (!g_custom_entries)
178 base::wcslcpy((*g_custom_entries)[offset].value,
179 base::StringPrintf(L"%d", value).c_str(),
180 google_breakpad::CustomInfoEntry::kValueMaxLength);
183 // Appends the plugin path to |g_custom_entries|.
184 void SetPluginPath(const std::wstring& path) {
185 DCHECK(g_custom_entries);
187 if (path.size() > kMaxPluginPathLength) {
188 // If the path is too long, truncate from the start rather than the end,
189 // since we want to be able to recover the DLL name.
190 SetPluginPath(path.substr(path.size() - kMaxPluginPathLength));
194 // The chunk size without terminator.
195 const size_t kChunkSize = static_cast<size_t>(
196 google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
199 size_t chunk_start = 0; // Current position inside |path|
201 for (chunk_start = 0; chunk_start < path.size(); chunk_index++) {
202 size_t chunk_length = std::min(kChunkSize, path.size() - chunk_start);
204 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
205 base::StringPrintf(L"plugin-path-chunk-%i", chunk_index + 1).c_str(),
206 path.substr(chunk_start, chunk_length).c_str()));
208 chunk_start += chunk_length;
212 // Appends the breakpad dump path to |g_custom_entries|.
213 void SetBreakpadDumpPath() {
214 DCHECK(g_custom_entries);
215 base::FilePath crash_dumps_dir_path;
216 if (GetBreakpadClient()->GetAlternativeCrashDumpLocation(
217 &crash_dumps_dir_path)) {
218 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
219 L"breakpad-dump-location", crash_dumps_dir_path.value().c_str()));
223 // Returns a string containing a list of all modifiers for the loaded profile.
224 std::wstring GetProfileType() {
225 std::wstring profile_type;
226 DWORD profile_bits = 0;
227 if (::GetProfileType(&profile_bits)) {
228 static const struct {
232 { PT_MANDATORY, L"mandatory" },
233 { PT_ROAMING, L"roaming" },
234 { PT_TEMPORARY, L"temporary" },
236 for (size_t i = 0; i < arraysize(kBitNames); ++i) {
237 const DWORD this_bit = kBitNames[i].bit;
238 if ((profile_bits & this_bit) != 0) {
239 profile_type.append(kBitNames[i].name);
240 profile_bits &= ~this_bit;
241 if (profile_bits != 0)
242 profile_type.append(L", ");
246 DWORD last_error = ::GetLastError();
247 base::SStringPrintf(&profile_type, L"error %u", last_error);
252 // Returns the custom info structure based on the dll in parameter and the
254 google_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& exe_path,
255 const std::wstring& type) {
256 base::string16 version, product;
257 base::string16 special_build;
258 base::string16 channel_name;
259 GetBreakpadClient()->GetProductNameAndVersion(
260 base::FilePath(exe_path),
266 // We only expect this method to be called once per process.
267 DCHECK(!g_custom_entries);
268 g_custom_entries = new std::vector<google_breakpad::CustomInfoEntry>;
270 // Common g_custom_entries.
271 g_custom_entries->push_back(
272 google_breakpad::CustomInfoEntry(L"ver", UTF16ToWide(version).c_str()));
273 g_custom_entries->push_back(
274 google_breakpad::CustomInfoEntry(L"prod", UTF16ToWide(product).c_str()));
275 g_custom_entries->push_back(
276 google_breakpad::CustomInfoEntry(L"plat", L"Win32"));
277 g_custom_entries->push_back(
278 google_breakpad::CustomInfoEntry(L"ptype", type.c_str()));
279 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
280 L"channel", base::UTF16ToWide(channel_name).c_str()));
281 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
282 L"profile-type", GetProfileType().c_str()));
284 if (g_deferred_crash_uploads)
285 g_custom_entries->push_back(
286 google_breakpad::CustomInfoEntry(L"deferred-upload", L"true"));
288 if (!special_build.empty())
289 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
290 L"special", UTF16ToWide(special_build).c_str()));
292 if (type == L"plugin" || type == L"ppapi") {
293 std::wstring plugin_path =
294 CommandLine::ForCurrentProcess()->GetSwitchValueNative("plugin-path");
295 if (!plugin_path.empty())
296 SetPluginPath(plugin_path);
299 // Check whether configuration management controls crash reporting.
300 bool crash_reporting_enabled = true;
301 bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
302 &crash_reporting_enabled);
303 const CommandLine& command = *CommandLine::ForCurrentProcess();
304 bool use_crash_service =
305 !controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
306 GetBreakpadClient()->IsRunningUnattended());
307 if (use_crash_service)
308 SetBreakpadDumpPath();
310 // Create space for dynamic ad-hoc keys. The names and values are set using
311 // the API defined in base/debug/crash_logging.h.
312 g_dynamic_keys_offset = g_custom_entries->size();
313 for (size_t i = 0; i < kMaxDynamicEntries; ++i) {
314 // The names will be mutated as they are set. Un-numbered since these are
315 // merely placeholders. The name cannot be empty because Breakpad's
316 // HTTPUpload will interpret that as an invalid parameter.
317 g_custom_entries->push_back(
318 google_breakpad::CustomInfoEntry(L"unspecified-crash-key", L""));
320 g_dynamic_entries = new DynamicEntriesMap;
322 static google_breakpad::CustomClientInfo custom_client_info;
323 custom_client_info.entries = &g_custom_entries->front();
324 custom_client_info.count = g_custom_entries->size();
326 return &custom_client_info;
329 // This callback is used when we want to get a dump without crashing the
331 bool DumpDoneCallbackWhenNoCrash(const wchar_t*, const wchar_t*, void*,
332 EXCEPTION_POINTERS* ex_info,
333 MDRawAssertionInfo*, bool) {
337 // This callback is executed when the browser process has crashed, after
338 // the crash dump has been created. We need to minimize the amount of work
339 // done here since we have potentially corrupted process. Our job is to
340 // spawn another instance of chrome which will show a 'chrome has crashed'
341 // dialog. This code needs to live in the exe and thus has no access to
342 // facilities such as the i18n helpers.
343 bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
344 EXCEPTION_POINTERS* ex_info,
345 MDRawAssertionInfo*, bool) {
346 // Check if the exception is one of the kind which would not be solved
347 // by simply restarting chrome. In this case we show a message box with
348 // and exit silently. Remember that chrome is in a crashed state so we
349 // can't show our own UI from this process.
350 if (HardErrorHandler(ex_info))
353 if (!GetBreakpadClient()->AboutToRestart())
356 // Now we just start chrome browser with the same command line.
357 STARTUPINFOW si = {sizeof(si)};
358 PROCESS_INFORMATION pi;
359 if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
360 CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
361 ::CloseHandle(pi.hProcess);
362 ::CloseHandle(pi.hThread);
364 // After this return we will be terminated. The actual return value is
369 // flag to indicate that we are already handling an exception.
370 volatile LONG handling_exception = 0;
372 // This callback is used when there is no crash. Note: Unlike the
373 // |FilterCallback| below this does not do dupe detection. It is upto the caller
375 bool FilterCallbackWhenNoCrash(
376 void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
377 GetBreakpadClient()->RecordCrashDumpAttempt(false);
381 // This callback is executed when the Chrome process has crashed and *before*
382 // the crash dump is created. To prevent duplicate crash reports we
383 // make every thread calling this method, except the very first one,
385 bool FilterCallback(void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
386 // Capture every thread except the first one in the sleep. We don't
387 // want multiple threads to concurrently report exceptions.
388 if (::InterlockedCompareExchange(&handling_exception, 1, 0) == 1) {
391 GetBreakpadClient()->RecordCrashDumpAttempt(true);
395 // Previous unhandled filter. Will be called if not null when we
396 // intercept a crash.
397 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
399 // Exception filter used when breakpad is not enabled. We just display
400 // the "Do you want to restart" message and then we call the previous filter.
401 long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
402 DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
405 return previous_filter(info);
407 return EXCEPTION_EXECUTE_HANDLER;
410 // Exception filter for the service process used when breakpad is not enabled.
411 // We just display the "Do you want to restart" message and then die
412 // (without calling the previous filter).
413 long WINAPI ServiceExceptionFilter(EXCEPTION_POINTERS* info) {
414 DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
415 return EXCEPTION_EXECUTE_HANDLER;
418 // NOTE: This function is used by SyzyASAN to annotate crash reports. If you
419 // change the name or signature of this function you will break SyzyASAN
420 // instrumented releases of Chrome. Please contact syzygy-team@chromium.org
422 extern "C" void __declspec(dllexport) __cdecl SetCrashKeyValueImpl(
423 const wchar_t* key, const wchar_t* value) {
424 if (!g_dynamic_entries)
427 // CustomInfoEntry limits the length of key and value. If they exceed
428 // their maximum length the underlying string handling functions raise
429 // an exception and prematurely trigger a crash. Truncate here.
430 std::wstring safe_key(std::wstring(key).substr(
431 0, google_breakpad::CustomInfoEntry::kNameMaxLength - 1));
432 std::wstring safe_value(std::wstring(value).substr(
433 0, google_breakpad::CustomInfoEntry::kValueMaxLength - 1));
435 // If we already have a value for this key, update it; otherwise, insert
436 // the new value if we have not exhausted the pre-allocated slots for dynamic
438 DynamicEntriesMap::iterator it = g_dynamic_entries->find(safe_key);
439 google_breakpad::CustomInfoEntry* entry = NULL;
440 if (it == g_dynamic_entries->end()) {
441 if (g_dynamic_entries->size() >= kMaxDynamicEntries)
443 entry = &(*g_custom_entries)[g_dynamic_keys_offset++];
444 g_dynamic_entries->insert(std::make_pair(safe_key, entry));
449 entry->set(safe_key.data(), safe_value.data());
452 extern "C" void __declspec(dllexport) __cdecl ClearCrashKeyValueImpl(
453 const wchar_t* key) {
454 if (!g_dynamic_entries)
457 std::wstring key_string(key);
458 DynamicEntriesMap::iterator it = g_dynamic_entries->find(key_string);
459 if (it == g_dynamic_entries->end())
462 it->second->set_value(NULL);
467 bool WrapMessageBoxWithSEH(const wchar_t* text, const wchar_t* caption,
468 UINT flags, bool* exit_now) {
469 // We wrap the call to MessageBoxW with a SEH handler because it some
470 // machines with CursorXP, PeaDict or with FontExplorer installed it crashes
471 // uncontrollably here. Being this a best effort deal we better go away.
473 *exit_now = (IDOK != ::MessageBoxW(NULL, text, caption, flags));
474 } __except(EXCEPTION_EXECUTE_HANDLER) {
475 // Its not safe to continue executing, exit silently here.
476 ::TerminateProcess(::GetCurrentProcess(),
477 GetBreakpadClient()->GetResultCodeRespawnFailed());
483 // This function is executed by the child process that DumpDoneCallback()
484 // spawned and basically just shows the 'chrome has crashed' dialog if
485 // the CHROME_CRASHED environment variable is present.
486 bool ShowRestartDialogIfCrashed(bool* exit_now) {
487 // If we are being launched in metro mode don't try to show the dialog.
488 if (base::win::IsMetroProcess())
491 // Only show this for the browser process. See crbug.com/132119.
492 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
493 std::string process_type =
494 command_line.GetSwitchValueASCII(switches::kProcessType);
495 if (!process_type.empty())
498 base::string16 message;
499 base::string16 title;
501 if (!GetBreakpadClient()->ShouldShowRestartDialog(
502 &title, &message, &is_rtl_locale)) {
506 // If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
507 // flags so that an RTL message box is displayed.
508 UINT flags = MB_OKCANCEL | MB_ICONWARNING;
510 flags |= MB_RIGHT | MB_RTLREADING;
512 return WrapMessageBoxWithSEH(base::UTF16ToWide(message).c_str(),
513 base::UTF16ToWide(title).c_str(),
518 // Crashes the process after generating a dump for the provided exception. Note
519 // that the crash reporter should be initialized before calling this function
520 // for it to do anything.
521 // NOTE: This function is used by SyzyASAN to invoke a crash. If you change the
522 // the name or signature of this function you will break SyzyASAN instrumented
523 // releases of Chrome. Please contact syzygy-team@chromium.org before doing so!
524 extern "C" int __declspec(dllexport) CrashForException(
525 EXCEPTION_POINTERS* info) {
527 g_breakpad->WriteMinidumpForException(info);
528 // Patched stub exists based on conditions (See InitCrashReporter).
529 // As a side note this function also gets called from
530 // WindowProcExceptionFilter.
531 if (g_real_terminate_process_stub == NULL) {
532 ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
534 NtTerminateProcessPtr real_terminate_proc =
535 reinterpret_cast<NtTerminateProcessPtr>(
536 static_cast<char*>(g_real_terminate_process_stub));
537 real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
540 return EXCEPTION_CONTINUE_SEARCH;
543 NTSTATUS WINAPI HookNtTerminateProcess(HANDLE ProcessHandle,
544 NTSTATUS ExitStatus) {
546 (ProcessHandle == ::GetCurrentProcess() || ProcessHandle == NULL)) {
547 NT_TIB* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
548 void* address_on_stack = _AddressOfReturnAddress();
549 if (address_on_stack < tib->StackLimit ||
550 address_on_stack > tib->StackBase) {
551 g_surrogate_exception_record.ExceptionAddress = _ReturnAddress();
552 g_surrogate_exception_record.ExceptionCode = DBG_TERMINATE_PROCESS;
553 g_surrogate_exception_record.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
554 CrashForException(&g_surrogate_exception_pointers);
558 NtTerminateProcessPtr real_proc =
559 reinterpret_cast<NtTerminateProcessPtr>(
560 static_cast<char*>(g_real_terminate_process_stub));
561 return real_proc(ProcessHandle, ExitStatus);
564 static void InitTerminateProcessHooks() {
565 NtTerminateProcessPtr terminate_process_func_address =
566 reinterpret_cast<NtTerminateProcessPtr>(::GetProcAddress(
567 ::GetModuleHandle(L"ntdll.dll"), "NtTerminateProcess"));
568 if (terminate_process_func_address == NULL)
571 DWORD old_protect = 0;
572 if (!::VirtualProtect(terminate_process_func_address, 5,
573 PAGE_EXECUTE_READWRITE, &old_protect))
576 g_real_terminate_process_stub = reinterpret_cast<char*>(VirtualAllocEx(
577 ::GetCurrentProcess(), NULL, sidestep::kMaxPreambleStubSize,
578 MEM_COMMIT, PAGE_EXECUTE_READWRITE));
579 if (g_real_terminate_process_stub == NULL)
582 g_surrogate_exception_pointers.ContextRecord = &g_surrogate_context;
583 g_surrogate_exception_pointers.ExceptionRecord =
584 &g_surrogate_exception_record;
586 sidestep::SideStepError patch_result =
587 sidestep::PreamblePatcher::Patch(
588 terminate_process_func_address, HookNtTerminateProcess,
589 g_real_terminate_process_stub, sidestep::kMaxPreambleStubSize);
590 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
591 CHECK(::VirtualFreeEx(::GetCurrentProcess(), g_real_terminate_process_stub,
593 CHECK(::VirtualProtect(terminate_process_func_address, 5, old_protect,
599 CHECK(::VirtualProtect(terminate_process_func_address,
603 CHECK(::VirtualProtect(g_real_terminate_process_stub,
604 sidestep::kMaxPreambleStubSize,
609 static void InitPipeNameEnvVar(bool is_per_user_install) {
610 scoped_ptr<base::Environment> env(base::Environment::Create());
611 if (env->HasVar(kPipeNameVar)) {
612 // The Breakpad pipe name is already configured: nothing to do.
616 // Check whether configuration management controls crash reporting.
617 bool crash_reporting_enabled = true;
618 bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
619 &crash_reporting_enabled);
621 const CommandLine& command = *CommandLine::ForCurrentProcess();
622 bool use_crash_service =
623 !controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
624 GetBreakpadClient()->IsRunningUnattended());
626 std::wstring pipe_name;
627 if (use_crash_service) {
628 // Crash reporting is done by crash_service.exe.
629 pipe_name = kChromePipeName;
631 // We want to use the Google Update crash reporting. We need to check if the
632 // user allows it first (in case the administrator didn't already decide
634 if (!controlled_by_policy)
635 crash_reporting_enabled = GetBreakpadClient()->GetCollectStatsConsent();
637 if (!crash_reporting_enabled) {
638 if (!controlled_by_policy &&
639 GetBreakpadClient()->GetDeferredUploadsSupported(
640 is_per_user_install)) {
641 g_deferred_crash_uploads = true;
647 // Build the pipe name. It can be either:
648 // System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
649 // Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
650 std::wstring user_sid;
651 if (is_per_user_install) {
652 if (!base::win::GetUserSidString(&user_sid)) {
656 user_sid = kSystemPrincipalSid;
659 pipe_name = kGoogleUpdatePipeName;
660 pipe_name += user_sid;
662 env->SetVar(kPipeNameVar, WideToASCII(pipe_name));
665 void InitDefaultCrashCallback(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
666 previous_filter = SetUnhandledExceptionFilter(filter);
669 void InitCrashReporter() {
670 const CommandLine& command = *CommandLine::ForCurrentProcess();
671 if (command.HasSwitch(switches::kDisableBreakpad))
674 // Disable the message box for assertions.
675 _CrtSetReportMode(_CRT_ASSERT, 0);
677 std::wstring process_type =
678 command.GetSwitchValueNative(switches::kProcessType);
679 if (process_type.empty())
680 process_type = L"browser";
682 wchar_t exe_path[MAX_PATH];
684 GetModuleFileNameW(NULL, exe_path, MAX_PATH);
686 bool is_per_user_install =
687 GetBreakpadClient()->GetIsPerUserInstall(base::FilePath(exe_path));
689 google_breakpad::CustomClientInfo* custom_info =
690 GetCustomInfo(exe_path, process_type);
692 google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
693 LPTOP_LEVEL_EXCEPTION_FILTER default_filter = NULL;
694 // We install the post-dump callback only for the browser and service
695 // processes. It spawns a new browser/service process.
696 if (process_type == L"browser") {
697 callback = &DumpDoneCallback;
698 default_filter = &ChromeExceptionFilter;
699 } else if (process_type == L"service") {
700 callback = &DumpDoneCallback;
701 default_filter = &ServiceExceptionFilter;
704 if (process_type == L"browser") {
705 InitPipeNameEnvVar(is_per_user_install);
706 GetBreakpadClient()->InitBrowserCrashDumpsRegKey();
709 scoped_ptr<base::Environment> env(base::Environment::Create());
710 std::string pipe_name_ascii;
711 if (!env->GetVar(kPipeNameVar, &pipe_name_ascii)) {
712 // Breakpad is not enabled. Configuration is managed or the user
713 // did not allow Google Update to send crashes. We need to use
714 // our default crash handler instead, but only for the
715 // browser/service processes.
717 InitDefaultCrashCallback(default_filter);
720 std::wstring pipe_name = ASCIIToWide(pipe_name_ascii);
723 // The protocol for connecting to the out-of-process Breakpad crash
724 // reporter is different for x86-32 and x86-64: the message sizes
725 // are different because the message struct contains a pointer. As
726 // a result, there are two different named pipes to connect to. The
727 // 64-bit one is distinguished with an "-x64" suffix.
728 pipe_name += L"-x64";
731 // Get the alternate dump directory. We use the temp path.
732 wchar_t temp_dir[MAX_PATH] = {0};
733 ::GetTempPathW(MAX_PATH, temp_dir);
735 MINIDUMP_TYPE dump_type = kSmallDumpType;
736 // Capture full memory if explicitly instructed to.
737 if (command.HasSwitch(switches::kFullMemoryCrashReport))
738 dump_type = kFullDumpType;
739 else if (GetBreakpadClient()->GetShouldDumpLargerDumps(is_per_user_install))
740 dump_type = kLargerDumpType;
742 g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, &FilterCallback,
744 google_breakpad::ExceptionHandler::HANDLER_ALL,
745 dump_type, pipe_name.c_str(), custom_info);
747 // Now initialize the non crash dump handler.
748 g_dumphandler_no_crash = new google_breakpad::ExceptionHandler(temp_dir,
749 &FilterCallbackWhenNoCrash,
750 &DumpDoneCallbackWhenNoCrash,
752 // Set the handler to none so this handler would not be added to
753 // |handler_stack_| in |ExceptionHandler| which is a list of exception
755 google_breakpad::ExceptionHandler::HANDLER_NONE,
756 dump_type, pipe_name.c_str(), custom_info);
758 if (g_breakpad->IsOutOfProcess()) {
759 // Tells breakpad to handle breakpoint and single step exceptions.
760 // This might break JIT debuggers, but at least it will always
761 // generate a crashdump for these exceptions.
762 g_breakpad->set_handle_debug_exceptions(true);
765 if (process_type != L"browser" &&
766 !GetBreakpadClient()->IsRunningUnattended()) {
767 // Initialize the hook TerminateProcess to catch unexpected exits.
768 InitTerminateProcessHooks();
774 } // namespace breakpad