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"
17 #include "base/base_switches.h"
18 #include "base/basictypes.h"
19 #include "base/command_line.h"
20 #include "base/debug/crash_logging.h"
21 #include "base/debug/dump_without_crashing.h"
22 #include "base/environment.h"
23 #include "base/memory/scoped_ptr.h"
24 #include "base/strings/string16.h"
25 #include "base/strings/string_split.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/synchronization/lock.h"
30 #include "base/win/metro.h"
31 #include "base/win/pe_image.h"
32 #include "base/win/registry.h"
33 #include "base/win/win_util.h"
34 #include "breakpad/src/client/windows/handler/exception_handler.h"
35 #include "components/breakpad/app/breakpad_client.h"
36 #include "components/breakpad/app/crash_keys_win.h"
37 #include "components/breakpad/app/hard_error_handler_win.h"
38 #include "content/public/common/result_codes.h"
39 #include "sandbox/win/src/nt_internals.h"
40 #include "sandbox/win/src/sidestep/preamble_patcher.h"
42 // userenv.dll is required for GetProfileType().
43 #pragma comment(lib, "userenv.lib")
45 #pragma intrinsic(_AddressOfReturnAddress)
46 #pragma intrinsic(_ReturnAddress)
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;
91 // Dumps the current process memory.
92 extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
94 g_breakpad->WriteMinidump();
98 // Used for dumping a process state when there is no crash.
99 extern "C" void __declspec(dllexport) __cdecl DumpProcessWithoutCrash() {
100 if (g_dumphandler_no_crash) {
101 g_dumphandler_no_crash->WriteMinidump();
107 // We need to prevent ICF from folding DumpForHangDebuggingThread() and
108 // DumpProcessWithoutCrashThread() together, since that makes them
109 // indistinguishable in crash dumps. We do this by making the function
110 // bodies unique, and prevent optimization from shuffling things around.
111 MSVC_DISABLE_OPTIMIZE()
112 MSVC_PUSH_DISABLE_WARNING(4748)
114 DWORD WINAPI DumpProcessWithoutCrashThread(void*) {
115 DumpProcessWithoutCrash();
119 // The following two functions do exactly the same thing as the two above. But
120 // we want the signatures to be different so that we can easily track them in
122 // TODO(yzshen): Remove when enough information is collected and the hang rate
123 // of pepper/renderer processes is reduced.
124 DWORD WINAPI DumpForHangDebuggingThread(void*) {
125 DumpProcessWithoutCrash();
126 VLOG(1) << "dumped for hang debugging";
131 MSVC_ENABLE_OPTIMIZE()
135 // Injects a thread into a remote process to dump state when there is no crash.
136 extern "C" HANDLE __declspec(dllexport) __cdecl
137 InjectDumpProcessWithoutCrash(HANDLE process) {
138 return CreateRemoteThread(process, NULL, 0, DumpProcessWithoutCrashThread,
142 extern "C" HANDLE __declspec(dllexport) __cdecl
143 InjectDumpForHangDebugging(HANDLE process) {
144 return CreateRemoteThread(process, NULL, 0, DumpForHangDebuggingThread,
148 // Returns a string containing a list of all modifiers for the loaded profile.
149 std::wstring GetProfileType() {
150 std::wstring profile_type;
151 DWORD profile_bits = 0;
152 if (::GetProfileType(&profile_bits)) {
153 static const struct {
157 { PT_MANDATORY, L"mandatory" },
158 { PT_ROAMING, L"roaming" },
159 { PT_TEMPORARY, L"temporary" },
161 for (size_t i = 0; i < arraysize(kBitNames); ++i) {
162 const DWORD this_bit = kBitNames[i].bit;
163 if ((profile_bits & this_bit) != 0) {
164 profile_type.append(kBitNames[i].name);
165 profile_bits &= ~this_bit;
166 if (profile_bits != 0)
167 profile_type.append(L", ");
171 DWORD last_error = ::GetLastError();
172 base::SStringPrintf(&profile_type, L"error %u", last_error);
179 // This callback is used when we want to get a dump without crashing the
181 bool DumpDoneCallbackWhenNoCrash(const wchar_t*, const wchar_t*, void*,
182 EXCEPTION_POINTERS* ex_info,
183 MDRawAssertionInfo*, bool) {
187 // This callback is executed when the browser process has crashed, after
188 // the crash dump has been created. We need to minimize the amount of work
189 // done here since we have potentially corrupted process. Our job is to
190 // spawn another instance of chrome which will show a 'chrome has crashed'
191 // dialog. This code needs to live in the exe and thus has no access to
192 // facilities such as the i18n helpers.
193 bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
194 EXCEPTION_POINTERS* ex_info,
195 MDRawAssertionInfo*, bool) {
196 // Check if the exception is one of the kind which would not be solved
197 // by simply restarting chrome. In this case we show a message box with
198 // and exit silently. Remember that chrome is in a crashed state so we
199 // can't show our own UI from this process.
200 if (HardErrorHandler(ex_info))
203 if (!GetBreakpadClient()->AboutToRestart())
206 // Now we just start chrome browser with the same command line.
207 STARTUPINFOW si = {sizeof(si)};
208 PROCESS_INFORMATION pi;
209 if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
210 CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
211 ::CloseHandle(pi.hProcess);
212 ::CloseHandle(pi.hThread);
214 // After this return we will be terminated. The actual return value is
219 // flag to indicate that we are already handling an exception.
220 volatile LONG handling_exception = 0;
222 // This callback is used when there is no crash. Note: Unlike the
223 // |FilterCallback| below this does not do dupe detection. It is upto the caller
225 bool FilterCallbackWhenNoCrash(
226 void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
227 GetBreakpadClient()->RecordCrashDumpAttempt(false);
231 // This callback is executed when the Chrome process has crashed and *before*
232 // the crash dump is created. To prevent duplicate crash reports we
233 // make every thread calling this method, except the very first one,
235 bool FilterCallback(void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
236 // Capture every thread except the first one in the sleep. We don't
237 // want multiple threads to concurrently report exceptions.
238 if (::InterlockedCompareExchange(&handling_exception, 1, 0) == 1) {
241 GetBreakpadClient()->RecordCrashDumpAttempt(true);
245 // Previous unhandled filter. Will be called if not null when we
246 // intercept a crash.
247 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
249 // Exception filter used when breakpad is not enabled. We just display
250 // the "Do you want to restart" message and then we call the previous filter.
251 long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
252 DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
255 return previous_filter(info);
257 return EXCEPTION_EXECUTE_HANDLER;
260 // Exception filter for the service process used when breakpad is not enabled.
261 // We just display the "Do you want to restart" message and then die
262 // (without calling the previous filter).
263 long WINAPI ServiceExceptionFilter(EXCEPTION_POINTERS* info) {
264 DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
265 return EXCEPTION_EXECUTE_HANDLER;
270 // NOTE: This function is used by SyzyASAN to annotate crash reports. If you
271 // change the name or signature of this function you will break SyzyASAN
272 // instrumented releases of Chrome. Please contact syzygy-team@chromium.org
274 extern "C" void __declspec(dllexport) __cdecl SetCrashKeyValueImpl(
275 const wchar_t* key, const wchar_t* value) {
276 CrashKeysWin* keeper = CrashKeysWin::keeper();
280 // TODO(siggi): This doesn't look quite right - there's NULL deref potential
281 // here, and an implicit std::wstring conversion. Fixme.
282 keeper->SetCrashKeyValue(key, value);
285 extern "C" void __declspec(dllexport) __cdecl ClearCrashKeyValueImpl(
286 const wchar_t* key) {
287 CrashKeysWin* keeper = CrashKeysWin::keeper();
291 // TODO(siggi): This doesn't look quite right - there's NULL deref potential
292 // here, and an implicit std::wstring conversion. Fixme.
293 keeper->ClearCrashKeyValue(key);
296 static bool WrapMessageBoxWithSEH(const wchar_t* text, const wchar_t* caption,
297 UINT flags, bool* exit_now) {
298 // We wrap the call to MessageBoxW with a SEH handler because it some
299 // machines with CursorXP, PeaDict or with FontExplorer installed it crashes
300 // uncontrollably here. Being this a best effort deal we better go away.
302 *exit_now = (IDOK != ::MessageBoxW(NULL, text, caption, flags));
303 } __except(EXCEPTION_EXECUTE_HANDLER) {
304 // Its not safe to continue executing, exit silently here.
305 ::TerminateProcess(::GetCurrentProcess(),
306 GetBreakpadClient()->GetResultCodeRespawnFailed());
312 // This function is executed by the child process that DumpDoneCallback()
313 // spawned and basically just shows the 'chrome has crashed' dialog if
314 // the CHROME_CRASHED environment variable is present.
315 bool ShowRestartDialogIfCrashed(bool* exit_now) {
316 // If we are being launched in metro mode don't try to show the dialog.
317 if (base::win::IsMetroProcess())
320 base::string16 message;
321 base::string16 title;
323 if (!GetBreakpadClient()->ShouldShowRestartDialog(
324 &title, &message, &is_rtl_locale)) {
328 // If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
329 // flags so that an RTL message box is displayed.
330 UINT flags = MB_OKCANCEL | MB_ICONWARNING;
332 flags |= MB_RIGHT | MB_RTLREADING;
334 return WrapMessageBoxWithSEH(message.c_str(), title.c_str(), flags, exit_now);
337 // Crashes the process after generating a dump for the provided exception. Note
338 // that the crash reporter should be initialized before calling this function
339 // for it to do anything.
340 // NOTE: This function is used by SyzyASAN to invoke a crash. If you change the
341 // the name or signature of this function you will break SyzyASAN instrumented
342 // releases of Chrome. Please contact syzygy-team@chromium.org before doing so!
343 extern "C" int __declspec(dllexport) CrashForException(
344 EXCEPTION_POINTERS* info) {
346 g_breakpad->WriteMinidumpForException(info);
347 // Patched stub exists based on conditions (See InitCrashReporter).
348 // As a side note this function also gets called from
349 // WindowProcExceptionFilter.
350 if (g_real_terminate_process_stub == NULL) {
351 ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
353 NtTerminateProcessPtr real_terminate_proc =
354 reinterpret_cast<NtTerminateProcessPtr>(
355 static_cast<char*>(g_real_terminate_process_stub));
356 real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
359 return EXCEPTION_CONTINUE_SEARCH;
362 static NTSTATUS WINAPI HookNtTerminateProcess(HANDLE ProcessHandle,
363 NTSTATUS ExitStatus) {
365 (ProcessHandle == ::GetCurrentProcess() || ProcessHandle == NULL)) {
366 NT_TIB* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
367 void* address_on_stack = _AddressOfReturnAddress();
368 if (address_on_stack < tib->StackLimit ||
369 address_on_stack > tib->StackBase) {
370 g_surrogate_exception_record.ExceptionAddress = _ReturnAddress();
371 g_surrogate_exception_record.ExceptionCode = DBG_TERMINATE_PROCESS;
372 g_surrogate_exception_record.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
373 CrashForException(&g_surrogate_exception_pointers);
377 NtTerminateProcessPtr real_proc =
378 reinterpret_cast<NtTerminateProcessPtr>(
379 static_cast<char*>(g_real_terminate_process_stub));
380 return real_proc(ProcessHandle, ExitStatus);
383 static void InitTerminateProcessHooks() {
384 NtTerminateProcessPtr terminate_process_func_address =
385 reinterpret_cast<NtTerminateProcessPtr>(::GetProcAddress(
386 ::GetModuleHandle(L"ntdll.dll"), "NtTerminateProcess"));
387 if (terminate_process_func_address == NULL)
390 DWORD old_protect = 0;
391 if (!::VirtualProtect(terminate_process_func_address, 5,
392 PAGE_EXECUTE_READWRITE, &old_protect))
395 g_real_terminate_process_stub = reinterpret_cast<char*>(VirtualAllocEx(
396 ::GetCurrentProcess(), NULL, sidestep::kMaxPreambleStubSize,
397 MEM_COMMIT, PAGE_EXECUTE_READWRITE));
398 if (g_real_terminate_process_stub == NULL)
401 g_surrogate_exception_pointers.ContextRecord = &g_surrogate_context;
402 g_surrogate_exception_pointers.ExceptionRecord =
403 &g_surrogate_exception_record;
405 sidestep::SideStepError patch_result =
406 sidestep::PreamblePatcher::Patch(
407 terminate_process_func_address, HookNtTerminateProcess,
408 g_real_terminate_process_stub, sidestep::kMaxPreambleStubSize);
409 if (patch_result != sidestep::SIDESTEP_SUCCESS) {
410 CHECK(::VirtualFreeEx(::GetCurrentProcess(), g_real_terminate_process_stub,
412 CHECK(::VirtualProtect(terminate_process_func_address, 5, old_protect,
418 CHECK(::VirtualProtect(terminate_process_func_address,
422 CHECK(::VirtualProtect(g_real_terminate_process_stub,
423 sidestep::kMaxPreambleStubSize,
428 static void InitPipeNameEnvVar(bool is_per_user_install) {
429 scoped_ptr<base::Environment> env(base::Environment::Create());
430 if (env->HasVar(kPipeNameVar)) {
431 // The Breakpad pipe name is already configured: nothing to do.
435 // Check whether configuration management controls crash reporting.
436 bool crash_reporting_enabled = true;
437 bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
438 &crash_reporting_enabled);
440 const CommandLine& command = *CommandLine::ForCurrentProcess();
441 bool use_crash_service =
442 !controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
443 GetBreakpadClient()->IsRunningUnattended());
445 std::wstring pipe_name;
446 if (use_crash_service) {
447 // Crash reporting is done by crash_service.exe.
448 pipe_name = kChromePipeName;
450 // We want to use the Google Update crash reporting. We need to check if the
451 // user allows it first (in case the administrator didn't already decide
453 if (!controlled_by_policy)
454 crash_reporting_enabled = GetBreakpadClient()->GetCollectStatsConsent();
456 if (!crash_reporting_enabled) {
457 // Crash reporting is disabled, don't set the environment variable.
461 // Build the pipe name. It can be either:
462 // System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
463 // Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
464 std::wstring user_sid;
465 if (is_per_user_install) {
466 if (!base::win::GetUserSidString(&user_sid)) {
470 user_sid = kSystemPrincipalSid;
473 pipe_name = kGoogleUpdatePipeName;
474 pipe_name += user_sid;
476 env->SetVar(kPipeNameVar, base::UTF16ToASCII(pipe_name));
479 void InitDefaultCrashCallback(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
480 previous_filter = SetUnhandledExceptionFilter(filter);
483 void InitCrashReporter(const std::string& process_type_switch) {
484 const CommandLine& command = *CommandLine::ForCurrentProcess();
485 if (command.HasSwitch(switches::kDisableBreakpad))
488 // Disable the message box for assertions.
489 _CrtSetReportMode(_CRT_ASSERT, 0);
491 std::wstring process_type = base::ASCIIToWide(process_type_switch);
492 if (process_type.empty())
493 process_type = L"browser";
495 wchar_t exe_path[MAX_PATH];
497 GetModuleFileNameW(NULL, exe_path, MAX_PATH);
499 bool is_per_user_install =
500 GetBreakpadClient()->GetIsPerUserInstall(base::FilePath(exe_path));
502 // This is intentionally leaked.
503 CrashKeysWin* keeper = new CrashKeysWin();
505 google_breakpad::CustomClientInfo* custom_info =
506 keeper->GetCustomInfo(exe_path, process_type,
507 GetProfileType(), CommandLine::ForCurrentProcess(),
508 GetBreakpadClient());
510 google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
511 LPTOP_LEVEL_EXCEPTION_FILTER default_filter = NULL;
512 // We install the post-dump callback only for the browser and service
513 // processes. It spawns a new browser/service process.
514 if (process_type == L"browser") {
515 callback = &DumpDoneCallback;
516 default_filter = &ChromeExceptionFilter;
517 } else if (process_type == L"service") {
518 callback = &DumpDoneCallback;
519 default_filter = &ServiceExceptionFilter;
522 if (process_type == L"browser") {
523 InitPipeNameEnvVar(is_per_user_install);
524 GetBreakpadClient()->InitBrowserCrashDumpsRegKey();
527 scoped_ptr<base::Environment> env(base::Environment::Create());
528 std::string pipe_name_ascii;
529 if (!env->GetVar(kPipeNameVar, &pipe_name_ascii)) {
530 // Breakpad is not enabled. Configuration is managed or the user
531 // did not allow Google Update to send crashes. We need to use
532 // our default crash handler instead, but only for the
533 // browser/service processes.
535 InitDefaultCrashCallback(default_filter);
538 std::wstring pipe_name = base::ASCIIToWide(pipe_name_ascii);
541 // The protocol for connecting to the out-of-process Breakpad crash
542 // reporter is different for x86-32 and x86-64: the message sizes
543 // are different because the message struct contains a pointer. As
544 // a result, there are two different named pipes to connect to. The
545 // 64-bit one is distinguished with an "-x64" suffix.
546 pipe_name += L"-x64";
549 // Get the alternate dump directory. We use the temp path.
550 wchar_t temp_dir[MAX_PATH] = {0};
551 ::GetTempPathW(MAX_PATH, temp_dir);
553 MINIDUMP_TYPE dump_type = kSmallDumpType;
554 // Capture full memory if explicitly instructed to.
555 if (command.HasSwitch(switches::kFullMemoryCrashReport))
556 dump_type = kFullDumpType;
557 else if (GetBreakpadClient()->GetShouldDumpLargerDumps(is_per_user_install))
558 dump_type = kLargerDumpType;
560 g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, &FilterCallback,
562 google_breakpad::ExceptionHandler::HANDLER_ALL,
563 dump_type, pipe_name.c_str(), custom_info);
565 // Now initialize the non crash dump handler.
566 g_dumphandler_no_crash = new google_breakpad::ExceptionHandler(temp_dir,
567 &FilterCallbackWhenNoCrash,
568 &DumpDoneCallbackWhenNoCrash,
570 // Set the handler to none so this handler would not be added to
571 // |handler_stack_| in |ExceptionHandler| which is a list of exception
573 google_breakpad::ExceptionHandler::HANDLER_NONE,
574 dump_type, pipe_name.c_str(), custom_info);
576 // Set the DumpWithoutCrashingFunction for this instance of base.lib. Other
577 // executable images linked with base should set this again for
578 // DumpWithoutCrashing to function correctly.
579 // See chrome_main.cc for example.
580 base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);
582 if (g_breakpad->IsOutOfProcess()) {
583 // Tells breakpad to handle breakpoint and single step exceptions.
584 // This might break JIT debuggers, but at least it will always
585 // generate a crashdump for these exceptions.
586 g_breakpad->set_handle_debug_exceptions(true);
589 if (process_type != L"browser" &&
590 !GetBreakpadClient()->IsRunningUnattended()) {
591 // Initialize the hook TerminateProcess to catch unexpected exits.
592 InitTerminateProcessHooks();
598 // If the user has disabled crash reporting uploads and restarted Chrome, the
599 // restarted instance will still contain the pipe environment variable, which
600 // will allow the restarted process to still upload crash reports. This function
601 // clears the environment variable, so that the restarted Chrome, which inherits
602 // its environment from the current Chrome, will no longer contain the variable.
603 extern "C" void __declspec(dllexport) __cdecl
604 ClearBreakpadPipeEnvironmentVariable() {
605 scoped_ptr<base::Environment> env(base::Environment::Create());
606 env->UnSetVar(kPipeNameVar);
609 } // namespace breakpad