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/debug/dump_without_crashing.h"
21 #include "base/environment.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/win/metro.h"
29 #include "base/win/pe_image.h"
30 #include "base/win/registry.h"
31 #include "base/win/win_util.h"
32 #include "breakpad/src/client/windows/handler/exception_handler.h"
33 #include "components/breakpad/app/breakpad_client.h"
34 #include "components/breakpad/app/hard_error_handler_win.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 std::vector<google_breakpad::CustomInfoEntry>* g_custom_entries = NULL;
48 bool g_deferred_crash_uploads = false;
52 // Minidump with stacks, PEB, TEB, and unloaded module list.
53 const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(
54 MiniDumpWithProcessThreadData | // Get PEB and TEB.
55 MiniDumpWithUnloadedModules); // Get unloaded modules when available.
57 // Minidump with all of the above, plus memory referenced from stack.
58 const MINIDUMP_TYPE kLargerDumpType = static_cast<MINIDUMP_TYPE>(
59 MiniDumpWithProcessThreadData | // Get PEB and TEB.
60 MiniDumpWithUnloadedModules | // Get unloaded modules when available.
61 MiniDumpWithIndirectlyReferencedMemory); // Get memory referenced by stack.
63 // Large dump with all process memory.
64 const MINIDUMP_TYPE kFullDumpType = static_cast<MINIDUMP_TYPE>(
65 MiniDumpWithFullMemory | // Full memory from process.
66 MiniDumpWithProcessThreadData | // Get PEB and TEB.
67 MiniDumpWithHandleData | // Get all handle information.
68 MiniDumpWithUnloadedModules); // Get unloaded modules when available.
70 const char kPipeNameVar[] = "CHROME_BREAKPAD_PIPE_NAME";
72 const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
73 const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
75 // This is the well known SID for the system principal.
76 const wchar_t kSystemPrincipalSid[] =L"S-1-5-18";
78 google_breakpad::ExceptionHandler* g_breakpad = NULL;
79 google_breakpad::ExceptionHandler* g_dumphandler_no_crash = NULL;
81 EXCEPTION_POINTERS g_surrogate_exception_pointers = {0};
82 EXCEPTION_RECORD g_surrogate_exception_record = {0};
83 CONTEXT g_surrogate_context = {0};
85 typedef NTSTATUS (WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle,
87 char* g_real_terminate_process_stub = NULL;
89 static size_t g_dynamic_keys_offset = 0;
90 typedef std::map<std::wstring, google_breakpad::CustomInfoEntry*>
92 DynamicEntriesMap* g_dynamic_entries = NULL;
93 // Allow for 128 entries. POSIX uses 64 entries of 256 bytes, so Windows needs
94 // 256 entries of 64 bytes to match. See CustomInfoEntry::kValueMaxLength in
96 const size_t kMaxDynamicEntries = 256;
98 // Maximum length for plugin path to include in plugin crash reports.
99 const size_t kMaxPluginPathLength = 256;
101 // Dumps the current process memory.
102 extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
104 g_breakpad->WriteMinidump();
108 // Used for dumping a process state when there is no crash.
109 extern "C" void __declspec(dllexport) __cdecl DumpProcessWithoutCrash() {
110 if (g_dumphandler_no_crash) {
111 g_dumphandler_no_crash->WriteMinidump();
115 // We need to prevent ICF from folding DumpForHangDebuggingThread() and
116 // DumpProcessWithoutCrashThread() together, since that makes them
117 // indistinguishable in crash dumps. We do this by making the function
118 // bodies unique, and prevent optimization from shuffling things around.
119 MSVC_DISABLE_OPTIMIZE()
120 MSVC_PUSH_DISABLE_WARNING(4748)
122 DWORD WINAPI DumpProcessWithoutCrashThread(void*) {
123 DumpProcessWithoutCrash();
127 // The following two functions do exactly the same thing as the two above. But
128 // we want the signatures to be different so that we can easily track them in
130 // TODO(yzshen): Remove when enough information is collected and the hang rate
131 // of pepper/renderer processes is reduced.
132 DWORD WINAPI DumpForHangDebuggingThread(void*) {
133 DumpProcessWithoutCrash();
134 VLOG(1) << "dumped for hang debugging";
139 MSVC_ENABLE_OPTIMIZE()
141 // Injects a thread into a remote process to dump state when there is no crash.
142 extern "C" HANDLE __declspec(dllexport) __cdecl
143 InjectDumpProcessWithoutCrash(HANDLE process) {
144 return CreateRemoteThread(process, NULL, 0, DumpProcessWithoutCrashThread,
148 extern "C" HANDLE __declspec(dllexport) __cdecl
149 InjectDumpForHangDebugging(HANDLE process) {
150 return CreateRemoteThread(process, NULL, 0, DumpForHangDebuggingThread,
154 extern "C" void DumpProcessAbnormalSignature() {
157 g_custom_entries->push_back(
158 google_breakpad::CustomInfoEntry(L"unusual-crash-signature", L""));
159 g_breakpad->WriteMinidump();
162 // Reduces the size of the string |str| to a max of 64 chars. Required because
163 // breakpad's CustomInfoEntry raises an invalid_parameter error if the string
164 // we want to set is longer.
165 std::wstring TrimToBreakpadMax(const std::wstring& str) {
166 std::wstring shorter(str);
167 return shorter.substr(0,
168 google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
171 static void SetIntegerValue(size_t offset, int value) {
172 if (!g_custom_entries)
175 base::wcslcpy((*g_custom_entries)[offset].value,
176 base::StringPrintf(L"%d", value).c_str(),
177 google_breakpad::CustomInfoEntry::kValueMaxLength);
180 // Appends the plugin path to |g_custom_entries|.
181 void SetPluginPath(const std::wstring& path) {
182 DCHECK(g_custom_entries);
184 if (path.size() > kMaxPluginPathLength) {
185 // If the path is too long, truncate from the start rather than the end,
186 // since we want to be able to recover the DLL name.
187 SetPluginPath(path.substr(path.size() - kMaxPluginPathLength));
191 // The chunk size without terminator.
192 const size_t kChunkSize = static_cast<size_t>(
193 google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
196 size_t chunk_start = 0; // Current position inside |path|
198 for (chunk_start = 0; chunk_start < path.size(); chunk_index++) {
199 size_t chunk_length = std::min(kChunkSize, path.size() - chunk_start);
201 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
202 base::StringPrintf(L"plugin-path-chunk-%i", chunk_index + 1).c_str(),
203 path.substr(chunk_start, chunk_length).c_str()));
205 chunk_start += chunk_length;
209 // Appends the breakpad dump path to |g_custom_entries|.
210 void SetBreakpadDumpPath() {
211 DCHECK(g_custom_entries);
212 base::FilePath crash_dumps_dir_path;
213 if (GetBreakpadClient()->GetAlternativeCrashDumpLocation(
214 &crash_dumps_dir_path)) {
215 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
216 L"breakpad-dump-location", crash_dumps_dir_path.value().c_str()));
220 // Returns a string containing a list of all modifiers for the loaded profile.
221 std::wstring GetProfileType() {
222 std::wstring profile_type;
223 DWORD profile_bits = 0;
224 if (::GetProfileType(&profile_bits)) {
225 static const struct {
229 { PT_MANDATORY, L"mandatory" },
230 { PT_ROAMING, L"roaming" },
231 { PT_TEMPORARY, L"temporary" },
233 for (size_t i = 0; i < arraysize(kBitNames); ++i) {
234 const DWORD this_bit = kBitNames[i].bit;
235 if ((profile_bits & this_bit) != 0) {
236 profile_type.append(kBitNames[i].name);
237 profile_bits &= ~this_bit;
238 if (profile_bits != 0)
239 profile_type.append(L", ");
243 DWORD last_error = ::GetLastError();
244 base::SStringPrintf(&profile_type, L"error %u", last_error);
249 // Returns the custom info structure based on the dll in parameter and the
251 google_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& exe_path,
252 const std::wstring& type) {
253 base::string16 version, product;
254 base::string16 special_build;
255 base::string16 channel_name;
256 GetBreakpadClient()->GetProductNameAndVersion(
257 base::FilePath(exe_path),
263 // We only expect this method to be called once per process.
264 DCHECK(!g_custom_entries);
265 g_custom_entries = new std::vector<google_breakpad::CustomInfoEntry>;
267 // Common g_custom_entries.
268 g_custom_entries->push_back(
269 google_breakpad::CustomInfoEntry(L"ver",
270 base::UTF16ToWide(version).c_str()));
271 g_custom_entries->push_back(
272 google_breakpad::CustomInfoEntry(L"prod",
273 base::UTF16ToWide(product).c_str()));
274 g_custom_entries->push_back(
275 google_breakpad::CustomInfoEntry(L"plat", L"Win32"));
276 g_custom_entries->push_back(
277 google_breakpad::CustomInfoEntry(L"ptype", type.c_str()));
278 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
279 L"pid", base::StringPrintf(L"%d", ::GetCurrentProcessId()).c_str()));
280 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
281 L"channel", base::UTF16ToWide(channel_name).c_str()));
282 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
283 L"profile-type", GetProfileType().c_str()));
285 if (g_deferred_crash_uploads)
286 g_custom_entries->push_back(
287 google_breakpad::CustomInfoEntry(L"deferred-upload", L"true"));
289 if (!special_build.empty())
290 g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
291 L"special", base::UTF16ToWide(special_build).c_str()));
293 if (type == L"plugin" || type == L"ppapi") {
294 std::wstring plugin_path =
295 CommandLine::ForCurrentProcess()->GetSwitchValueNative("plugin-path");
296 if (!plugin_path.empty())
297 SetPluginPath(plugin_path);
300 // Check whether configuration management controls crash reporting.
301 bool crash_reporting_enabled = true;
302 bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
303 &crash_reporting_enabled);
304 const CommandLine& command = *CommandLine::ForCurrentProcess();
305 bool use_crash_service =
306 !controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
307 GetBreakpadClient()->IsRunningUnattended());
308 if (use_crash_service)
309 SetBreakpadDumpPath();
311 // Create space for dynamic ad-hoc keys. The names and values are set using
312 // the API defined in base/debug/crash_logging.h.
313 g_dynamic_keys_offset = g_custom_entries->size();
314 for (size_t i = 0; i < kMaxDynamicEntries; ++i) {
315 // The names will be mutated as they are set. Un-numbered since these are
316 // merely placeholders. The name cannot be empty because Breakpad's
317 // HTTPUpload will interpret that as an invalid parameter.
318 g_custom_entries->push_back(
319 google_breakpad::CustomInfoEntry(L"unspecified-crash-key", L""));
321 g_dynamic_entries = new DynamicEntriesMap;
323 static google_breakpad::CustomClientInfo custom_client_info;
324 custom_client_info.entries = &g_custom_entries->front();
325 custom_client_info.count = g_custom_entries->size();
327 return &custom_client_info;
330 // This callback is used when we want to get a dump without crashing the
332 bool DumpDoneCallbackWhenNoCrash(const wchar_t*, const wchar_t*, void*,
333 EXCEPTION_POINTERS* ex_info,
334 MDRawAssertionInfo*, bool) {
338 // This callback is executed when the browser process has crashed, after
339 // the crash dump has been created. We need to minimize the amount of work
340 // done here since we have potentially corrupted process. Our job is to
341 // spawn another instance of chrome which will show a 'chrome has crashed'
342 // dialog. This code needs to live in the exe and thus has no access to
343 // facilities such as the i18n helpers.
344 bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
345 EXCEPTION_POINTERS* ex_info,
346 MDRawAssertionInfo*, bool) {
347 // Check if the exception is one of the kind which would not be solved
348 // by simply restarting chrome. In this case we show a message box with
349 // and exit silently. Remember that chrome is in a crashed state so we
350 // can't show our own UI from this process.
351 if (HardErrorHandler(ex_info))
354 if (!GetBreakpadClient()->AboutToRestart())
357 // Now we just start chrome browser with the same command line.
358 STARTUPINFOW si = {sizeof(si)};
359 PROCESS_INFORMATION pi;
360 if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
361 CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
362 ::CloseHandle(pi.hProcess);
363 ::CloseHandle(pi.hThread);
365 // After this return we will be terminated. The actual return value is
370 // flag to indicate that we are already handling an exception.
371 volatile LONG handling_exception = 0;
373 // This callback is used when there is no crash. Note: Unlike the
374 // |FilterCallback| below this does not do dupe detection. It is upto the caller
376 bool FilterCallbackWhenNoCrash(
377 void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
378 GetBreakpadClient()->RecordCrashDumpAttempt(false);
382 // This callback is executed when the Chrome process has crashed and *before*
383 // the crash dump is created. To prevent duplicate crash reports we
384 // make every thread calling this method, except the very first one,
386 bool FilterCallback(void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
387 // Capture every thread except the first one in the sleep. We don't
388 // want multiple threads to concurrently report exceptions.
389 if (::InterlockedCompareExchange(&handling_exception, 1, 0) == 1) {
392 GetBreakpadClient()->RecordCrashDumpAttempt(true);
396 // Previous unhandled filter. Will be called if not null when we
397 // intercept a crash.
398 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
400 // Exception filter used when breakpad is not enabled. We just display
401 // the "Do you want to restart" message and then we call the previous filter.
402 long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
403 DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
406 return previous_filter(info);
408 return EXCEPTION_EXECUTE_HANDLER;
411 // Exception filter for the service process used when breakpad is not enabled.
412 // We just display the "Do you want to restart" message and then die
413 // (without calling the previous filter).
414 long WINAPI ServiceExceptionFilter(EXCEPTION_POINTERS* info) {
415 DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
416 return EXCEPTION_EXECUTE_HANDLER;
419 // NOTE: This function is used by SyzyASAN to annotate crash reports. If you
420 // change the name or signature of this function you will break SyzyASAN
421 // instrumented releases of Chrome. Please contact syzygy-team@chromium.org
423 extern "C" void __declspec(dllexport) __cdecl SetCrashKeyValueImpl(
424 const wchar_t* key, const wchar_t* value) {
425 if (!g_dynamic_entries)
428 // CustomInfoEntry limits the length of key and value. If they exceed
429 // their maximum length the underlying string handling functions raise
430 // an exception and prematurely trigger a crash. Truncate here.
431 std::wstring safe_key(std::wstring(key).substr(
432 0, google_breakpad::CustomInfoEntry::kNameMaxLength - 1));
433 std::wstring safe_value(std::wstring(value).substr(
434 0, google_breakpad::CustomInfoEntry::kValueMaxLength - 1));
436 // If we already have a value for this key, update it; otherwise, insert
437 // the new value if we have not exhausted the pre-allocated slots for dynamic
439 DynamicEntriesMap::iterator it = g_dynamic_entries->find(safe_key);
440 google_breakpad::CustomInfoEntry* entry = NULL;
441 if (it == g_dynamic_entries->end()) {
442 if (g_dynamic_entries->size() >= kMaxDynamicEntries)
444 entry = &(*g_custom_entries)[g_dynamic_keys_offset++];
445 g_dynamic_entries->insert(std::make_pair(safe_key, entry));
450 entry->set(safe_key.data(), safe_value.data());
453 extern "C" void __declspec(dllexport) __cdecl ClearCrashKeyValueImpl(
454 const wchar_t* key) {
455 if (!g_dynamic_entries)
458 std::wstring key_string(key);
459 DynamicEntriesMap::iterator it = g_dynamic_entries->find(key_string);
460 if (it == g_dynamic_entries->end())
463 it->second->set_value(NULL);
468 bool WrapMessageBoxWithSEH(const wchar_t* text, const wchar_t* caption,
469 UINT flags, bool* exit_now) {
470 // We wrap the call to MessageBoxW with a SEH handler because it some
471 // machines with CursorXP, PeaDict or with FontExplorer installed it crashes
472 // uncontrollably here. Being this a best effort deal we better go away.
474 *exit_now = (IDOK != ::MessageBoxW(NULL, text, caption, flags));
475 } __except(EXCEPTION_EXECUTE_HANDLER) {
476 // Its not safe to continue executing, exit silently here.
477 ::TerminateProcess(::GetCurrentProcess(),
478 GetBreakpadClient()->GetResultCodeRespawnFailed());
484 // This function is executed by the child process that DumpDoneCallback()
485 // spawned and basically just shows the 'chrome has crashed' dialog if
486 // the CHROME_CRASHED environment variable is present.
487 bool ShowRestartDialogIfCrashed(bool* exit_now) {
488 // If we are being launched in metro mode don't try to show the dialog.
489 if (base::win::IsMetroProcess())
492 base::string16 message;
493 base::string16 title;
495 if (!GetBreakpadClient()->ShouldShowRestartDialog(
496 &title, &message, &is_rtl_locale)) {
500 // If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
501 // flags so that an RTL message box is displayed.
502 UINT flags = MB_OKCANCEL | MB_ICONWARNING;
504 flags |= MB_RIGHT | MB_RTLREADING;
506 return WrapMessageBoxWithSEH(base::UTF16ToWide(message).c_str(),
507 base::UTF16ToWide(title).c_str(),
512 // Crashes the process after generating a dump for the provided exception. Note
513 // that the crash reporter should be initialized before calling this function
514 // for it to do anything.
515 // NOTE: This function is used by SyzyASAN to invoke a crash. If you change the
516 // the name or signature of this function you will break SyzyASAN instrumented
517 // releases of Chrome. Please contact syzygy-team@chromium.org before doing so!
518 extern "C" int __declspec(dllexport) CrashForException(
519 EXCEPTION_POINTERS* info) {
521 g_breakpad->WriteMinidumpForException(info);
522 // Patched stub exists based on conditions (See InitCrashReporter).
523 // As a side note this function also gets called from
524 // WindowProcExceptionFilter.
525 if (g_real_terminate_process_stub == NULL) {
526 ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
528 NtTerminateProcessPtr real_terminate_proc =
529 reinterpret_cast<NtTerminateProcessPtr>(
530 static_cast<char*>(g_real_terminate_process_stub));
531 real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
534 return EXCEPTION_CONTINUE_SEARCH;
537 NTSTATUS WINAPI HookNtTerminateProcess(HANDLE ProcessHandle,
538 NTSTATUS ExitStatus) {
540 (ProcessHandle == ::GetCurrentProcess() || ProcessHandle == NULL)) {
541 NT_TIB* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
542 void* address_on_stack = _AddressOfReturnAddress();
543 if (address_on_stack < tib->StackLimit ||
544 address_on_stack > tib->StackBase) {
545 g_surrogate_exception_record.ExceptionAddress = _ReturnAddress();
546 g_surrogate_exception_record.ExceptionCode = DBG_TERMINATE_PROCESS;
547 g_surrogate_exception_record.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
548 CrashForException(&g_surrogate_exception_pointers);
552 NtTerminateProcessPtr real_proc =
553 reinterpret_cast<NtTerminateProcessPtr>(
554 static_cast<char*>(g_real_terminate_process_stub));
555 return real_proc(ProcessHandle, ExitStatus);
558 static void InitTerminateProcessHooks() {
559 NtTerminateProcessPtr terminate_process_func_address =
560 reinterpret_cast<NtTerminateProcessPtr>(::GetProcAddress(
561 ::GetModuleHandle(L"ntdll.dll"), "NtTerminateProcess"));
562 if (terminate_process_func_address == NULL)
565 DWORD old_protect = 0;
566 if (!::VirtualProtect(terminate_process_func_address, 5,
567 PAGE_EXECUTE_READWRITE, &old_protect))
570 g_real_terminate_process_stub = reinterpret_cast<char*>(VirtualAllocEx(
571 ::GetCurrentProcess(), NULL, sidestep::kMaxPreambleStubSize,
572 MEM_COMMIT, PAGE_EXECUTE_READWRITE));
573 if (g_real_terminate_process_stub == NULL)
576 g_surrogate_exception_pointers.ContextRecord = &g_surrogate_context;
577 g_surrogate_exception_pointers.ExceptionRecord =
578 &g_surrogate_exception_record;
580 sidestep::SideStepError patch_result =
581 sidestep::PreamblePatcher::Patch(
582 terminate_process_func_address, HookNtTerminateProcess,
583 g_real_terminate_process_stub, sidestep::kMaxPreambleStubSize);
584 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
585 CHECK(::VirtualFreeEx(::GetCurrentProcess(), g_real_terminate_process_stub,
587 CHECK(::VirtualProtect(terminate_process_func_address, 5, old_protect,
593 CHECK(::VirtualProtect(terminate_process_func_address,
597 CHECK(::VirtualProtect(g_real_terminate_process_stub,
598 sidestep::kMaxPreambleStubSize,
603 static void InitPipeNameEnvVar(bool is_per_user_install) {
604 scoped_ptr<base::Environment> env(base::Environment::Create());
605 if (env->HasVar(kPipeNameVar)) {
606 // The Breakpad pipe name is already configured: nothing to do.
610 // Check whether configuration management controls crash reporting.
611 bool crash_reporting_enabled = true;
612 bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
613 &crash_reporting_enabled);
615 const CommandLine& command = *CommandLine::ForCurrentProcess();
616 bool use_crash_service =
617 !controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
618 GetBreakpadClient()->IsRunningUnattended());
620 std::wstring pipe_name;
621 if (use_crash_service) {
622 // Crash reporting is done by crash_service.exe.
623 pipe_name = kChromePipeName;
625 // We want to use the Google Update crash reporting. We need to check if the
626 // user allows it first (in case the administrator didn't already decide
628 if (!controlled_by_policy)
629 crash_reporting_enabled = GetBreakpadClient()->GetCollectStatsConsent();
631 if (!crash_reporting_enabled) {
632 if (!controlled_by_policy &&
633 GetBreakpadClient()->GetDeferredUploadsSupported(
634 is_per_user_install)) {
635 g_deferred_crash_uploads = true;
641 // Build the pipe name. It can be either:
642 // System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
643 // Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
644 std::wstring user_sid;
645 if (is_per_user_install) {
646 if (!base::win::GetUserSidString(&user_sid)) {
650 user_sid = kSystemPrincipalSid;
653 pipe_name = kGoogleUpdatePipeName;
654 pipe_name += user_sid;
656 env->SetVar(kPipeNameVar, base::UTF16ToASCII(pipe_name));
659 void InitDefaultCrashCallback(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
660 previous_filter = SetUnhandledExceptionFilter(filter);
663 void InitCrashReporter(const std::string& process_type_switch) {
664 const CommandLine& command = *CommandLine::ForCurrentProcess();
665 if (command.HasSwitch(switches::kDisableBreakpad))
668 // Disable the message box for assertions.
669 _CrtSetReportMode(_CRT_ASSERT, 0);
671 std::wstring process_type = base::ASCIIToWide(process_type_switch);
672 if (process_type.empty())
673 process_type = L"browser";
675 wchar_t exe_path[MAX_PATH];
677 GetModuleFileNameW(NULL, exe_path, MAX_PATH);
679 bool is_per_user_install =
680 GetBreakpadClient()->GetIsPerUserInstall(base::FilePath(exe_path));
682 google_breakpad::CustomClientInfo* custom_info =
683 GetCustomInfo(exe_path, process_type);
685 google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
686 LPTOP_LEVEL_EXCEPTION_FILTER default_filter = NULL;
687 // We install the post-dump callback only for the browser and service
688 // processes. It spawns a new browser/service process.
689 if (process_type == L"browser") {
690 callback = &DumpDoneCallback;
691 default_filter = &ChromeExceptionFilter;
692 } else if (process_type == L"service") {
693 callback = &DumpDoneCallback;
694 default_filter = &ServiceExceptionFilter;
697 if (process_type == L"browser") {
698 InitPipeNameEnvVar(is_per_user_install);
699 GetBreakpadClient()->InitBrowserCrashDumpsRegKey();
702 scoped_ptr<base::Environment> env(base::Environment::Create());
703 std::string pipe_name_ascii;
704 if (!env->GetVar(kPipeNameVar, &pipe_name_ascii)) {
705 // Breakpad is not enabled. Configuration is managed or the user
706 // did not allow Google Update to send crashes. We need to use
707 // our default crash handler instead, but only for the
708 // browser/service processes.
710 InitDefaultCrashCallback(default_filter);
713 std::wstring pipe_name = base::ASCIIToWide(pipe_name_ascii);
716 // The protocol for connecting to the out-of-process Breakpad crash
717 // reporter is different for x86-32 and x86-64: the message sizes
718 // are different because the message struct contains a pointer. As
719 // a result, there are two different named pipes to connect to. The
720 // 64-bit one is distinguished with an "-x64" suffix.
721 pipe_name += L"-x64";
724 // Get the alternate dump directory. We use the temp path.
725 wchar_t temp_dir[MAX_PATH] = {0};
726 ::GetTempPathW(MAX_PATH, temp_dir);
728 MINIDUMP_TYPE dump_type = kSmallDumpType;
729 // Capture full memory if explicitly instructed to.
730 if (command.HasSwitch(switches::kFullMemoryCrashReport))
731 dump_type = kFullDumpType;
732 else if (GetBreakpadClient()->GetShouldDumpLargerDumps(is_per_user_install))
733 dump_type = kLargerDumpType;
735 g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, &FilterCallback,
737 google_breakpad::ExceptionHandler::HANDLER_ALL,
738 dump_type, pipe_name.c_str(), custom_info);
740 // Now initialize the non crash dump handler.
741 g_dumphandler_no_crash = new google_breakpad::ExceptionHandler(temp_dir,
742 &FilterCallbackWhenNoCrash,
743 &DumpDoneCallbackWhenNoCrash,
745 // Set the handler to none so this handler would not be added to
746 // |handler_stack_| in |ExceptionHandler| which is a list of exception
748 google_breakpad::ExceptionHandler::HANDLER_NONE,
749 dump_type, pipe_name.c_str(), custom_info);
751 base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);
753 if (g_breakpad->IsOutOfProcess()) {
754 // Tells breakpad to handle breakpoint and single step exceptions.
755 // This might break JIT debuggers, but at least it will always
756 // generate a crashdump for these exceptions.
757 g_breakpad->set_handle_debug_exceptions(true);
760 if (process_type != L"browser" &&
761 !GetBreakpadClient()->IsRunningUnattended()) {
762 // Initialize the hook TerminateProcess to catch unexpected exits.
763 InitTerminateProcessHooks();
769 } // namespace breakpad