Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / components / crash / app / breakpad_win.cc
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.
4
5 #include "components/crash/app/breakpad_win.h"
6
7 #include <windows.h>
8 #include <shellapi.h>
9 #include <tchar.h>
10 #include <userenv.h>
11 #include <winnt.h>
12
13 #include <algorithm>
14 #include <map>
15 #include <vector>
16
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"
42
43 // userenv.dll is required for GetProfileType().
44 #pragma comment(lib, "userenv.lib")
45
46 #pragma intrinsic(_AddressOfReturnAddress)
47 #pragma intrinsic(_ReturnAddress)
48
49 #ifdef _WIN64
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;
60 #endif
61
62 namespace breakpad {
63
64 using crash_reporter::GetCrashReporterClient;
65
66 namespace {
67
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.
72
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.
78
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.
85
86 const char kPipeNameVar[] = "CHROME_BREAKPAD_PIPE_NAME";
87
88 const wchar_t kGoogleUpdatePipeName[] = L"\\\\.\\pipe\\GoogleCrashServices\\";
89 const wchar_t kChromePipeName[] = L"\\\\.\\pipe\\ChromeCrashServices";
90
91 // This is the well known SID for the system principal.
92 const wchar_t kSystemPrincipalSid[] =L"S-1-5-18";
93
94 google_breakpad::ExceptionHandler* g_breakpad = NULL;
95 google_breakpad::ExceptionHandler* g_dumphandler_no_crash = NULL;
96
97 EXCEPTION_POINTERS g_surrogate_exception_pointers = {0};
98 EXCEPTION_RECORD g_surrogate_exception_record = {0};
99 CONTEXT g_surrogate_context = {0};
100
101 typedef NTSTATUS (WINAPI* NtTerminateProcessPtr)(HANDLE ProcessHandle,
102                                                  NTSTATUS ExitStatus);
103 char* g_real_terminate_process_stub = NULL;
104
105 }  // namespace
106
107 // Dumps the current process memory.
108 extern "C" void __declspec(dllexport) __cdecl DumpProcess() {
109   if (g_breakpad) {
110     g_breakpad->WriteMinidump();
111   }
112 }
113
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();
118   }
119 }
120
121 namespace {
122
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)
129
130 DWORD WINAPI DumpProcessWithoutCrashThread(void*) {
131   DumpProcessWithoutCrash();
132   return 0;
133 }
134
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
137 // crash reports.
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";
143   return 0;
144 }
145
146 MSVC_POP_WARNING()
147 MSVC_ENABLE_OPTIMIZE()
148
149 }  // namespace
150
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,
155                             0, 0, NULL);
156 }
157
158 extern "C" HANDLE __declspec(dllexport) __cdecl
159 InjectDumpForHangDebugging(HANDLE process) {
160   return CreateRemoteThread(process, NULL, 0, DumpForHangDebuggingThread,
161                             0, 0, NULL);
162 }
163
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 {
170       DWORD bit;
171       const wchar_t* name;
172     } kBitNames[] = {
173       { PT_MANDATORY, L"mandatory" },
174       { PT_ROAMING, L"roaming" },
175       { PT_TEMPORARY, L"temporary" },
176     };
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", ");
184       }
185     }
186   } else {
187     DWORD last_error = ::GetLastError();
188     base::SStringPrintf(&profile_type, L"error %u", last_error);
189   }
190   return profile_type;
191 }
192
193 namespace {
194
195 // This callback is used when we want to get a dump without crashing the
196 // process.
197 bool DumpDoneCallbackWhenNoCrash(const wchar_t*, const wchar_t*, void*,
198                                  EXCEPTION_POINTERS* ex_info,
199                                  MDRawAssertionInfo*, bool) {
200   return true;
201 }
202
203 // This callback is executed when the browser process has crashed, after
204 // the crash dump has been created. We need to minimize the amount of work
205 // done here since we have potentially corrupted process. Our job is to
206 // spawn another instance of chrome which will show a 'chrome has crashed'
207 // dialog. This code needs to live in the exe and thus has no access to
208 // facilities such as the i18n helpers.
209 bool DumpDoneCallback(const wchar_t*, const wchar_t*, void*,
210                       EXCEPTION_POINTERS* ex_info,
211                       MDRawAssertionInfo*, bool) {
212   // Check if the exception is one of the kind which would not be solved
213   // by simply restarting chrome. In this case we show a message box with
214   // and exit silently. Remember that chrome is in a crashed state so we
215   // can't show our own UI from this process.
216   if (HardErrorHandler(ex_info))
217     return true;
218
219   if (!GetCrashReporterClient()->AboutToRestart())
220     return true;
221
222   // Now we just start chrome browser with the same command line.
223   STARTUPINFOW si = {sizeof(si)};
224   PROCESS_INFORMATION pi;
225   if (::CreateProcessW(NULL, ::GetCommandLineW(), NULL, NULL, FALSE,
226                        CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi)) {
227     ::CloseHandle(pi.hProcess);
228     ::CloseHandle(pi.hThread);
229   }
230   // After this return we will be terminated. The actual return value is
231   // not used at all.
232   return true;
233 }
234
235 // flag to indicate that we are already handling an exception.
236 volatile LONG handling_exception = 0;
237
238 // This callback is used when there is no crash. Note: Unlike the
239 // |FilterCallback| below this does not do dupe detection. It is upto the caller
240 // to implement it.
241 bool FilterCallbackWhenNoCrash(
242     void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
243   GetCrashReporterClient()->RecordCrashDumpAttempt(false);
244   return true;
245 }
246
247 // This callback is executed when the Chrome process has crashed and *before*
248 // the crash dump is created. To prevent duplicate crash reports we
249 // make every thread calling this method, except the very first one,
250 // go to sleep.
251 bool FilterCallback(void*, EXCEPTION_POINTERS*, MDRawAssertionInfo*) {
252   // Capture every thread except the first one in the sleep. We don't
253   // want multiple threads to concurrently report exceptions.
254   if (::InterlockedCompareExchange(&handling_exception, 1, 0) == 1) {
255     ::Sleep(INFINITE);
256   }
257   GetCrashReporterClient()->RecordCrashDumpAttempt(true);
258   return true;
259 }
260
261 // Previous unhandled filter. Will be called if not null when we
262 // intercept a crash.
263 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter = NULL;
264
265 // Exception filter used when breakpad is not enabled. We just display
266 // the "Do you want to restart" message and then we call the previous filter.
267 long WINAPI ChromeExceptionFilter(EXCEPTION_POINTERS* info) {
268   DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
269
270   if (previous_filter)
271     return previous_filter(info);
272
273   return EXCEPTION_EXECUTE_HANDLER;
274 }
275
276 // Exception filter for the service process used when breakpad is not enabled.
277 // We just display the "Do you want to restart" message and then die
278 // (without calling the previous filter).
279 long WINAPI ServiceExceptionFilter(EXCEPTION_POINTERS* info) {
280   DumpDoneCallback(NULL, NULL, NULL, info, NULL, false);
281   return EXCEPTION_EXECUTE_HANDLER;
282 }
283
284 }  // namespace
285
286 // NOTE: This function is used by SyzyASAN to annotate crash reports. If you
287 // change the name or signature of this function you will break SyzyASAN
288 // instrumented releases of Chrome. Please contact syzygy-team@chromium.org
289 // before doing so!
290 extern "C" void __declspec(dllexport) __cdecl SetCrashKeyValueImpl(
291     const wchar_t* key, const wchar_t* value) {
292   CrashKeysWin* keeper = CrashKeysWin::keeper();
293   if (!keeper)
294     return;
295
296   // TODO(siggi): This doesn't look quite right - there's NULL deref potential
297   //    here, and an implicit std::wstring conversion. Fixme.
298   keeper->SetCrashKeyValue(key, value);
299 }
300
301 extern "C" void __declspec(dllexport) __cdecl ClearCrashKeyValueImpl(
302     const wchar_t* key) {
303   CrashKeysWin* keeper = CrashKeysWin::keeper();
304   if (!keeper)
305     return;
306
307   // TODO(siggi): This doesn't look quite right - there's NULL deref potential
308   //    here, and an implicit std::wstring conversion. Fixme.
309   keeper->ClearCrashKeyValue(key);
310 }
311
312 static bool WrapMessageBoxWithSEH(const wchar_t* text, const wchar_t* caption,
313                                   UINT flags, bool* exit_now) {
314   // We wrap the call to MessageBoxW with a SEH handler because it some
315   // machines with CursorXP, PeaDict or with FontExplorer installed it crashes
316   // uncontrollably here. Being this a best effort deal we better go away.
317   __try {
318     *exit_now = (IDOK != ::MessageBoxW(NULL, text, caption, flags));
319   } __except(EXCEPTION_EXECUTE_HANDLER) {
320     // Its not safe to continue executing, exit silently here.
321     ::TerminateProcess(::GetCurrentProcess(),
322                        GetCrashReporterClient()->GetResultCodeRespawnFailed());
323   }
324
325   return true;
326 }
327
328 // This function is executed by the child process that DumpDoneCallback()
329 // spawned and basically just shows the 'chrome has crashed' dialog if
330 // the CHROME_CRASHED environment variable is present.
331 bool ShowRestartDialogIfCrashed(bool* exit_now) {
332   // If we are being launched in metro mode don't try to show the dialog.
333   if (base::win::IsMetroProcess())
334     return false;
335
336   base::string16 message;
337   base::string16 title;
338   bool is_rtl_locale;
339   if (!GetCrashReporterClient()->ShouldShowRestartDialog(
340           &title, &message, &is_rtl_locale)) {
341     return false;
342   }
343
344   // If the UI layout is right-to-left, we need to pass the appropriate MB_XXX
345   // flags so that an RTL message box is displayed.
346   UINT flags = MB_OKCANCEL | MB_ICONWARNING;
347   if (is_rtl_locale)
348     flags |= MB_RIGHT | MB_RTLREADING;
349
350   return WrapMessageBoxWithSEH(message.c_str(), title.c_str(), flags, exit_now);
351 }
352
353 // Crashes the process after generating a dump for the provided exception. Note
354 // that the crash reporter should be initialized before calling this function
355 // for it to do anything.
356 // NOTE: This function is used by SyzyASAN to invoke a crash. If you change the
357 // the name or signature of this function you will break SyzyASAN instrumented
358 // releases of Chrome. Please contact syzygy-team@chromium.org before doing so!
359 extern "C" int __declspec(dllexport) CrashForException(
360     EXCEPTION_POINTERS* info) {
361   if (g_breakpad) {
362     g_breakpad->WriteMinidumpForException(info);
363     // Patched stub exists based on conditions (See InitCrashReporter).
364     // As a side note this function also gets called from
365     // WindowProcExceptionFilter.
366     if (g_real_terminate_process_stub == NULL) {
367       ::TerminateProcess(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
368     } else {
369       NtTerminateProcessPtr real_terminate_proc =
370           reinterpret_cast<NtTerminateProcessPtr>(
371               static_cast<char*>(g_real_terminate_process_stub));
372       real_terminate_proc(::GetCurrentProcess(), content::RESULT_CODE_KILLED);
373     }
374   }
375   return EXCEPTION_CONTINUE_SEARCH;
376 }
377
378 #ifndef _WIN64
379 static NTSTATUS WINAPI HookNtTerminateProcess(HANDLE ProcessHandle,
380                                               NTSTATUS ExitStatus) {
381   if (g_breakpad &&
382       (ProcessHandle == ::GetCurrentProcess() || ProcessHandle == NULL)) {
383     NT_TIB* tib = reinterpret_cast<NT_TIB*>(NtCurrentTeb());
384     void* address_on_stack = _AddressOfReturnAddress();
385     if (address_on_stack < tib->StackLimit ||
386         address_on_stack > tib->StackBase) {
387       g_surrogate_exception_record.ExceptionAddress = _ReturnAddress();
388       g_surrogate_exception_record.ExceptionCode = DBG_TERMINATE_PROCESS;
389       g_surrogate_exception_record.ExceptionFlags = EXCEPTION_NONCONTINUABLE;
390       CrashForException(&g_surrogate_exception_pointers);
391     }
392   }
393
394   NtTerminateProcessPtr real_proc =
395       reinterpret_cast<NtTerminateProcessPtr>(
396           static_cast<char*>(g_real_terminate_process_stub));
397   return real_proc(ProcessHandle, ExitStatus);
398 }
399
400 static void InitTerminateProcessHooks() {
401   NtTerminateProcessPtr terminate_process_func_address =
402       reinterpret_cast<NtTerminateProcessPtr>(::GetProcAddress(
403           ::GetModuleHandle(L"ntdll.dll"), "NtTerminateProcess"));
404   if (terminate_process_func_address == NULL)
405     return;
406
407   DWORD old_protect = 0;
408   if (!::VirtualProtect(terminate_process_func_address, 5,
409                         PAGE_EXECUTE_READWRITE, &old_protect))
410     return;
411
412   g_real_terminate_process_stub = reinterpret_cast<char*>(VirtualAllocEx(
413       ::GetCurrentProcess(), NULL, sidestep::kMaxPreambleStubSize,
414       MEM_COMMIT, PAGE_EXECUTE_READWRITE));
415   if (g_real_terminate_process_stub == NULL)
416     return;
417
418   g_surrogate_exception_pointers.ContextRecord = &g_surrogate_context;
419   g_surrogate_exception_pointers.ExceptionRecord =
420       &g_surrogate_exception_record;
421
422   sidestep::SideStepError patch_result =
423       sidestep::PreamblePatcher::Patch(
424           terminate_process_func_address, HookNtTerminateProcess,
425           g_real_terminate_process_stub, sidestep::kMaxPreambleStubSize);
426   if (patch_result != sidestep::SIDESTEP_SUCCESS) {
427     CHECK(::VirtualFreeEx(::GetCurrentProcess(), g_real_terminate_process_stub,
428                     0, MEM_RELEASE));
429     CHECK(::VirtualProtect(terminate_process_func_address, 5, old_protect,
430                            &old_protect));
431     return;
432   }
433
434   DWORD dummy = 0;
435   CHECK(::VirtualProtect(terminate_process_func_address,
436                          5,
437                          old_protect,
438                          &dummy));
439   CHECK(::VirtualProtect(g_real_terminate_process_stub,
440                          sidestep::kMaxPreambleStubSize,
441                          old_protect,
442                          &old_protect));
443 }
444 #endif
445
446 static void InitPipeNameEnvVar(bool is_per_user_install) {
447   scoped_ptr<base::Environment> env(base::Environment::Create());
448   if (env->HasVar(kPipeNameVar)) {
449     // The Breakpad pipe name is already configured: nothing to do.
450     return;
451   }
452
453   // Check whether configuration management controls crash reporting.
454   bool crash_reporting_enabled = true;
455   bool controlled_by_policy =
456       GetCrashReporterClient()->ReportingIsEnforcedByPolicy(
457           &crash_reporting_enabled);
458
459   const CommandLine& command = *CommandLine::ForCurrentProcess();
460   bool use_crash_service = !controlled_by_policy &&
461                            (command.HasSwitch(switches::kNoErrorDialogs) ||
462                             GetCrashReporterClient()->IsRunningUnattended());
463
464   std::wstring pipe_name;
465   if (use_crash_service) {
466     // Crash reporting is done by crash_service.exe.
467     pipe_name = kChromePipeName;
468   } else {
469     // We want to use the Google Update crash reporting. We need to check if the
470     // user allows it first (in case the administrator didn't already decide
471     // via policy).
472     if (!controlled_by_policy)
473       crash_reporting_enabled =
474           GetCrashReporterClient()->GetCollectStatsConsent();
475
476     if (!crash_reporting_enabled) {
477       // Crash reporting is disabled, don't set the environment variable.
478       return;
479     }
480
481     // Build the pipe name. It can be either:
482     // System-wide install: "NamedPipe\GoogleCrashServices\S-1-5-18"
483     // Per-user install: "NamedPipe\GoogleCrashServices\<user SID>"
484     std::wstring user_sid;
485     if (is_per_user_install) {
486       if (!base::win::GetUserSidString(&user_sid)) {
487         return;
488       }
489     } else {
490       user_sid = kSystemPrincipalSid;
491     }
492
493     pipe_name = kGoogleUpdatePipeName;
494     pipe_name += user_sid;
495   }
496   env->SetVar(kPipeNameVar, base::UTF16ToASCII(pipe_name));
497 }
498
499 void InitDefaultCrashCallback(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
500   previous_filter = SetUnhandledExceptionFilter(filter);
501 }
502
503 void InitCrashReporter(const std::string& process_type_switch) {
504   const CommandLine& command = *CommandLine::ForCurrentProcess();
505   if (command.HasSwitch(switches::kDisableBreakpad))
506     return;
507
508   // Disable the message box for assertions.
509   _CrtSetReportMode(_CRT_ASSERT, 0);
510
511   base::string16 process_type = base::ASCIIToUTF16(process_type_switch);
512   if (process_type.empty())
513     process_type = L"browser";
514
515   wchar_t exe_path[MAX_PATH];
516   exe_path[0] = 0;
517   GetModuleFileNameW(NULL, exe_path, MAX_PATH);
518
519   bool is_per_user_install =
520       GetCrashReporterClient()->GetIsPerUserInstall(base::FilePath(exe_path));
521
522   // This is intentionally leaked.
523   CrashKeysWin* keeper = new CrashKeysWin();
524
525   google_breakpad::CustomClientInfo* custom_info =
526       keeper->GetCustomInfo(exe_path, process_type,
527                             GetProfileType(), CommandLine::ForCurrentProcess(),
528                             GetCrashReporterClient());
529
530   google_breakpad::ExceptionHandler::MinidumpCallback callback = NULL;
531   LPTOP_LEVEL_EXCEPTION_FILTER default_filter = NULL;
532   // We install the post-dump callback only for the browser and service
533   // processes. It spawns a new browser/service process.
534   if (process_type == L"browser") {
535     callback = &DumpDoneCallback;
536     default_filter = &ChromeExceptionFilter;
537   } else if (process_type == L"service") {
538     callback = &DumpDoneCallback;
539     default_filter = &ServiceExceptionFilter;
540   }
541
542   if (process_type == L"browser") {
543     InitPipeNameEnvVar(is_per_user_install);
544     GetCrashReporterClient()->InitBrowserCrashDumpsRegKey();
545   }
546
547   scoped_ptr<base::Environment> env(base::Environment::Create());
548   std::string pipe_name_ascii;
549   if (!env->GetVar(kPipeNameVar, &pipe_name_ascii)) {
550     // Breakpad is not enabled.  Configuration is managed or the user
551     // did not allow Google Update to send crashes.  We need to use
552     // our default crash handler instead, but only for the
553     // browser/service processes.
554     if (default_filter)
555       InitDefaultCrashCallback(default_filter);
556     return;
557   }
558   base::string16 pipe_name = base::ASCIIToUTF16(pipe_name_ascii);
559
560 #ifdef _WIN64
561   // The protocol for connecting to the out-of-process Breakpad crash
562   // reporter is different for x86-32 and x86-64: the message sizes
563   // are different because the message struct contains a pointer.  As
564   // a result, there are two different named pipes to connect to.  The
565   // 64-bit one is distinguished with an "-x64" suffix.
566   pipe_name += L"-x64";
567 #endif
568
569   // Get the alternate dump directory. We use the temp path.
570   wchar_t temp_dir[MAX_PATH] = {0};
571   ::GetTempPathW(MAX_PATH, temp_dir);
572
573   MINIDUMP_TYPE dump_type = kSmallDumpType;
574   // Capture full memory if explicitly instructed to.
575   if (command.HasSwitch(switches::kFullMemoryCrashReport))
576     dump_type = kFullDumpType;
577   else if (GetCrashReporterClient()->GetShouldDumpLargerDumps(
578                is_per_user_install))
579     dump_type = kLargerDumpType;
580
581   g_breakpad = new google_breakpad::ExceptionHandler(temp_dir, &FilterCallback,
582                    callback, NULL,
583                    google_breakpad::ExceptionHandler::HANDLER_ALL,
584                    dump_type, pipe_name.c_str(), custom_info);
585
586   // Now initialize the non crash dump handler.
587   g_dumphandler_no_crash = new google_breakpad::ExceptionHandler(temp_dir,
588       &FilterCallbackWhenNoCrash,
589       &DumpDoneCallbackWhenNoCrash,
590       NULL,
591       // Set the handler to none so this handler would not be added to
592       // |handler_stack_| in |ExceptionHandler| which is a list of exception
593       // handlers.
594       google_breakpad::ExceptionHandler::HANDLER_NONE,
595       dump_type, pipe_name.c_str(), custom_info);
596
597   // Set the DumpWithoutCrashingFunction for this instance of base.lib.  Other
598   // executable images linked with base should set this again for
599   // DumpWithoutCrashing to function correctly.
600   // See chrome_main.cc for example.
601   base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);
602
603   if (g_breakpad->IsOutOfProcess()) {
604     // Tells breakpad to handle breakpoint and single step exceptions.
605     // This might break JIT debuggers, but at least it will always
606     // generate a crashdump for these exceptions.
607     g_breakpad->set_handle_debug_exceptions(true);
608
609 #ifndef _WIN64
610     if (process_type != L"browser" &&
611         !GetCrashReporterClient()->IsRunningUnattended()) {
612       // Initialize the hook TerminateProcess to catch unexpected exits.
613       InitTerminateProcessHooks();
614     }
615 #endif
616   }
617 }
618
619 // If the user has disabled crash reporting uploads and restarted Chrome, the
620 // restarted instance will still contain the pipe environment variable, which
621 // will allow the restarted process to still upload crash reports. This function
622 // clears the environment variable, so that the restarted Chrome, which inherits
623 // its environment from the current Chrome, will no longer contain the variable.
624 extern "C" void __declspec(dllexport) __cdecl
625       ClearBreakpadPipeEnvironmentVariable() {
626   scoped_ptr<base::Environment> env(base::Environment::Create());
627   env->UnSetVar(kPipeNameVar);
628 }
629
630 #ifdef _WIN64
631 int CrashForExceptionInNonABICompliantCodeRange(
632     PEXCEPTION_RECORD ExceptionRecord,
633     ULONG64 EstablisherFrame,
634     PCONTEXT ContextRecord,
635     PDISPATCHER_CONTEXT DispatcherContext) {
636   EXCEPTION_POINTERS info = { ExceptionRecord, ContextRecord };
637   return CrashForException(&info);
638 }
639
640 struct ExceptionHandlerRecord {
641   RUNTIME_FUNCTION runtime_function;
642   UNWIND_INFO unwind_info;
643   unsigned char thunk[12];
644 };
645
646 extern "C" void __declspec(dllexport) __cdecl
647 RegisterNonABICompliantCodeRange(void* start, size_t size_in_bytes) {
648   ExceptionHandlerRecord* record =
649       reinterpret_cast<ExceptionHandlerRecord*>(start);
650
651   // We assume that the first page of the code range is executable and
652   // committed and reserved for breakpad. What could possibly go wrong?
653
654   // All addresses are 32bit relative offsets to start.
655   record->runtime_function.BeginAddress = 0;
656   record->runtime_function.EndAddress =
657       base::checked_cast<DWORD>(size_in_bytes);
658   record->runtime_function.UnwindData =
659       offsetof(ExceptionHandlerRecord, unwind_info);
660
661   // Create unwind info that only specifies an exception handler.
662   record->unwind_info.Version = 1;
663   record->unwind_info.Flags = UNW_FLAG_EHANDLER;
664   record->unwind_info.SizeOfProlog = 0;
665   record->unwind_info.CountOfCodes = 0;
666   record->unwind_info.FrameRegister = 0;
667   record->unwind_info.FrameOffset = 0;
668   record->unwind_info.ExceptionHandler =
669       offsetof(ExceptionHandlerRecord, thunk);
670
671   // Hardcoded thunk.
672   // mov imm64, rax
673   record->thunk[0] = 0x48;
674   record->thunk[1] = 0xb8;
675   void* handler = &CrashForExceptionInNonABICompliantCodeRange;
676   memcpy(&record->thunk[2], &handler, 8);
677
678   // jmp rax
679   record->thunk[10] = 0xff;
680   record->thunk[11] = 0xe0;
681
682   // Protect reserved page against modifications.
683   DWORD old_protect;
684   CHECK(VirtualProtect(
685       start, sizeof(ExceptionHandlerRecord), PAGE_EXECUTE_READ, &old_protect));
686   CHECK(RtlAddFunctionTable(
687       &record->runtime_function, 1, reinterpret_cast<DWORD64>(start)));
688 }
689
690 extern "C" void __declspec(dllexport) __cdecl
691 UnregisterNonABICompliantCodeRange(void* start) {
692   ExceptionHandlerRecord* record =
693       reinterpret_cast<ExceptionHandlerRecord*>(start);
694
695   CHECK(RtlDeleteFunctionTable(&record->runtime_function));
696 }
697 #endif
698
699 }  // namespace breakpad