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/crash/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/numerics/safe_conversions.h"
25 #include "base/strings/string16.h"
26 #include "base/strings/string_split.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/stringprintf.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "base/synchronization/lock.h"
31 #include "base/win/metro.h"
32 #include "base/win/pe_image.h"
33 #include "base/win/registry.h"
34 #include "base/win/win_util.h"
35 #include "breakpad/src/client/windows/handler/exception_handler.h"
36 #include "components/crash/app/crash_keys_win.h"
37 #include "components/crash/app/crash_reporter_client.h"
38 #include "components/crash/app/hard_error_handler_win.h"
39 #include "content/public/common/result_codes.h"
40 #include "sandbox/win/src/nt_internals.h"
41 #include "sandbox/win/src/sidestep/preamble_patcher.h"
43 // userenv.dll is required for GetProfileType().
44 #pragma comment(lib, "userenv.lib")
46 #pragma intrinsic(_AddressOfReturnAddress)
47 #pragma intrinsic(_ReturnAddress)
50 // See http://msdn.microsoft.com/en-us/library/ddssxxy8.aspx
51 typedef struct _UNWIND_INFO
{
52 unsigned char Version
: 3;
53 unsigned char Flags
: 5;
54 unsigned char SizeOfProlog
;
55 unsigned char CountOfCodes
;
56 unsigned char FrameRegister
: 4;
57 unsigned char FrameOffset
: 4;
58 ULONG ExceptionHandler
;
59 } UNWIND_INFO
, *PUNWIND_INFO
;
64 using crash_reporter::GetCrashReporterClient
;
68 // Minidump with stacks, PEB, TEB, and unloaded module list.
69 const MINIDUMP_TYPE kSmallDumpType
= static_cast<MINIDUMP_TYPE
>(
70 MiniDumpWithProcessThreadData
| // Get PEB and TEB.
71 MiniDumpWithUnloadedModules
); // Get unloaded modules when available.
73 // Minidump with all of the above, plus memory referenced from stack.
74 const MINIDUMP_TYPE kLargerDumpType
= static_cast<MINIDUMP_TYPE
>(
75 MiniDumpWithProcessThreadData
| // Get PEB and TEB.
76 MiniDumpWithUnloadedModules
| // Get unloaded modules when available.
77 MiniDumpWithIndirectlyReferencedMemory
); // Get memory referenced by stack.
79 // Large dump with all process memory.
80 const MINIDUMP_TYPE kFullDumpType
= static_cast<MINIDUMP_TYPE
>(
81 MiniDumpWithFullMemory
| // Full memory from process.
82 MiniDumpWithProcessThreadData
| // Get PEB and TEB.
83 MiniDumpWithHandleData
| // Get all handle information.
84 MiniDumpWithUnloadedModules
); // Get unloaded modules when available.
86 const char kPipeNameVar
[] = "CHROME_BREAKPAD_PIPE_NAME";
88 const wchar_t kGoogleUpdatePipeName
[] = L
"\\\\.\\pipe\\GoogleCrashServices\\";
89 const wchar_t kChromePipeName
[] = L
"\\\\.\\pipe\\ChromeCrashServices";
91 // This is the well known SID for the system principal.
92 const wchar_t kSystemPrincipalSid
[] =L
"S-1-5-18";
94 google_breakpad::ExceptionHandler
* g_breakpad
= NULL
;
95 google_breakpad::ExceptionHandler
* g_dumphandler_no_crash
= NULL
;
97 EXCEPTION_POINTERS g_surrogate_exception_pointers
= {0};
98 EXCEPTION_RECORD g_surrogate_exception_record
= {0};
99 CONTEXT g_surrogate_context
= {0};
101 typedef NTSTATUS (WINAPI
* NtTerminateProcessPtr
)(HANDLE ProcessHandle
,
102 NTSTATUS ExitStatus
);
103 char* g_real_terminate_process_stub
= NULL
;
107 // Dumps the current process memory.
108 extern "C" void __declspec(dllexport
) __cdecl
DumpProcess() {
110 g_breakpad
->WriteMinidump();
114 // Used for dumping a process state when there is no crash.
115 extern "C" void __declspec(dllexport
) __cdecl
DumpProcessWithoutCrash() {
116 if (g_dumphandler_no_crash
) {
117 g_dumphandler_no_crash
->WriteMinidump();
123 // We need to prevent ICF from folding DumpForHangDebuggingThread() and
124 // DumpProcessWithoutCrashThread() together, since that makes them
125 // indistinguishable in crash dumps. We do this by making the function
126 // bodies unique, and prevent optimization from shuffling things around.
127 MSVC_DISABLE_OPTIMIZE()
128 MSVC_PUSH_DISABLE_WARNING(4748)
130 DWORD WINAPI
DumpProcessWithoutCrashThread(void*) {
131 DumpProcessWithoutCrash();
135 // The following two functions do exactly the same thing as the two above. But
136 // we want the signatures to be different so that we can easily track them in
138 // TODO(yzshen): Remove when enough information is collected and the hang rate
139 // of pepper/renderer processes is reduced.
140 DWORD WINAPI
DumpForHangDebuggingThread(void*) {
141 DumpProcessWithoutCrash();
142 VLOG(1) << "dumped for hang debugging";
147 MSVC_ENABLE_OPTIMIZE()
151 // Injects a thread into a remote process to dump state when there is no crash.
152 extern "C" HANDLE
__declspec(dllexport
) __cdecl
153 InjectDumpProcessWithoutCrash(HANDLE process
) {
154 return CreateRemoteThread(process
, NULL
, 0, DumpProcessWithoutCrashThread
,
158 extern "C" HANDLE
__declspec(dllexport
) __cdecl
159 InjectDumpForHangDebugging(HANDLE process
) {
160 return CreateRemoteThread(process
, NULL
, 0, DumpForHangDebuggingThread
,
164 // Returns a string containing a list of all modifiers for the loaded profile.
165 std::wstring
GetProfileType() {
166 std::wstring profile_type
;
167 DWORD profile_bits
= 0;
168 if (::GetProfileType(&profile_bits
)) {
169 static const struct {
173 { PT_MANDATORY
, L
"mandatory" },
174 { PT_ROAMING
, L
"roaming" },
175 { PT_TEMPORARY
, L
"temporary" },
177 for (size_t i
= 0; i
< arraysize(kBitNames
); ++i
) {
178 const DWORD this_bit
= kBitNames
[i
].bit
;
179 if ((profile_bits
& this_bit
) != 0) {
180 profile_type
.append(kBitNames
[i
].name
);
181 profile_bits
&= ~this_bit
;
182 if (profile_bits
!= 0)
183 profile_type
.append(L
", ");
187 DWORD last_error
= ::GetLastError();
188 base::SStringPrintf(&profile_type
, L
"error %u", last_error
);
195 // This callback is used when we want to get a dump without crashing the
197 bool DumpDoneCallbackWhenNoCrash(const wchar_t*, const wchar_t*, void*,
198 EXCEPTION_POINTERS
* ex_info
,
199 MDRawAssertionInfo
*, bool succeeded
) {
200 GetCrashReporterClient()->RecordCrashDumpAttemptResult(
201 false /* is_real_crash */, succeeded
);
205 // This callback is executed when the browser process has crashed, after
206 // the crash dump has been created. We need to minimize the amount of work
207 // done here since we have potentially corrupted process. Our job is to
208 // spawn another instance of chrome which will show a 'chrome has crashed'
209 // dialog. This code needs to live in the exe and thus has no access to
210 // facilities such as the i18n helpers.
211 bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
212 EXCEPTION_POINTERS
* ex_info
,
213 MDRawAssertionInfo
*, bool succeeded
) {
214 GetCrashReporterClient()->RecordCrashDumpAttemptResult(
215 true /* is_real_crash */, succeeded
);
216 // Check if the exception is one of the kind which would not be solved
217 // by simply restarting chrome. In this case we show a message box with
218 // and exit silently. Remember that chrome is in a crashed state so we
219 // can't show our own UI from this process.
220 if (HardErrorHandler(ex_info
))
223 if (!GetCrashReporterClient()->AboutToRestart())
226 // Now we just start chrome browser with the same command line.
227 STARTUPINFOW si
= {sizeof(si
)};
228 PROCESS_INFORMATION pi
;
229 if (::CreateProcessW(NULL
, ::GetCommandLineW(), NULL
, NULL
, FALSE
,
230 CREATE_UNICODE_ENVIRONMENT
, NULL
, NULL
, &si
, &pi
)) {
231 ::CloseHandle(pi
.hProcess
);
232 ::CloseHandle(pi
.hThread
);
234 // After this return we will be terminated. The actual return value is
239 // flag to indicate that we are already handling an exception.
240 volatile LONG handling_exception
= 0;
242 // This callback is used when there is no crash. Note: Unlike the
243 // |FilterCallback| below this does not do dupe detection. It is upto the caller
245 bool FilterCallbackWhenNoCrash(
246 void*, EXCEPTION_POINTERS
*, MDRawAssertionInfo
*) {
247 GetCrashReporterClient()->RecordCrashDumpAttempt(false);
251 // This callback is executed when the Chrome process has crashed and *before*
252 // the crash dump is created. To prevent duplicate crash reports we
253 // make every thread calling this method, except the very first one,
255 bool FilterCallback(void*, EXCEPTION_POINTERS
*, MDRawAssertionInfo
*) {
256 // Capture every thread except the first one in the sleep. We don't
257 // want multiple threads to concurrently report exceptions.
258 if (::InterlockedCompareExchange(&handling_exception
, 1, 0) == 1) {
261 GetCrashReporterClient()->RecordCrashDumpAttempt(true);
265 // Previous unhandled filter. Will be called if not null when we
266 // intercept a crash.
267 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter
= NULL
;
269 // Exception filter used when breakpad is not enabled. We just display
270 // the "Do you want to restart" message and then we call the previous filter.
271 long WINAPI
ChromeExceptionFilter(EXCEPTION_POINTERS
* info
) {
272 DumpDoneCallback(NULL
, NULL
, NULL
, info
, NULL
, false);
275 return previous_filter(info
);
277 return EXCEPTION_EXECUTE_HANDLER
;
280 // Exception filter for the service process used when breakpad is not enabled.
281 // We just display the "Do you want to restart" message and then die
282 // (without calling the previous filter).
283 long WINAPI
ServiceExceptionFilter(EXCEPTION_POINTERS
* info
) {
284 DumpDoneCallback(NULL
, NULL
, NULL
, info
, NULL
, false);
285 return EXCEPTION_EXECUTE_HANDLER
;
288 // Installed via base::debug::SetCrashKeyReportingFunctions.
289 void SetCrashKeyValueForBaseDebug(const base::StringPiece
& key
,
290 const base::StringPiece
& value
) {
291 DCHECK(CrashKeysWin::keeper());
292 CrashKeysWin::keeper()->SetCrashKeyValue(base::UTF8ToUTF16(key
),
293 base::UTF8ToUTF16(value
));
296 // Installed via base::debug::SetCrashKeyReportingFunctions.
297 void ClearCrashKeyForBaseDebug(const base::StringPiece
& key
) {
298 DCHECK(CrashKeysWin::keeper());
299 CrashKeysWin::keeper()->ClearCrashKeyValue(base::UTF8ToUTF16(key
));
304 // NOTE: This function is used by SyzyASAN to annotate crash reports. If you
305 // change the name or signature of this function you will break SyzyASAN
306 // instrumented releases of Chrome. Please contact syzygy-team@chromium.org
308 extern "C" void __declspec(dllexport
) __cdecl
SetCrashKeyValueImpl(
309 const wchar_t* key
, const wchar_t* value
) {
310 CrashKeysWin
* keeper
= CrashKeysWin::keeper();
314 // TODO(siggi): This doesn't look quite right - there's NULL deref potential
315 // here, and an implicit std::wstring conversion. Fixme.
316 keeper
->SetCrashKeyValue(key
, value
);
319 extern "C" void __declspec(dllexport
) __cdecl
ClearCrashKeyValueImpl(
320 const wchar_t* key
) {
321 CrashKeysWin
* keeper
= CrashKeysWin::keeper();
325 // TODO(siggi): This doesn't look quite right - there's NULL deref potential
326 // here, and an implicit std::wstring conversion. Fixme.
327 keeper
->ClearCrashKeyValue(key
);
330 static bool WrapMessageBoxWithSEH(const wchar_t* text
, const wchar_t* caption
,
331 UINT flags
, bool* exit_now
) {
332 // We wrap the call to MessageBoxW with a SEH handler because it some
333 // machines with CursorXP, PeaDict or with FontExplorer installed it crashes
334 // uncontrollably here. Being this a best effort deal we better go away.
336 *exit_now
= (IDOK
!= ::MessageBoxW(NULL
, text
, caption
, flags
));
337 } __except(EXCEPTION_EXECUTE_HANDLER
) {
338 // Its not safe to continue executing, exit silently here.
339 ::TerminateProcess(::GetCurrentProcess(),
340 GetCrashReporterClient()->GetResultCodeRespawnFailed());
346 // This function is executed by the child process that DumpDoneCallback()
347 // spawned and basically just shows the 'chrome has crashed' dialog if
348 // the CHROME_CRASHED environment variable is present.
349 bool ShowRestartDialogIfCrashed(bool* exit_now
) {
350 // If we are being launched in metro mode don't try to show the dialog.
351 if (base::win::IsMetroProcess())
354 base::string16 message
;
355 base::string16 title
;
357 if (!GetCrashReporterClient()->ShouldShowRestartDialog(
358 &title
, &message
, &is_rtl_locale
)) {
362 // If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
363 // flags so that an RTL message box is displayed.
364 UINT flags
= MB_OKCANCEL
| MB_ICONWARNING
;
366 flags
|= MB_RIGHT
| MB_RTLREADING
;
368 return WrapMessageBoxWithSEH(message
.c_str(), title
.c_str(), flags
, exit_now
);
371 // Crashes the process after generating a dump for the provided exception. Note
372 // that the crash reporter should be initialized before calling this function
373 // for it to do anything.
374 // NOTE: This function is used by SyzyASAN to invoke a crash. If you change the
375 // the name or signature of this function you will break SyzyASAN instrumented
376 // releases of Chrome. Please contact syzygy-team@chromium.org before doing so!
377 extern "C" int __declspec(dllexport
) CrashForException(
378 EXCEPTION_POINTERS
* info
) {
380 g_breakpad
->WriteMinidumpForException(info
);
381 // Patched stub exists based on conditions (See InitCrashReporter).
382 // As a side note this function also gets called from
383 // WindowProcExceptionFilter.
384 if (g_real_terminate_process_stub
== NULL
) {
385 ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED
);
387 NtTerminateProcessPtr real_terminate_proc
=
388 reinterpret_cast<NtTerminateProcessPtr
>(
389 static_cast<char*>(g_real_terminate_process_stub
));
390 real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED
);
393 return EXCEPTION_CONTINUE_SEARCH
;
397 static NTSTATUS WINAPI
HookNtTerminateProcess(HANDLE ProcessHandle
,
398 NTSTATUS ExitStatus
) {
400 (ProcessHandle
== ::GetCurrentProcess() || ProcessHandle
== NULL
)) {
401 NT_TIB
* tib
= reinterpret_cast<NT_TIB
*>(NtCurrentTeb());
402 void* address_on_stack
= _AddressOfReturnAddress();
403 if (address_on_stack
< tib
->StackLimit
||
404 address_on_stack
> tib
->StackBase
) {
405 g_surrogate_exception_record
.ExceptionAddress
= _ReturnAddress();
406 g_surrogate_exception_record
.ExceptionCode
= DBG_TERMINATE_PROCESS
;
407 g_surrogate_exception_record
.ExceptionFlags
= EXCEPTION_NONCONTINUABLE
;
408 CrashForException(&g_surrogate_exception_pointers
);
412 NtTerminateProcessPtr real_proc
=
413 reinterpret_cast<NtTerminateProcessPtr
>(
414 static_cast<char*>(g_real_terminate_process_stub
));
415 return real_proc(ProcessHandle
, ExitStatus
);
418 static void InitTerminateProcessHooks() {
419 NtTerminateProcessPtr terminate_process_func_address
=
420 reinterpret_cast<NtTerminateProcessPtr
>(::GetProcAddress(
421 ::GetModuleHandle(L
"ntdll.dll"), "NtTerminateProcess"));
422 if (terminate_process_func_address
== NULL
)
425 DWORD old_protect
= 0;
426 if (!::VirtualProtect(terminate_process_func_address
, 5,
427 PAGE_EXECUTE_READWRITE
, &old_protect
))
430 g_real_terminate_process_stub
= reinterpret_cast<char*>(VirtualAllocEx(
431 ::GetCurrentProcess(), NULL
, sidestep::kMaxPreambleStubSize
,
432 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
));
433 if (g_real_terminate_process_stub
== NULL
)
436 g_surrogate_exception_pointers
.ContextRecord
= &g_surrogate_context
;
437 g_surrogate_exception_pointers
.ExceptionRecord
=
438 &g_surrogate_exception_record
;
440 sidestep::SideStepError patch_result
=
441 sidestep::PreamblePatcher::Patch(
442 terminate_process_func_address
, HookNtTerminateProcess
,
443 g_real_terminate_process_stub
, sidestep::kMaxPreambleStubSize
);
444 if (patch_result
!= sidestep::SIDESTEP_SUCCESS
) {
445 CHECK(::VirtualFreeEx(::GetCurrentProcess(), g_real_terminate_process_stub
,
447 CHECK(::VirtualProtect(terminate_process_func_address
, 5, old_protect
,
453 CHECK(::VirtualProtect(terminate_process_func_address
,
457 CHECK(::VirtualProtect(g_real_terminate_process_stub
,
458 sidestep::kMaxPreambleStubSize
,
464 static void InitPipeNameEnvVar(bool is_per_user_install
) {
465 scoped_ptr
<base::Environment
> env(base::Environment::Create());
466 if (env
->HasVar(kPipeNameVar
)) {
467 // The Breakpad pipe name is already configured: nothing to do.
471 // Check whether configuration management controls crash reporting.
472 bool crash_reporting_enabled
= true;
473 bool controlled_by_policy
=
474 GetCrashReporterClient()->ReportingIsEnforcedByPolicy(
475 &crash_reporting_enabled
);
477 const base::CommandLine
& command
= *base::CommandLine::ForCurrentProcess();
478 bool use_crash_service
= !controlled_by_policy
&&
479 (command
.HasSwitch(switches::kNoErrorDialogs
) ||
480 GetCrashReporterClient()->IsRunningUnattended());
482 std::wstring pipe_name
;
483 if (use_crash_service
) {
484 // Crash reporting is done by crash_service.exe.
485 pipe_name
= kChromePipeName
;
487 // We want to use the Google Update crash reporting. We need to check if the
488 // user allows it first (in case the administrator didn't already decide
490 if (!controlled_by_policy
)
491 crash_reporting_enabled
=
492 GetCrashReporterClient()->GetCollectStatsConsent();
494 if (!crash_reporting_enabled
) {
495 // Crash reporting is disabled, don't set the environment variable.
499 // Build the pipe name. It can be either:
500 // System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
501 // Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
502 std::wstring user_sid
;
503 if (is_per_user_install
) {
504 if (!base::win::GetUserSidString(&user_sid
)) {
508 user_sid
= kSystemPrincipalSid
;
511 pipe_name
= kGoogleUpdatePipeName
;
512 pipe_name
+= user_sid
;
514 env
->SetVar(kPipeNameVar
, base::UTF16ToASCII(pipe_name
));
517 void InitDefaultCrashCallback(LPTOP_LEVEL_EXCEPTION_FILTER filter
) {
518 previous_filter
= SetUnhandledExceptionFilter(filter
);
521 void InitCrashReporter(const std::string
& process_type_switch
) {
522 const base::CommandLine
& command
= *base::CommandLine::ForCurrentProcess();
523 if (command
.HasSwitch(switches::kDisableBreakpad
))
526 // Disable the message box for assertions.
527 _CrtSetReportMode(_CRT_ASSERT
, 0);
529 base::string16 process_type
= base::ASCIIToUTF16(process_type_switch
);
530 if (process_type
.empty())
531 process_type
= L
"browser";
533 wchar_t exe_path
[MAX_PATH
];
535 GetModuleFileNameW(NULL
, exe_path
, MAX_PATH
);
537 bool is_per_user_install
=
538 GetCrashReporterClient()->GetIsPerUserInstall(base::FilePath(exe_path
));
540 // This is intentionally leaked.
541 CrashKeysWin
* keeper
= new CrashKeysWin();
543 google_breakpad::CustomClientInfo
* custom_info
=
544 keeper
->GetCustomInfo(exe_path
, process_type
, GetProfileType(),
545 base::CommandLine::ForCurrentProcess(),
546 GetCrashReporterClient());
548 #if !defined(COMPONENT_BUILD)
549 // chrome/common/child_process_logging_win.cc registers crash keys for
550 // chrome.dll. In a component build, that is sufficient as chrome.dll and
551 // chrome.exe share a copy of base (in base.dll).
552 // In a static build, the EXE must separately initialize the crash keys
553 // configuration as it has its own statically linked copy of base.
554 base::debug::SetCrashKeyReportingFunctions(&SetCrashKeyValueForBaseDebug
,
555 &ClearCrashKeyForBaseDebug
);
556 GetCrashReporterClient()->RegisterCrashKeys();
559 google_breakpad::ExceptionHandler::MinidumpCallback callback
= NULL
;
560 LPTOP_LEVEL_EXCEPTION_FILTER default_filter
= NULL
;
561 // We install the post-dump callback only for the browser and service
562 // processes. It spawns a new browser/service process.
563 if (process_type
== L
"browser") {
564 callback
= &DumpDoneCallback
;
565 default_filter
= &ChromeExceptionFilter
;
566 } else if (process_type
== L
"service") {
567 callback
= &DumpDoneCallback
;
568 default_filter
= &ServiceExceptionFilter
;
571 if (process_type
== L
"browser") {
572 InitPipeNameEnvVar(is_per_user_install
);
573 GetCrashReporterClient()->InitBrowserCrashDumpsRegKey();
576 scoped_ptr
<base::Environment
> env(base::Environment::Create());
577 std::string pipe_name_ascii
;
578 if (!env
->GetVar(kPipeNameVar
, &pipe_name_ascii
)) {
579 // Breakpad is not enabled. Configuration is managed or the user
580 // did not allow Google Update to send crashes. We need to use
581 // our default crash handler instead, but only for the
582 // browser/service processes.
584 InitDefaultCrashCallback(default_filter
);
587 base::string16 pipe_name
= base::ASCIIToUTF16(pipe_name_ascii
);
590 // The protocol for connecting to the out-of-process Breakpad crash
591 // reporter is different for x86-32 and x86-64: the message sizes
592 // are different because the message struct contains a pointer. As
593 // a result, there are two different named pipes to connect to. The
594 // 64-bit one is distinguished with an "-x64" suffix.
595 pipe_name
+= L
"-x64";
598 // Get the alternate dump directory. We use the temp path.
599 wchar_t temp_dir
[MAX_PATH
] = {0};
600 ::GetTempPathW(MAX_PATH
, temp_dir
);
602 MINIDUMP_TYPE dump_type
= kSmallDumpType
;
603 // Capture full memory if explicitly instructed to.
604 if (command
.HasSwitch(switches::kFullMemoryCrashReport
))
605 dump_type
= kFullDumpType
;
606 else if (GetCrashReporterClient()->GetShouldDumpLargerDumps(
607 is_per_user_install
))
608 dump_type
= kLargerDumpType
;
610 g_breakpad
= new google_breakpad::ExceptionHandler(temp_dir
, &FilterCallback
,
612 google_breakpad::ExceptionHandler::HANDLER_ALL
,
613 dump_type
, pipe_name
.c_str(), custom_info
);
615 // Now initialize the non crash dump handler.
616 g_dumphandler_no_crash
= new google_breakpad::ExceptionHandler(temp_dir
,
617 &FilterCallbackWhenNoCrash
,
618 &DumpDoneCallbackWhenNoCrash
,
620 // Set the handler to none so this handler would not be added to
621 // |handler_stack_| in |ExceptionHandler| which is a list of exception
623 google_breakpad::ExceptionHandler::HANDLER_NONE
,
624 dump_type
, pipe_name
.c_str(), custom_info
);
626 // Set the DumpWithoutCrashingFunction for this instance of base.lib. Other
627 // executable images linked with base should set this again for
628 // DumpWithoutCrashing to function correctly.
629 // See chrome_main.cc for example.
630 base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash
);
632 if (g_breakpad
->IsOutOfProcess()) {
633 // Tells breakpad to handle breakpoint and single step exceptions.
634 // This might break JIT debuggers, but at least it will always
635 // generate a crashdump for these exceptions.
636 g_breakpad
->set_handle_debug_exceptions(true);
639 if (process_type
!= L
"browser" &&
640 !GetCrashReporterClient()->IsRunningUnattended()) {
641 // Initialize the hook TerminateProcess to catch unexpected exits.
642 InitTerminateProcessHooks();
648 void ConsumeInvalidHandleExceptions() {
650 g_breakpad
->set_consume_invalid_handle_exceptions(true);
652 if (g_dumphandler_no_crash
) {
653 g_dumphandler_no_crash
->set_consume_invalid_handle_exceptions(true);
657 // If the user has disabled crash reporting uploads and restarted Chrome, the
658 // restarted instance will still contain the pipe environment variable, which
659 // will allow the restarted process to still upload crash reports. This function
660 // clears the environment variable, so that the restarted Chrome, which inherits
661 // its environment from the current Chrome, will no longer contain the variable.
662 extern "C" void __declspec(dllexport
) __cdecl
663 ClearBreakpadPipeEnvironmentVariable() {
664 scoped_ptr
<base::Environment
> env(base::Environment::Create());
665 env
->UnSetVar(kPipeNameVar
);
669 int CrashForExceptionInNonABICompliantCodeRange(
670 PEXCEPTION_RECORD ExceptionRecord
,
671 ULONG64 EstablisherFrame
,
672 PCONTEXT ContextRecord
,
673 PDISPATCHER_CONTEXT DispatcherContext
) {
674 EXCEPTION_POINTERS info
= { ExceptionRecord
, ContextRecord
};
675 return CrashForException(&info
);
678 struct ExceptionHandlerRecord
{
679 RUNTIME_FUNCTION runtime_function
;
680 UNWIND_INFO unwind_info
;
681 unsigned char thunk
[12];
684 extern "C" void __declspec(dllexport
) __cdecl
685 RegisterNonABICompliantCodeRange(void* start
, size_t size_in_bytes
) {
686 ExceptionHandlerRecord
* record
=
687 reinterpret_cast<ExceptionHandlerRecord
*>(start
);
689 // We assume that the first page of the code range is executable and
690 // committed and reserved for breakpad. What could possibly go wrong?
692 // All addresses are 32bit relative offsets to start.
693 record
->runtime_function
.BeginAddress
= 0;
694 record
->runtime_function
.EndAddress
=
695 base::checked_cast
<DWORD
>(size_in_bytes
);
696 record
->runtime_function
.UnwindData
=
697 offsetof(ExceptionHandlerRecord
, unwind_info
);
699 // Create unwind info that only specifies an exception handler.
700 record
->unwind_info
.Version
= 1;
701 record
->unwind_info
.Flags
= UNW_FLAG_EHANDLER
;
702 record
->unwind_info
.SizeOfProlog
= 0;
703 record
->unwind_info
.CountOfCodes
= 0;
704 record
->unwind_info
.FrameRegister
= 0;
705 record
->unwind_info
.FrameOffset
= 0;
706 record
->unwind_info
.ExceptionHandler
=
707 offsetof(ExceptionHandlerRecord
, thunk
);
711 record
->thunk
[0] = 0x48;
712 record
->thunk
[1] = 0xb8;
713 void* handler
= &CrashForExceptionInNonABICompliantCodeRange
;
714 memcpy(&record
->thunk
[2], &handler
, 8);
717 record
->thunk
[10] = 0xff;
718 record
->thunk
[11] = 0xe0;
720 // Protect reserved page against modifications.
722 CHECK(VirtualProtect(
723 start
, sizeof(ExceptionHandlerRecord
), PAGE_EXECUTE_READ
, &old_protect
));
724 CHECK(RtlAddFunctionTable(
725 &record
->runtime_function
, 1, reinterpret_cast<DWORD64
>(start
)));
728 extern "C" void __declspec(dllexport
) __cdecl
729 UnregisterNonABICompliantCodeRange(void* start
) {
730 ExceptionHandlerRecord
* record
=
731 reinterpret_cast<ExceptionHandlerRecord
*>(start
);
733 CHECK(RtlDeleteFunctionTable(&record
->runtime_function
));
737 } // namespace breakpad