This source file includes following definitions.
- __declspec
- __declspec
- MSVC_DISABLE_OPTIMIZE
- DumpForHangDebuggingThread
- MSVC_POP_WARNING
- __declspec
- DumpProcessAbnormalSignature
- TrimToBreakpadMax
- SetIntegerValue
- SetPluginPath
- SetBreakpadDumpPath
- GetProfileType
- GetCustomInfo
- DumpDoneCallbackWhenNoCrash
- DumpDoneCallback
- FilterCallbackWhenNoCrash
- FilterCallback
- ChromeExceptionFilter
- ServiceExceptionFilter
- __declspec
- __declspec
- WrapMessageBoxWithSEH
- ShowRestartDialogIfCrashed
- __declspec
- HookNtTerminateProcess
- InitTerminateProcessHooks
- InitPipeNameEnvVar
- InitDefaultCrashCallback
- InitCrashReporter
#include "components/breakpad/app/breakpad_win.h"
#include <windows.h>
#include <shellapi.h>
#include <tchar.h>
#include <userenv.h>
#include <winnt.h>
#include <algorithm>
#include <vector>
#include "base/base_switches.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/debug/crash_logging.h"
#include "base/debug/dump_without_crashing.h"
#include "base/environment.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string16.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/metro.h"
#include "base/win/pe_image.h"
#include "base/win/registry.h"
#include "base/win/win_util.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
#include "components/breakpad/app/breakpad_client.h"
#include "components/breakpad/app/hard_error_handler_win.h"
#include "content/public/common/result_codes.h"
#include "sandbox/win/src/nt_internals.h"
#include "sandbox/win/src/sidestep/preamble_patcher.h"
#pragma comment(lib, "userenv.lib")
#pragma intrinsic(_AddressOfReturnAddress)
#pragma intrinsic(_ReturnAddress)
namespace breakpad {
std::vector<google_breakpad::CustomInfoEntry>* g_custom_entries = NULL;
bool g_deferred_crash_uploads = false;
namespace {
const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(
MiniDumpWithProcessThreadData |
MiniDumpWithUnloadedModules);
const MINIDUMP_TYPE kLargerDumpType = static_cast<MINIDUMP_TYPE>(
MiniDumpWithProcessThreadData |
MiniDumpWithUnloadedModules |
MiniDumpWithIndirectlyReferencedMemory);
const MINIDUMP_TYPE kFullDumpType = static_cast<MINIDUMP_TYPE>(
MiniDumpWithFullMemory |
MiniDumpWithProcessThreadData |
MiniDumpWithHandleData |
MiniDumpWithUnloadedModules);
const char kPipeNameVar[] = "CHROME_BREAKPAD_PIPE_NAME";
const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
const wchar_t kSystemPrincipalSid[] =L"S-1-5-18";
google_breakpad::ExceptionHandler* g_breakpad = NULL;
google_breakpad::ExceptionHandler* g_dumphandler_no_crash = NULL;
EXCEPTION_POINTERS g_surrogate_exception_pointers = {0};
EXCEPTION_RECORD g_surrogate_exception_record = {0};
CONTEXT g_surrogate_context = {0};
typedef NTSTATUS (WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle,
NTSTATUS ExitStatus);
char* g_real_terminate_process_stub = NULL;
static size_t g_dynamic_keys_offset = 0;
typedef std::map<std::wstring, google_breakpad::CustomInfoEntry*>
DynamicEntriesMap;
DynamicEntriesMap* g_dynamic_entries = NULL;
const size_t kMaxDynamicEntries = 256;
const size_t kMaxPluginPathLength = 256;
extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
if (g_breakpad) {
g_breakpad->WriteMinidump();
}
}
extern "C" void __declspec(dllexport) __cdecl DumpProcessWithoutCrash() {
if (g_dumphandler_no_crash) {
g_dumphandler_no_crash->WriteMinidump();
}
}
MSVC_DISABLE_OPTIMIZE()
MSVC_PUSH_DISABLE_WARNING(4748)
DWORD WINAPI DumpProcessWithoutCrashThread(void*) {
DumpProcessWithoutCrash();
return 0;
}
DWORD WINAPI DumpForHangDebuggingThread(void*) {
DumpProcessWithoutCrash();
VLOG(1) << "dumped for hang debugging";
return 0;
}
MSVC_POP_WARNING()
MSVC_ENABLE_OPTIMIZE()
extern "C" HANDLE __declspec(dllexport) __cdecl
InjectDumpProcessWithoutCrash(HANDLE process) {
return CreateRemoteThread(process, NULL, 0, DumpProcessWithoutCrashThread,
0, 0, NULL);
}
extern "C" HANDLE __declspec(dllexport) __cdecl
InjectDumpForHangDebugging(HANDLE process) {
return CreateRemoteThread(process, NULL, 0, DumpForHangDebuggingThread,
0, 0, NULL);
}
extern "C" void DumpProcessAbnormalSignature() {
if (!g_breakpad)
return;
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"unusual-crash-signature", L""));
g_breakpad->WriteMinidump();
}
std::wstring TrimToBreakpadMax(const std::wstring& str) {
std::wstring shorter(str);
return shorter.substr(0,
google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
}
static void SetIntegerValue(size_t offset, int value) {
if (!g_custom_entries)
return;
base::wcslcpy((*g_custom_entries)[offset].value,
base::StringPrintf(L"%d", value).c_str(),
google_breakpad::CustomInfoEntry::kValueMaxLength);
}
void SetPluginPath(const std::wstring& path) {
DCHECK(g_custom_entries);
if (path.size() > kMaxPluginPathLength) {
SetPluginPath(path.substr(path.size() - kMaxPluginPathLength));
return;
}
const size_t kChunkSize = static_cast<size_t>(
google_breakpad::CustomInfoEntry::kValueMaxLength - 1);
int chunk_index = 0;
size_t chunk_start = 0;
for (chunk_start = 0; chunk_start < path.size(); chunk_index++) {
size_t chunk_length = std::min(kChunkSize, path.size() - chunk_start);
g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
base::StringPrintf(L"plugin-path-chunk-%i", chunk_index + 1).c_str(),
path.substr(chunk_start, chunk_length).c_str()));
chunk_start += chunk_length;
}
}
void SetBreakpadDumpPath() {
DCHECK(g_custom_entries);
base::FilePath crash_dumps_dir_path;
if (GetBreakpadClient()->GetAlternativeCrashDumpLocation(
&crash_dumps_dir_path)) {
g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
L"breakpad-dump-location", crash_dumps_dir_path.value().c_str()));
}
}
std::wstring GetProfileType() {
std::wstring profile_type;
DWORD profile_bits = 0;
if (::GetProfileType(&profile_bits)) {
static const struct {
DWORD bit;
const wchar_t* name;
} kBitNames[] = {
{ PT_MANDATORY, L"mandatory" },
{ PT_ROAMING, L"roaming" },
{ PT_TEMPORARY, L"temporary" },
};
for (size_t i = 0; i < arraysize(kBitNames); ++i) {
const DWORD this_bit = kBitNames[i].bit;
if ((profile_bits & this_bit) != 0) {
profile_type.append(kBitNames[i].name);
profile_bits &= ~this_bit;
if (profile_bits != 0)
profile_type.append(L", ");
}
}
} else {
DWORD last_error = ::GetLastError();
base::SStringPrintf(&profile_type, L"error %u", last_error);
}
return profile_type;
}
google_breakpad::CustomClientInfo* GetCustomInfo(const std::wstring& exe_path,
const std::wstring& type) {
base::string16 version, product;
base::string16 special_build;
base::string16 channel_name;
GetBreakpadClient()->GetProductNameAndVersion(
base::FilePath(exe_path),
&product,
&version,
&special_build,
&channel_name);
DCHECK(!g_custom_entries);
g_custom_entries = new std::vector<google_breakpad::CustomInfoEntry>;
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"ver",
base::UTF16ToWide(version).c_str()));
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"prod",
base::UTF16ToWide(product).c_str()));
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"plat", L"Win32"));
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"ptype", type.c_str()));
g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
L"pid", base::StringPrintf(L"%d", ::GetCurrentProcessId()).c_str()));
g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
L"channel", base::UTF16ToWide(channel_name).c_str()));
g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
L"profile-type", GetProfileType().c_str()));
if (g_deferred_crash_uploads)
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"deferred-upload", L"true"));
if (!special_build.empty())
g_custom_entries->push_back(google_breakpad::CustomInfoEntry(
L"special", base::UTF16ToWide(special_build).c_str()));
if (type == L"plugin" || type == L"ppapi") {
std::wstring plugin_path =
CommandLine::ForCurrentProcess()->GetSwitchValueNative("plugin-path");
if (!plugin_path.empty())
SetPluginPath(plugin_path);
}
bool crash_reporting_enabled = true;
bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
&crash_reporting_enabled);
const CommandLine& command = *CommandLine::ForCurrentProcess();
bool use_crash_service =
!controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
GetBreakpadClient()->IsRunningUnattended());
if (use_crash_service)
SetBreakpadDumpPath();
g_dynamic_keys_offset = g_custom_entries->size();
for (size_t i = 0; i < kMaxDynamicEntries; ++i) {
g_custom_entries->push_back(
google_breakpad::CustomInfoEntry(L"unspecified-crash-key", L""));
}
g_dynamic_entries = new DynamicEntriesMap;
static google_breakpad::CustomClientInfo custom_client_info;
custom_client_info.entries = &g_custom_entries->front();
custom_client_info.count = g_custom_entries->size();
return &custom_client_info;
}
bool DumpDoneCallbackWhenNoCrash(const wchar_t*, const wchar_t*, void*,
EXCEPTION_POINTERS* ex_info,
MDRawAssertionInfo*, bool) {
return true;
}
bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
EXCEPTION_POINTERS* ex_info,
MDRawAssertionInfo*, bool) {
if (HardErrorHandler(ex_info))
return true;
if (!GetBreakpadClient()->AboutToRestart())
return true;
STARTUPINFOW si = {sizeof(si)};
PROCESS_INFORMATION pi;
if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
}
return true;
}
volatile LONG handling_exception = 0;
bool FilterCallbackWhenNoCrash(
void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
GetBreakpadClient()->RecordCrashDumpAttempt(false);
return true;
}
bool FilterCallback(void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
if (::InterlockedCompareExchange(&handling_exception, 1, 0) == 1) {
::Sleep(INFINITE);
}
GetBreakpadClient()->RecordCrashDumpAttempt(true);
return true;
}
LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
if (previous_filter)
return previous_filter(info);
return EXCEPTION_EXECUTE_HANDLER;
}
long WINAPI ServiceExceptionFilter(EXCEPTION_POINTERS* info) {
DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
return EXCEPTION_EXECUTE_HANDLER;
}
extern "C" void __declspec(dllexport) __cdecl SetCrashKeyValueImpl(
const wchar_t* key, const wchar_t* value) {
if (!g_dynamic_entries)
return;
std::wstring safe_key(std::wstring(key).substr(
0, google_breakpad::CustomInfoEntry::kNameMaxLength - 1));
std::wstring safe_value(std::wstring(value).substr(
0, google_breakpad::CustomInfoEntry::kValueMaxLength - 1));
DynamicEntriesMap::iterator it = g_dynamic_entries->find(safe_key);
google_breakpad::CustomInfoEntry* entry = NULL;
if (it == g_dynamic_entries->end()) {
if (g_dynamic_entries->size() >= kMaxDynamicEntries)
return;
entry = &(*g_custom_entries)[g_dynamic_keys_offset++];
g_dynamic_entries->insert(std::make_pair(safe_key, entry));
} else {
entry = it->second;
}
entry->set(safe_key.data(), safe_value.data());
}
extern "C" void __declspec(dllexport) __cdecl ClearCrashKeyValueImpl(
const wchar_t* key) {
if (!g_dynamic_entries)
return;
std::wstring key_string(key);
DynamicEntriesMap::iterator it = g_dynamic_entries->find(key_string);
if (it == g_dynamic_entries->end())
return;
it->second->set_value(NULL);
}
}
bool WrapMessageBoxWithSEH(const wchar_t* text, const wchar_t* caption,
UINT flags, bool* exit_now) {
__try {
*exit_now = (IDOK != ::MessageBoxW(NULL, text, caption, flags));
} __except(EXCEPTION_EXECUTE_HANDLER) {
::TerminateProcess(::GetCurrentProcess(),
GetBreakpadClient()->GetResultCodeRespawnFailed());
}
return true;
}
bool ShowRestartDialogIfCrashed(bool* exit_now) {
if (base::win::IsMetroProcess())
return false;
base::string16 message;
base::string16 title;
bool is_rtl_locale;
if (!GetBreakpadClient()->ShouldShowRestartDialog(
&title, &message, &is_rtl_locale)) {
return false;
}
UINT flags = MB_OKCANCEL | MB_ICONWARNING;
if (is_rtl_locale)
flags |= MB_RIGHT | MB_RTLREADING;
return WrapMessageBoxWithSEH(base::UTF16ToWide(message).c_str(),
base::UTF16ToWide(title).c_str(),
flags,
exit_now);
}
extern "C" int __declspec(dllexport) CrashForException(
EXCEPTION_POINTERS* info) {
if (g_breakpad) {
g_breakpad->WriteMinidumpForException(info);
if (g_real_terminate_process_stub == NULL) {
::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
} else {
NtTerminateProcessPtr real_terminate_proc =
reinterpret_cast<NtTerminateProcessPtr>(
static_cast<char*>(g_real_terminate_process_stub));
real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
}
}
return EXCEPTION_CONTINUE_SEARCH;
}
NTSTATUS WINAPI HookNtTerminateProcess(HANDLE ProcessHandle,
NTSTATUS ExitStatus) {
if (g_breakpad &&
(ProcessHandle == ::GetCurrentProcess() || ProcessHandle == NULL)) {
NT_TIB* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
void* address_on_stack = _AddressOfReturnAddress();
if (address_on_stack < tib->StackLimit ||
address_on_stack > tib->StackBase) {
g_surrogate_exception_record.ExceptionAddress = _ReturnAddress();
g_surrogate_exception_record.ExceptionCode = DBG_TERMINATE_PROCESS;
g_surrogate_exception_record.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
CrashForException(&g_surrogate_exception_pointers);
}
}
NtTerminateProcessPtr real_proc =
reinterpret_cast<NtTerminateProcessPtr>(
static_cast<char*>(g_real_terminate_process_stub));
return real_proc(ProcessHandle, ExitStatus);
}
static void InitTerminateProcessHooks() {
NtTerminateProcessPtr terminate_process_func_address =
reinterpret_cast<NtTerminateProcessPtr>(::GetProcAddress(
::GetModuleHandle(L"ntdll.dll"), "NtTerminateProcess"));
if (terminate_process_func_address == NULL)
return;
DWORD old_protect = 0;
if (!::VirtualProtect(terminate_process_func_address, 5,
PAGE_EXECUTE_READWRITE, &old_protect))
return;
g_real_terminate_process_stub = reinterpret_cast<char*>(VirtualAllocEx(
::GetCurrentProcess(), NULL, sidestep::kMaxPreambleStubSize,
MEM_COMMIT, PAGE_EXECUTE_READWRITE));
if (g_real_terminate_process_stub == NULL)
return;
g_surrogate_exception_pointers.ContextRecord = &g_surrogate_context;
g_surrogate_exception_pointers.ExceptionRecord =
&g_surrogate_exception_record;
sidestep::SideStepError patch_result =
sidestep::PreamblePatcher::Patch(
terminate_process_func_address, HookNtTerminateProcess,
g_real_terminate_process_stub, sidestep::kMaxPreambleStubSize);
if (patch_result != sidestep::SIDESTEP_SUCCESS) {
CHECK(::VirtualFreeEx(::GetCurrentProcess(), g_real_terminate_process_stub,
0, MEM_RELEASE));
CHECK(::VirtualProtect(terminate_process_func_address, 5, old_protect,
&old_protect));
return;
}
DWORD dummy = 0;
CHECK(::VirtualProtect(terminate_process_func_address,
5,
old_protect,
&dummy));
CHECK(::VirtualProtect(g_real_terminate_process_stub,
sidestep::kMaxPreambleStubSize,
old_protect,
&old_protect));
}
static void InitPipeNameEnvVar(bool is_per_user_install) {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar(kPipeNameVar)) {
return;
}
bool crash_reporting_enabled = true;
bool controlled_by_policy = GetBreakpadClient()->ReportingIsEnforcedByPolicy(
&crash_reporting_enabled);
const CommandLine& command = *CommandLine::ForCurrentProcess();
bool use_crash_service =
!controlled_by_policy && (command.HasSwitch(switches::kNoErrorDialogs) ||
GetBreakpadClient()->IsRunningUnattended());
std::wstring pipe_name;
if (use_crash_service) {
pipe_name = kChromePipeName;
} else {
if (!controlled_by_policy)
crash_reporting_enabled = GetBreakpadClient()->GetCollectStatsConsent();
if (!crash_reporting_enabled) {
if (!controlled_by_policy &&
GetBreakpadClient()->GetDeferredUploadsSupported(
is_per_user_install)) {
g_deferred_crash_uploads = true;
} else {
return;
}
}
std::wstring user_sid;
if (is_per_user_install) {
if (!base::win::GetUserSidString(&user_sid)) {
return;
}
} else {
user_sid = kSystemPrincipalSid;
}
pipe_name = kGoogleUpdatePipeName;
pipe_name += user_sid;
}
env->SetVar(kPipeNameVar, base::UTF16ToASCII(pipe_name));
}
void InitDefaultCrashCallback(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
previous_filter = SetUnhandledExceptionFilter(filter);
}
void InitCrashReporter(const std::string& process_type_switch) {
const CommandLine& command = *CommandLine::ForCurrentProcess();
if (command.HasSwitch(switches::kDisableBreakpad))
return;
_CrtSetReportMode(_CRT_ASSERT, 0);
std::wstring process_type = base::ASCIIToWide(process_type_switch);
if (process_type.empty())
process_type = L"browser";
wchar_t exe_path[MAX_PATH];
exe_path[0] = 0;
GetModuleFileNameW(NULL, exe_path, MAX_PATH);
bool is_per_user_install =
GetBreakpadClient()->GetIsPerUserInstall(base::FilePath(exe_path));
google_breakpad::CustomClientInfo* custom_info =
GetCustomInfo(exe_path, process_type);
google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
LPTOP_LEVEL_EXCEPTION_FILTER default_filter = NULL;
if (process_type == L"browser") {
callback = &DumpDoneCallback;
default_filter = &ChromeExceptionFilter;
} else if (process_type == L"service") {
callback = &DumpDoneCallback;
default_filter = &ServiceExceptionFilter;
}
if (process_type == L"browser") {
InitPipeNameEnvVar(is_per_user_install);
GetBreakpadClient()->InitBrowserCrashDumpsRegKey();
}
scoped_ptr<base::Environment> env(base::Environment::Create());
std::string pipe_name_ascii;
if (!env->GetVar(kPipeNameVar, &pipe_name_ascii)) {
if (default_filter)
InitDefaultCrashCallback(default_filter);
return;
}
std::wstring pipe_name = base::ASCIIToWide(pipe_name_ascii);
#ifdef _WIN64
pipe_name += L"-x64";
#endif
wchar_t temp_dir[MAX_PATH] = {0};
::GetTempPathW(MAX_PATH, temp_dir);
MINIDUMP_TYPE dump_type = kSmallDumpType;
if (command.HasSwitch(switches::kFullMemoryCrashReport))
dump_type = kFullDumpType;
else if (GetBreakpadClient()->GetShouldDumpLargerDumps(is_per_user_install))
dump_type = kLargerDumpType;
g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, &FilterCallback,
callback, NULL,
google_breakpad::ExceptionHandler::HANDLER_ALL,
dump_type, pipe_name.c_str(), custom_info);
g_dumphandler_no_crash = new google_breakpad::ExceptionHandler(temp_dir,
&FilterCallbackWhenNoCrash,
&DumpDoneCallbackWhenNoCrash,
NULL,
google_breakpad::ExceptionHandler::HANDLER_NONE,
dump_type, pipe_name.c_str(), custom_info);
base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);
if (g_breakpad->IsOutOfProcess()) {
g_breakpad->set_handle_debug_exceptions(true);
#ifndef _WIN64
if (process_type != L"browser" &&
!GetBreakpadClient()->IsRunningUnattended()) {
InitTerminateProcessHooks();
}
#endif
}
}
}