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 namespace google_breakpad { 79 80 using std::vector; 81 using std::wstring; 82 83 class ExceptionHandler { 84 public: 85 // A callback function to run before Breakpad performs any substantial 86 // processing of an exception. A FilterCallback is called before writing 87 // a minidump. context is the parameter supplied by the user as 88 // callback_context when the handler was created. exinfo points to the 89 // exception record, if any; assertion points to assertion information, 90 // if any. 91 // 92 // If a FilterCallback returns true, Breakpad will continue processing, 93 // attempting to write a minidump. If a FilterCallback returns false, 94 // Breakpad will immediately report the exception as unhandled without 95 // writing a minidump, allowing another handler the opportunity to handle it. 96 typedef bool (*FilterCallback)(void* context, EXCEPTION_POINTERS* exinfo, 97 MDRawAssertionInfo* assertion); 98 99 // A callback function to run after the minidump has been written. 100 // minidump_id is a unique id for the dump, so the minidump 101 // file is <dump_path>\<minidump_id>.dmp. context is the parameter supplied 102 // by the user as callback_context when the handler was created. exinfo 103 // points to the exception record, or NULL if no exception occurred. 104 // succeeded indicates whether a minidump file was successfully written. 105 // assertion points to information about an assertion if the handler was 106 // invoked by an assertion. 107 // 108 // If an exception occurred and the callback returns true, Breakpad will treat 109 // the exception as fully-handled, suppressing any other handlers from being 110 // notified of the exception. If the callback returns false, Breakpad will 111 // treat the exception as unhandled, and allow another handler to handle it. 112 // If there are no other handlers, Breakpad will report the exception to the 113 // system as unhandled, allowing a debugger or native crash dialog the 114 // opportunity to handle the exception. Most callback implementations 115 // should normally return the value of |succeeded|, or when they wish to 116 // not report an exception of handled, false. Callbacks will rarely want to 117 // return true directly (unless |succeeded| is true). 118 // 119 // For out-of-process dump generation, dump path and minidump ID will always 120 // be NULL. In case of out-of-process dump generation, the dump path and 121 // minidump id are controlled by the server process and are not communicated 122 // back to the crashing process. 123 typedef bool (*MinidumpCallback)(const wchar_t* dump_path, 124 const wchar_t* minidump_id, 125 void* context, 126 EXCEPTION_POINTERS* exinfo, 127 MDRawAssertionInfo* assertion, 128 bool succeeded); 129 130 // HandlerType specifies which types of handlers should be installed, if 131 // any. Use HANDLER_NONE for an ExceptionHandler that remains idle, 132 // without catching any failures on its own. This type of handler may 133 // still be triggered by calling WriteMinidump. Otherwise, use a 134 // combination of the other HANDLER_ values, or HANDLER_ALL to install 135 // all handlers. 136 enum HandlerType { 137 HANDLER_NONE = 0, 138 HANDLER_EXCEPTION = 1 << 0, // SetUnhandledExceptionFilter 139 HANDLER_INVALID_PARAMETER = 1 << 1, // _set_invalid_parameter_handler 140 HANDLER_PURECALL = 1 << 2, // _set_purecall_handler 141 HANDLER_ALL = HANDLER_EXCEPTION | 142 HANDLER_INVALID_PARAMETER | 143 HANDLER_PURECALL 144 }; 145 146 // Creates a new ExceptionHandler instance to handle writing minidumps. 147 // Before writing a minidump, the optional filter callback will be called. 148 // Its return value determines whether or not Breakpad should write a 149 // minidump. Minidump files will be written to dump_path, and the optional 150 // callback is called after writing the dump file, as described above. 151 // handler_types specifies the types of handlers that should be installed. 152 ExceptionHandler(const wstring& dump_path, 153 FilterCallback filter, 154 MinidumpCallback callback, 155 void* callback_context, 156 int handler_types); 157 158 // Creates a new ExceptionHandler instance that can attempt to perform 159 // out-of-process dump generation if pipe_name is not NULL. If pipe_name is 160 // NULL, or if out-of-process dump generation registration step fails, 161 // in-process dump generation will be used. This also allows specifying 162 // the dump type to generate. 163 ExceptionHandler(const wstring& dump_path, 164 FilterCallback filter, 165 MinidumpCallback callback, 166 void* callback_context, 167 int handler_types, 168 MINIDUMP_TYPE dump_type, 169 const wchar_t* pipe_name, 170 const CustomClientInfo* custom_info); 171 172 // As above, creates a new ExceptionHandler instance to perform 173 // out-of-process dump generation if the given pipe_handle is not NULL. 174 ExceptionHandler(const wstring& dump_path, 175 FilterCallback filter, 176 MinidumpCallback callback, 177 void* callback_context, 178 int handler_types, 179 MINIDUMP_TYPE dump_type, 180 HANDLE pipe_handle, 181 const CustomClientInfo* custom_info); 182 183 // ExceptionHandler that ENSURES out-of-process dump generation. Expects a 184 // crash generation client that is already registered with a crash generation 185 // server. Takes ownership of the passed-in crash_generation_client. 186 // 187 // Usage example: 188 // crash_generation_client = new CrashGenerationClient(..); 189 // if (crash_generation_client->Register()) { 190 // // Registration with the crash generation server succeeded. 191 // // Out-of-process dump generation is guaranteed. 192 // g_handler = new ExceptionHandler(.., crash_generation_client, ..); 193 // return true; 194 // } 195 ExceptionHandler(const wstring& dump_path, 196 FilterCallback filter, 197 MinidumpCallback callback, 198 void* callback_context, 199 int handler_types, 200 CrashGenerationClient* crash_generation_client); 201 202 ~ExceptionHandler(); 203 204 // Get and set the minidump path. dump_path()205 wstring dump_path() const { return dump_path_; } set_dump_path(const wstring & dump_path)206 void set_dump_path(const wstring &dump_path) { 207 dump_path_ = dump_path; 208 dump_path_c_ = dump_path_.c_str(); 209 UpdateNextID(); // Necessary to put dump_path_ in next_minidump_path_. 210 } 211 212 // Requests that a previously reported crash be uploaded. 213 bool RequestUpload(DWORD crash_id); 214 215 // Writes a minidump immediately. This can be used to capture the 216 // execution state independently of a crash. Returns true on success. 217 bool WriteMinidump(); 218 219 // Writes a minidump immediately, with the user-supplied exception 220 // information. 221 bool WriteMinidumpForException(EXCEPTION_POINTERS* exinfo); 222 223 // Convenience form of WriteMinidump which does not require an 224 // ExceptionHandler instance. 225 static bool WriteMinidump(const wstring &dump_path, 226 MinidumpCallback callback, void* callback_context, 227 MINIDUMP_TYPE dump_type = MiniDumpNormal); 228 229 // Write a minidump of |child| immediately. This can be used to 230 // capture the execution state of |child| independently of a crash. 231 // Pass a meaningful |child_blamed_thread| to make that thread in 232 // the child process the one from which a crash signature is 233 // extracted. 234 static bool WriteMinidumpForChild(HANDLE child, 235 DWORD child_blamed_thread, 236 const wstring& dump_path, 237 MinidumpCallback callback, 238 void* callback_context, 239 MINIDUMP_TYPE dump_type = MiniDumpNormal); 240 241 // Get the thread ID of the thread requesting the dump (either the exception 242 // thread or any other thread that called WriteMinidump directly). This 243 // may be useful if you want to include additional thread state in your 244 // dumps. get_requesting_thread_id()245 DWORD get_requesting_thread_id() const { return requesting_thread_id_; } 246 247 // Controls behavior of EXCEPTION_BREAKPOINT and EXCEPTION_SINGLE_STEP. get_handle_debug_exceptions()248 bool get_handle_debug_exceptions() const { return handle_debug_exceptions_; } set_handle_debug_exceptions(bool handle_debug_exceptions)249 void set_handle_debug_exceptions(bool handle_debug_exceptions) { 250 handle_debug_exceptions_ = handle_debug_exceptions; 251 } 252 253 // Controls behavior of EXCEPTION_INVALID_HANDLE. get_consume_invalid_handle_exceptions()254 bool get_consume_invalid_handle_exceptions() const { 255 return consume_invalid_handle_exceptions_; 256 } set_consume_invalid_handle_exceptions(bool consume_invalid_handle_exceptions)257 void set_consume_invalid_handle_exceptions( 258 bool consume_invalid_handle_exceptions) { 259 consume_invalid_handle_exceptions_ = consume_invalid_handle_exceptions; 260 } 261 262 // Returns whether out-of-process dump generation is used or not. IsOutOfProcess()263 bool IsOutOfProcess() const { return crash_generation_client_.get() != NULL; } 264 265 // Calling RegisterAppMemory(p, len) causes len bytes starting 266 // at address p to be copied to the minidump when a crash happens. 267 void RegisterAppMemory(void* ptr, size_t length); 268 void UnregisterAppMemory(void* ptr); 269 270 // Calling set_include_context_heap(true) causes heap regions to be included 271 // in the minidump when a crash happens. The heap regions are from the 272 // register values of the crashing context. 273 void set_include_context_heap(bool enabled); 274 275 private: 276 friend class AutoExceptionHandler; 277 278 // Initializes the instance with given values. 279 void Initialize(const wstring& dump_path, 280 FilterCallback filter, 281 MinidumpCallback callback, 282 void* callback_context, 283 int handler_types, 284 MINIDUMP_TYPE dump_type, 285 const wchar_t* pipe_name, 286 HANDLE pipe_handle, 287 CrashGenerationClient* crash_generation_client, 288 const CustomClientInfo* custom_info); 289 290 // Function pointer type for MiniDumpWriteDump, which is looked up 291 // dynamically. 292 typedef BOOL (WINAPI *MiniDumpWriteDump_type)( 293 HANDLE hProcess, 294 DWORD dwPid, 295 HANDLE hFile, 296 MINIDUMP_TYPE DumpType, 297 CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, 298 CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, 299 CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); 300 301 // Function pointer type for UuidCreate, which is looked up dynamically. 302 typedef RPC_STATUS (RPC_ENTRY *UuidCreate_type)(UUID* Uuid); 303 304 // Runs the main loop for the exception handler thread. 305 static DWORD WINAPI ExceptionHandlerThreadMain(void* lpParameter); 306 307 // Called on the exception thread when an unhandled exception occurs. 308 // Signals the exception handler thread to handle the exception. 309 static LONG WINAPI HandleException(EXCEPTION_POINTERS* exinfo); 310 311 #if _MSC_VER >= 1400 // MSVC 2005/8 312 // This function will be called by some CRT functions when they detect 313 // that they were passed an invalid parameter. Note that in _DEBUG builds, 314 // the CRT may display an assertion dialog before calling this function, 315 // and the function will not be called unless the assertion dialog is 316 // dismissed by clicking "Ignore." 317 static void HandleInvalidParameter(const wchar_t* expression, 318 const wchar_t* function, 319 const wchar_t* file, 320 unsigned int line, 321 uintptr_t reserved); 322 #endif // _MSC_VER >= 1400 323 324 // This function will be called by the CRT when a pure virtual 325 // function is called. 326 static void HandlePureVirtualCall(); 327 328 // This is called on the exception thread or on another thread that 329 // the user wishes to produce a dump from. It calls 330 // WriteMinidumpWithException on the handler thread, avoiding stack 331 // overflows and inconsistent dumps due to writing the dump from 332 // the exception thread. If the dump is requested as a result of an 333 // exception, exinfo contains exception information, otherwise, it 334 // is NULL. If the dump is requested as a result of an assertion 335 // (such as an invalid parameter being passed to a CRT function), 336 // assertion contains data about the assertion, otherwise, it is NULL. 337 bool WriteMinidumpOnHandlerThread(EXCEPTION_POINTERS* exinfo, 338 MDRawAssertionInfo* assertion); 339 340 // This function is called on the handler thread. It calls into 341 // WriteMinidumpWithExceptionForProcess() with a handle to the 342 // current process. requesting_thread_id is the ID of the thread 343 // that requested the dump. If the dump is requested as a result of 344 // an exception, exinfo contains exception information, otherwise, 345 // it is NULL. 346 bool WriteMinidumpWithException(DWORD requesting_thread_id, 347 EXCEPTION_POINTERS* exinfo, 348 MDRawAssertionInfo* assertion); 349 350 // This function does the actual writing of a minidump. It is 351 // called on the handler thread. requesting_thread_id is the ID of 352 // the thread that requested the dump, if that information is 353 // meaningful. If the dump is requested as a result of an 354 // exception, exinfo contains exception information, otherwise, it 355 // is NULL. process is the one that will be dumped. If 356 // requesting_thread_id is meaningful and should be added to the 357 // minidump, write_requester_stream is |true|. 358 bool WriteMinidumpWithExceptionForProcess(DWORD requesting_thread_id, 359 EXCEPTION_POINTERS* exinfo, 360 MDRawAssertionInfo* assertion, 361 HANDLE process, 362 bool write_requester_stream); 363 364 // Generates a new ID and stores it in next_minidump_id_, and stores the 365 // path of the next minidump to be written in next_minidump_path_. 366 void UpdateNextID(); 367 368 FilterCallback filter_; 369 MinidumpCallback callback_; 370 void* callback_context_; 371 372 scoped_ptr<CrashGenerationClient> crash_generation_client_; 373 374 // The directory in which a minidump will be written, set by the dump_path 375 // argument to the constructor, or set_dump_path. 376 wstring dump_path_; 377 378 // The basename of the next minidump to be written, without the extension. 379 wstring next_minidump_id_; 380 381 // The full pathname of the next minidump to be written, including the file 382 // extension. 383 wstring next_minidump_path_; 384 385 // Pointers to C-string representations of the above. These are set when 386 // the above wstring versions are set in order to avoid calling c_str during 387 // an exception, as c_str may attempt to allocate heap memory. These 388 // pointers are not owned by the ExceptionHandler object, but their lifetimes 389 // should be equivalent to the lifetimes of the associated wstring, provided 390 // that the wstrings are not altered. 391 const wchar_t* dump_path_c_; 392 const wchar_t* next_minidump_id_c_; 393 const wchar_t* next_minidump_path_c_; 394 395 HMODULE dbghelp_module_; 396 MiniDumpWriteDump_type minidump_write_dump_; 397 MINIDUMP_TYPE dump_type_; 398 399 HMODULE rpcrt4_module_; 400 UuidCreate_type uuid_create_; 401 402 // Tracks the handler types that were installed according to the 403 // handler_types constructor argument. 404 int handler_types_; 405 406 // When installed_handler_ is true, previous_filter_ is the unhandled 407 // exception filter that was set prior to installing ExceptionHandler as 408 // the unhandled exception filter and pointing it to |this|. NULL indicates 409 // that there is no previous unhandled exception filter. 410 LPTOP_LEVEL_EXCEPTION_FILTER previous_filter_; 411 412 #if _MSC_VER >= 1400 // MSVC 2005/8 413 // Beginning in VC 8, the CRT provides an invalid parameter handler that will 414 // be called when some CRT functions are passed invalid parameters. In 415 // earlier CRTs, the same conditions would cause unexpected behavior or 416 // crashes. 417 _invalid_parameter_handler previous_iph_; 418 #endif // _MSC_VER >= 1400 419 420 // The CRT allows you to override the default handler for pure 421 // virtual function calls. 422 _purecall_handler previous_pch_; 423 424 // The exception handler thread. 425 HANDLE handler_thread_; 426 427 // True if the exception handler is being destroyed. 428 // Starting with MSVC 2005, Visual C has stronger guarantees on volatile vars. 429 // It has release semantics on write and acquire semantics on reads. 430 // See the msdn documentation. 431 volatile bool is_shutdown_; 432 433 // The critical section enforcing the requirement that only one exception be 434 // handled by a handler at a time. 435 CRITICAL_SECTION handler_critical_section_; 436 437 // Semaphores used to move exception handling between the exception thread 438 // and the handler thread. handler_start_semaphore_ is signalled by the 439 // exception thread to wake up the handler thread when an exception occurs. 440 // handler_finish_semaphore_ is signalled by the handler thread to wake up 441 // the exception thread when handling is complete. 442 HANDLE handler_start_semaphore_; 443 HANDLE handler_finish_semaphore_; 444 445 // The next 2 fields contain data passed from the requesting thread to 446 // the handler thread. 447 448 // The thread ID of the thread requesting the dump (either the exception 449 // thread or any other thread that called WriteMinidump directly). 450 DWORD requesting_thread_id_; 451 452 // The exception info passed to the exception handler on the exception 453 // thread, if an exception occurred. NULL for user-requested dumps. 454 EXCEPTION_POINTERS* exception_info_; 455 456 // If the handler is invoked due to an assertion, this will contain a 457 // pointer to the assertion information. It is NULL at other times. 458 MDRawAssertionInfo* assertion_; 459 460 // The return value of the handler, passed from the handler thread back to 461 // the requesting thread. 462 bool handler_return_value_; 463 464 // If true, the handler will intercept EXCEPTION_BREAKPOINT and 465 // EXCEPTION_SINGLE_STEP exceptions. Leave this false (the default) 466 // to not interfere with debuggers. 467 bool handle_debug_exceptions_; 468 469 // If true, the handler will consume any EXCEPTION_INVALID_HANDLE exceptions. 470 // Leave this false (the default) to handle these exceptions as normal. 471 bool consume_invalid_handle_exceptions_; 472 473 // Callers can request additional memory regions to be included in 474 // the dump. 475 AppMemoryList app_memory_info_; 476 477 // A stack of ExceptionHandler objects that have installed unhandled 478 // exception filters. This vector is used by HandleException to determine 479 // which ExceptionHandler object to route an exception to. When an 480 // ExceptionHandler is created with install_handler true, it will append 481 // itself to this list. 482 static vector<ExceptionHandler*>* handler_stack_; 483 484 // The index of the ExceptionHandler in handler_stack_ that will handle the 485 // next exception. Note that 0 means the last entry in handler_stack_, 1 486 // means the next-to-last entry, and so on. This is used by HandleException 487 // to support multiple stacked Breakpad handlers. 488 static LONG handler_stack_index_; 489 490 // handler_stack_critical_section_ guards operations on handler_stack_ and 491 // handler_stack_index_. The critical section is initialized by the 492 // first instance of the class and destroyed by the last instance of it. 493 static CRITICAL_SECTION handler_stack_critical_section_; 494 495 // The number of instances of this class. 496 static volatile LONG instance_count_; 497 498 bool include_context_heap_; 499 500 // disallow copy ctor and operator= 501 explicit ExceptionHandler(const ExceptionHandler &); 502 void operator=(const ExceptionHandler &); 503 }; 504 505 } // namespace google_breakpad 506 507 #pragma warning(pop) 508 509 #endif // CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__ 510