1 // Copyright (c) 2006, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 30 // ExceptionHandler can write a minidump file when an exception occurs, 31 // or when WriteMinidump() is called explicitly by your program. 32 // 33 // To have the exception handler write minidumps when an uncaught exception 34 // (crash) occurs, you should create an instance early in the execution 35 // of your program, and keep it around for the entire time you want to 36 // have crash handling active (typically, until shutdown). 37 // 38 // If you want to write minidumps without installing the exception handler, 39 // you can create an ExceptionHandler with install_handler set to false, 40 // then call WriteMinidump. You can also use this technique if you want to 41 // use different minidump callbacks for different call sites. 42 // 43 // In either case, a callback function is called when a minidump is written, 44 // which receives the unqiue id of the minidump. The caller can use this 45 // id to collect and write additional application state, and to launch an 46 // external crash-reporting application. 47 // 48 // It is important that creation and destruction of ExceptionHandler objects 49 // be nested cleanly, when using install_handler = true. 50 // Avoid the following pattern: 51 // ExceptionHandler *e = new ExceptionHandler(...); 52 // ExceptionHandler *f = new ExceptionHandler(...); 53 // delete e; 54 // This will put the exception filter stack into an inconsistent state. 55 56 #ifndef CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__ 57 #define CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__ 58 59 #include <stdlib.h> 60 #include <windows.h> 61 #include <dbghelp.h> 62 #include <rpc.h> 63 64 #pragma warning(push) 65 // Disable exception handler warnings. 66 #pragma warning(disable:4530) 67 68 #include <list> 69 #include <string> 70 #include <vector> 71 72 #include "windows/common/minidump_callback.h" 73 #include "windows/common/ipc_protocol.h" 74 #include "windows/crash_generation/crash_generation_client.h" 75 #include "common/scoped_ptr.h" 76 #include "google_breakpad/common/minidump_format.h" 77 78 #ifdef MOZ_PHC 79 #include "PHC.h" 80 #else 81 namespace mozilla { namespace phc { class AddrInfo {}; } } 82 #endif 83 84 namespace google_breakpad { 85 86 using std::vector; 87 using std::wstring; 88 89 class ExceptionHandler { 90 public: 91 // The result value for the filter callback, see below. 92 enum class FilterResult { 93 HandleException, 94 AbortWithoutMinidump, 95 ContinueSearch 96 }; 97 98 // A callback function to run before Breakpad performs any substantial 99 // processing of an exception. A FilterCallback is called before writing 100 // a minidump. context is the parameter supplied by the user as 101 // callback_context when the handler was created. exinfo points to the 102 // exception record, if any; assertion points to assertion information, 103 // if any. 104 // 105 // If a FilterCallback returns HandleException, Breakpad will attempt to 106 // write a minidump. If a FilterCallback returns ContinueSearch Breakpad 107 // will immediately report the exception as unhandled without writing a 108 // minidump, allowing another handler the opportunity to handle it. 109 // If a FilterCallback returns AbortWithoutMinidump, Breakpad will report the 110 // exception as handled but will not write a minidump, letting the process 111 // terminate itself instead. 112 typedef FilterResult (*FilterCallback)(void* context, 113 EXCEPTION_POINTERS* exinfo, 114 MDRawAssertionInfo* assertion); 115 116 // A callback function to run after the minidump has been written. 117 // minidump_id is a unique id for the dump, so the minidump 118 // file is <dump_path>\<minidump_id>.dmp. context is the parameter supplied 119 // by the user as callback_context when the handler was created. exinfo 120 // points to the exception record, or NULL if no exception occurred. 121 // succeeded indicates whether a minidump file was successfully written. 122 // assertion points to information about an assertion if the handler was 123 // invoked by an assertion. 124 // 125 // If an exception occurred and the callback returns true, Breakpad will treat 126 // the exception as fully-handled, suppressing any other handlers from being 127 // notified of the exception. If the callback returns false, Breakpad will 128 // treat the exception as unhandled, and allow another handler to handle it. 129 // If there are no other handlers, Breakpad will report the exception to the 130 // system as unhandled, allowing a debugger or native crash dialog the 131 // opportunity to handle the exception. Most callback implementations 132 // should normally return the value of |succeeded|, or when they wish to 133 // not report an exception of handled, false. Callbacks will rarely want to 134 // return true directly (unless |succeeded| is true). 135 // 136 // For out-of-process dump generation, dump path and minidump ID will always 137 // be NULL. In case of out-of-process dump generation, the dump path and 138 // minidump id are controlled by the server process and are not communicated 139 // back to the crashing process. 140 typedef bool (*MinidumpCallback)(const wchar_t* dump_path, 141 const wchar_t* minidump_id, 142 void* context, 143 EXCEPTION_POINTERS* exinfo, 144 MDRawAssertionInfo* assertion, 145 const mozilla::phc::AddrInfo* addr_info, 146 bool succeeded); 147 148 // HandlerType specifies which types of handlers should be installed, if 149 // any. Use HANDLER_NONE for an ExceptionHandler that remains idle, 150 // without catching any failures on its own. This type of handler may 151 // still be triggered by calling WriteMinidump. Otherwise, use a 152 // combination of the other HANDLER_ values, or HANDLER_ALL to install 153 // all handlers. 154 enum HandlerType { 155 HANDLER_NONE = 0, 156 HANDLER_EXCEPTION = 1 << 0, // SetUnhandledExceptionFilter 157 HANDLER_INVALID_PARAMETER = 1 << 1, // _set_invalid_parameter_handler 158 HANDLER_PURECALL = 1 << 2, // _set_purecall_handler 159 HANDLER_ALL = HANDLER_EXCEPTION | 160 HANDLER_INVALID_PARAMETER | 161 HANDLER_PURECALL 162 }; 163 164 // Creates a new ExceptionHandler instance to handle writing minidumps. 165 // Before writing a minidump, the optional filter callback will be called. 166 // Its return value determines whether or not Breakpad should write a 167 // minidump. Minidump files will be written to dump_path, and the optional 168 // callback is called after writing the dump file, as described above. 169 // handler_types specifies the types of handlers that should be installed. 170 ExceptionHandler(const wstring& dump_path, 171 FilterCallback filter, 172 MinidumpCallback callback, 173 void* callback_context, 174 int handler_types); 175 176 // Creates a new ExceptionHandler instance that can attempt to perform 177 // out-of-process dump generation if pipe_name is not NULL. If pipe_name is 178 // NULL, or if out-of-process dump generation registration step fails, 179 // in-process dump generation will be used. This also allows specifying 180 // the dump type to generate. 181 ExceptionHandler(const wstring& dump_path, 182 FilterCallback filter, 183 MinidumpCallback callback, 184 void* callback_context, 185 int handler_types, 186 MINIDUMP_TYPE dump_type, 187 const wchar_t* pipe_name, 188 const CustomClientInfo* custom_info); 189 190 // As above, creates a new ExceptionHandler instance to perform 191 // out-of-process dump generation if the given pipe_handle is not NULL. 192 ExceptionHandler(const wstring& dump_path, 193 FilterCallback filter, 194 MinidumpCallback callback, 195 void* callback_context, 196 int handler_types, 197 MINIDUMP_TYPE dump_type, 198 HANDLE pipe_handle, 199 const CustomClientInfo* custom_info); 200 201 // ExceptionHandler that ENSURES out-of-process dump generation. Expects a 202 // crash generation client that is already registered with a crash generation 203 // server. Takes ownership of the passed-in crash_generation_client. 204 // 205 // Usage example: 206 // crash_generation_client = new CrashGenerationClient(..); 207 // if (crash_generation_client->Register()) { 208 // // Registration with the crash generation server succeeded. 209 // // Out-of-process dump generation is guaranteed. 210 // g_handler = new ExceptionHandler(.., crash_generation_client, ..); 211 // return true; 212 // } 213 ExceptionHandler(const wstring& dump_path, 214 FilterCallback filter, 215 MinidumpCallback callback, 216 void* callback_context, 217 int handler_types, 218 CrashGenerationClient* crash_generation_client); 219 220 ~ExceptionHandler(); 221 222 // Get and set the minidump path. dump_path()223 wstring dump_path() const { return dump_path_; } set_dump_path(const wstring & dump_path)224 void set_dump_path(const wstring &dump_path) { 225 dump_path_ = dump_path; 226 dump_path_c_ = dump_path_.c_str(); 227 UpdateNextID(); // Necessary to put dump_path_ in next_minidump_path_. 228 } 229 230 // Requests that a previously reported crash be uploaded. 231 bool RequestUpload(DWORD crash_id); 232 233 // Writes a minidump immediately. This can be used to capture the 234 // execution state independently of a crash. Returns true on success. 235 bool WriteMinidump(); 236 237 // Writes a minidump immediately, with the user-supplied exception 238 // information. 239 bool WriteMinidumpForException(EXCEPTION_POINTERS* exinfo); 240 241 // Convenience form of WriteMinidump which does not require an 242 // ExceptionHandler instance. 243 static bool WriteMinidump(const wstring &dump_path, 244 MinidumpCallback callback, void* callback_context, 245 MINIDUMP_TYPE dump_type = MiniDumpNormal); 246 247 // Write a minidump of |child| immediately. This can be used to 248 // capture the execution state of |child| independently of a crash. 249 // Pass a meaningful |child_blamed_thread| to make that thread in 250 // the child process the one from which a crash signature is 251 // extracted. 252 static bool WriteMinidumpForChild(HANDLE child, 253 DWORD child_blamed_thread, 254 const wstring& dump_path, 255 MinidumpCallback callback, 256 void* callback_context, 257 MINIDUMP_TYPE dump_type = MiniDumpNormal); 258 259 // Get the thread ID of the thread requesting the dump (either the exception 260 // thread or any other thread that called WriteMinidump directly). This 261 // may be useful if you want to include additional thread state in your 262 // dumps. get_requesting_thread_id()263 DWORD get_requesting_thread_id() const { return requesting_thread_id_; } 264 265 // Controls behavior of EXCEPTION_BREAKPOINT and EXCEPTION_SINGLE_STEP. get_handle_debug_exceptions()266 bool get_handle_debug_exceptions() const { return handle_debug_exceptions_; } set_handle_debug_exceptions(bool handle_debug_exceptions)267 void set_handle_debug_exceptions(bool handle_debug_exceptions) { 268 handle_debug_exceptions_ = handle_debug_exceptions; 269 } 270 271 // Controls behavior of EXCEPTION_INVALID_HANDLE. get_consume_invalid_handle_exceptions()272 bool get_consume_invalid_handle_exceptions() const { 273 return consume_invalid_handle_exceptions_; 274 } set_consume_invalid_handle_exceptions(bool consume_invalid_handle_exceptions)275 void set_consume_invalid_handle_exceptions( 276 bool consume_invalid_handle_exceptions) { 277 consume_invalid_handle_exceptions_ = consume_invalid_handle_exceptions; 278 } 279 280 // Returns whether out-of-process dump generation is used or not. IsOutOfProcess()281 bool IsOutOfProcess() const { return crash_generation_client_.get() != NULL; } 282 283 // Calling RegisterAppMemory(p, len) causes len bytes starting 284 // at address p to be copied to the minidump when a crash happens. 285 void RegisterAppMemory(void* ptr, size_t length); 286 void UnregisterAppMemory(void* ptr); 287 288 // Calling set_include_context_heap(true) causes heap regions to be included 289 // in the minidump when a crash happens. The heap regions are from the 290 // register values of the crashing context. 291 void set_include_context_heap(bool enabled); 292 293 private: 294 friend class AutoExceptionHandler; 295 296 // Initializes the instance with given values. 297 void Initialize(const wstring& dump_path, 298 FilterCallback filter, 299 MinidumpCallback callback, 300 void* callback_context, 301 int handler_types, 302 MINIDUMP_TYPE dump_type, 303 const wchar_t* pipe_name, 304 HANDLE pipe_handle, 305 CrashGenerationClient* crash_generation_client, 306 const CustomClientInfo* custom_info); 307 308 // Function pointer type for MiniDumpWriteDump, which is looked up 309 // dynamically. 310 typedef BOOL (WINAPI *MiniDumpWriteDump_type)( 311 HANDLE hProcess, 312 DWORD dwPid, 313 HANDLE hFile, 314 MINIDUMP_TYPE DumpType, 315 CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, 316 CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, 317 CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); 318 319 // Function pointer type for UuidCreate, which is looked up dynamically. 320 typedef RPC_STATUS (RPC_ENTRY *UuidCreate_type)(UUID* Uuid); 321 322 // Runs the main loop for the exception handler thread. 323 static DWORD WINAPI ExceptionHandlerThreadMain(void* lpParameter); 324 325 // Called on the exception thread when an unhandled exception occurs. 326 // Signals the exception handler thread to handle the exception. 327 static LONG WINAPI HandleException(EXCEPTION_POINTERS* exinfo); 328 329 #if _MSC_VER >= 1400 // MSVC 2005/8 330 // This function will be called by some CRT functions when they detect 331 // that they were passed an invalid parameter. Note that in _DEBUG builds, 332 // the CRT may display an assertion dialog before calling this function, 333 // and the function will not be called unless the assertion dialog is 334 // dismissed by clicking "Ignore." 335 static void HandleInvalidParameter(const wchar_t* expression, 336 const wchar_t* function, 337 const wchar_t* file, 338 unsigned int line, 339 uintptr_t reserved); 340 #endif // _MSC_VER >= 1400 341 342 // This function will be called by the CRT when a pure virtual 343 // function is called. 344 static void HandlePureVirtualCall(); 345 346 // This is called on the exception thread or on another thread that 347 // the user wishes to produce a dump from. It calls 348 // WriteMinidumpWithException on the handler thread, avoiding stack 349 // overflows and inconsistent dumps due to writing the dump from 350 // the exception thread. If the dump is requested as a result of an 351 // exception, exinfo contains exception information, otherwise, it 352 // is NULL. If the dump is requested as a result of an assertion 353 // (such as an invalid parameter being passed to a CRT function), 354 // assertion contains data about the assertion, otherwise, it is NULL. 355 bool WriteMinidumpOnHandlerThread(EXCEPTION_POINTERS* exinfo, 356 MDRawAssertionInfo* assertion); 357 358 // The return value for WriteMinidumpWithException(), see below. 359 enum class MinidumpResult { 360 Success, 361 Failure, 362 Ignored 363 }; 364 365 // This function is called on the handler thread. It calls into 366 // WriteMinidumpWithExceptionForProcess() with a handle to the 367 // current process. requesting_thread_id is the ID of the thread 368 // that requested the dump. If the dump is requested as a result of 369 // an exception, exinfo contains exception information, otherwise, 370 // it is NULL. It will return Success in case the minidump has been written 371 // successfully, Failure if we couldn't write out the minidump because of an 372 // error and Ignored if we didn't even try to write the minidump because the 373 // filter callback indicated that we should ignore this exception and abort. 374 // The latter condition is only relevent for a top-level exception handler, 375 // other callers should equate it to a failure. 376 MinidumpResult WriteMinidumpWithException(DWORD requesting_thread_id, 377 EXCEPTION_POINTERS* exinfo, 378 MDRawAssertionInfo* assertion); 379 380 // This function does the actual writing of a minidump. It is 381 // called on the handler thread. requesting_thread_id is the ID of 382 // the thread that requested the dump, if that information is 383 // meaningful. If the dump is requested as a result of an 384 // exception, exinfo contains exception information, otherwise, it 385 // is NULL. process is the one that will be dumped. If 386 // requesting_thread_id is meaningful and should be added to the 387 // minidump, write_requester_stream is |true|. 388 bool WriteMinidumpWithExceptionForProcess(DWORD requesting_thread_id, 389 EXCEPTION_POINTERS* exinfo, 390 MDRawAssertionInfo* assertion, 391 HANDLE process, 392 bool write_requester_stream); 393 394 // Generates a new ID and stores it in next_minidump_id_, and stores the 395 // path of the next minidump to be written in next_minidump_path_. 396 void UpdateNextID(); 397 398 FilterCallback filter_; 399 MinidumpCallback callback_; 400 void* callback_context_; 401 402 scoped_ptr<CrashGenerationClient> crash_generation_client_; 403 404 // The directory in which a minidump will be written, set by the dump_path 405 // argument to the constructor, or set_dump_path. 406 wstring dump_path_; 407 408 // The basename of the next minidump to be written, without the extension. 409 wstring next_minidump_id_; 410 411 // The full pathname of the next minidump to be written, including the file 412 // extension. 413 wstring next_minidump_path_; 414 415 // Pointers to C-string representations of the above. These are set when 416 // the above wstring versions are set in order to avoid calling c_str during 417 // an exception, as c_str may attempt to allocate heap memory. These 418 // pointers are not owned by the ExceptionHandler object, but their lifetimes 419 // should be equivalent to the lifetimes of the associated wstring, provided 420 // that the wstrings are not altered. 421 const wchar_t* dump_path_c_; 422 const wchar_t* next_minidump_id_c_; 423 const wchar_t* next_minidump_path_c_; 424 425 HMODULE dbghelp_module_; 426 MiniDumpWriteDump_type minidump_write_dump_; 427 MINIDUMP_TYPE dump_type_; 428 429 HMODULE rpcrt4_module_; 430 UuidCreate_type uuid_create_; 431 432 // Tracks the handler types that were installed according to the 433 // handler_types constructor argument. 434 int handler_types_; 435 436 // When installed_handler_ is true, previous_filter_ is the unhandled 437 // exception filter that was set prior to installing ExceptionHandler as 438 // the unhandled exception filter and pointing it to |this|. NULL indicates 439 // that there is no previous unhandled exception filter. 440 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter_; 441 442 #if _MSC_VER >= 1400 // MSVC 2005/8 443 // Beginning in VC 8, the CRT provides an invalid parameter handler that will 444 // be called when some CRT functions are passed invalid parameters. In 445 // earlier CRTs, the same conditions would cause unexpected behavior or 446 // crashes. 447 _invalid_parameter_handler previous_iph_; 448 #endif // _MSC_VER >= 1400 449 450 // The CRT allows you to override the default handler for pure 451 // virtual function calls. 452 _purecall_handler previous_pch_; 453 454 // The exception handler thread. 455 HANDLE handler_thread_; 456 457 // True if the exception handler is being destroyed. 458 // Starting with MSVC 2005, Visual C has stronger guarantees on volatile vars. 459 // It has release semantics on write and acquire semantics on reads. 460 // See the msdn documentation. 461 volatile bool is_shutdown_; 462 463 // The critical section enforcing the requirement that only one exception be 464 // handled by a handler at a time. 465 CRITICAL_SECTION handler_critical_section_; 466 467 // Semaphores used to move exception handling between the exception thread 468 // and the handler thread. handler_start_semaphore_ is signalled by the 469 // exception thread to wake up the handler thread when an exception occurs. 470 // handler_finish_semaphore_ is signalled by the handler thread to wake up 471 // the exception thread when handling is complete. 472 HANDLE handler_start_semaphore_; 473 HANDLE handler_finish_semaphore_; 474 475 // The next 2 fields contain data passed from the requesting thread to 476 // the handler thread. 477 478 // The thread ID of the thread requesting the dump (either the exception 479 // thread or any other thread that called WriteMinidump directly). 480 DWORD requesting_thread_id_; 481 482 // The exception info passed to the exception handler on the exception 483 // thread, if an exception occurred. NULL for user-requested dumps. 484 EXCEPTION_POINTERS* exception_info_; 485 486 // If the handler is invoked due to an assertion, this will contain a 487 // pointer to the assertion information. It is NULL at other times. 488 MDRawAssertionInfo* assertion_; 489 490 // The return value of the handler, passed from the handler thread back to 491 // the requesting thread. 492 MinidumpResult handler_return_value_; 493 494 // If true, the handler will intercept EXCEPTION_BREAKPOINT and 495 // EXCEPTION_SINGLE_STEP exceptions. Leave this false (the default) 496 // to not interfere with debuggers. 497 bool handle_debug_exceptions_; 498 499 // If true, the handler will consume any EXCEPTION_INVALID_HANDLE exceptions. 500 // Leave this false (the default) to handle these exceptions as normal. 501 bool consume_invalid_handle_exceptions_; 502 503 // Callers can request additional memory regions to be included in 504 // the dump. 505 AppMemoryList app_memory_info_; 506 507 // A stack of ExceptionHandler objects that have installed unhandled 508 // exception filters. This vector is used by HandleException to determine 509 // which ExceptionHandler object to route an exception to. When an 510 // ExceptionHandler is created with install_handler true, it will append 511 // itself to this list. 512 static vector<ExceptionHandler*>* handler_stack_; 513 514 // The index of the ExceptionHandler in handler_stack_ that will handle the 515 // next exception. Note that 0 means the last entry in handler_stack_, 1 516 // means the next-to-last entry, and so on. This is used by HandleException 517 // to support multiple stacked Breakpad handlers. 518 static LONG handler_stack_index_; 519 520 // handler_stack_critical_section_ guards operations on handler_stack_ and 521 // handler_stack_index_. The critical section is initialized by the 522 // first instance of the class and destroyed by the last instance of it. 523 static CRITICAL_SECTION handler_stack_critical_section_; 524 525 // The number of instances of this class. 526 static volatile LONG instance_count_; 527 528 bool include_context_heap_; 529 530 // disallow copy ctor and operator= 531 explicit ExceptionHandler(const ExceptionHandler &); 532 void operator=(const ExceptionHandler &); 533 }; 534 535 } // namespace google_breakpad 536 537 #pragma warning(pop) 538 539 #endif // CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__ 540