Planeshift

exception_handler.h

Go to the documentation of this file.
00001 // Copyright (c) 2006, Google Inc.
00002 // All rights reserved.
00003 //
00004 // Redistribution and use in source and binary forms, with or without
00005 // modification, are permitted provided that the following conditions are
00006 // met:
00007 //
00008 //     * Redistributions of source code must retain the above copyright
00009 // notice, this list of conditions and the following disclaimer.
00010 //     * Redistributions in binary form must reproduce the above
00011 // copyright notice, this list of conditions and the following disclaimer
00012 // in the documentation and/or other materials provided with the
00013 // distribution.
00014 //     * Neither the name of Google Inc. nor the names of its
00015 // contributors may be used to endorse or promote products derived from
00016 // this software without specific prior written permission.
00017 //
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
00019 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00020 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
00021 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
00022 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
00023 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00024 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
00025 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
00026 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
00027 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
00028 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 
00030 // ExceptionHandler can write a minidump file when an exception occurs,
00031 // or when WriteMinidump() is called explicitly by your program.
00032 //
00033 // To have the exception handler write minidumps when an uncaught exception
00034 // (crash) occurs, you should create an instance early in the execution
00035 // of your program, and keep it around for the entire time you want to
00036 // have crash handling active (typically, until shutdown).
00037 //
00038 // If you want to write minidumps without installing the exception handler,
00039 // you can create an ExceptionHandler with install_handler set to false,
00040 // then call WriteMinidump.  You can also use this technique if you want to
00041 // use different minidump callbacks for different call sites.
00042 //
00043 // In either case, a callback function is called when a minidump is written,
00044 // which receives the unqiue id of the minidump.  The caller can use this
00045 // id to collect and write additional application state, and to launch an
00046 // external crash-reporting application.
00047 //
00048 // It is important that creation and destruction of ExceptionHandler objects
00049 // be nested cleanly, when using install_handler = true.
00050 // Avoid the following pattern:
00051 //   ExceptionHandler *e = new ExceptionHandler(...);
00052 //   ExceptionHandler *f = new ExceptionHandler(...);
00053 //   delete e;
00054 // This will put the exception filter stack into an inconsistent state.
00055 
00056 #ifndef CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__
00057 #define CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__
00058 
00059 #include <stdlib.h>
00060 #include <Windows.h>
00061 #include <DbgHelp.h>
00062 #include <rpc.h>
00063 
00064 #pragma warning(push)
00065 // Disable exception handler warnings.
00066 #pragma warning(disable:4530)
00067 
00068 #include <list>
00069 #include <string>
00070 #include <vector>
00071 
00072 #include "client/windows/common/ipc_protocol.h"
00073 #include "client/windows/crash_generation/crash_generation_client.h"
00074 #include "common/scoped_ptr.h"
00075 #include "google_breakpad/common/minidump_format.h"
00076 
00077 namespace google_breakpad {
00078 
00079 using std::vector;
00080 using std::wstring;
00081 
00082 // These entries store a list of memory regions that the client wants included
00083 // in the minidump.
00084 struct AppMemory {
00085   ULONG64 ptr;
00086   ULONG length;
00087 
00088   bool operator==(const struct AppMemory& other) const {
00089     return ptr == other.ptr;
00090   }
00091 
00092   bool operator==(const void* other) const {
00093     return ptr == reinterpret_cast<ULONG64>(other);
00094   }
00095 };
00096 typedef std::list<AppMemory> AppMemoryList;
00097 
00098 class ExceptionHandler {
00099  public:
00100   // A callback function to run before Breakpad performs any substantial
00101   // processing of an exception.  A FilterCallback is called before writing
00102   // a minidump.  context is the parameter supplied by the user as
00103   // callback_context when the handler was created.  exinfo points to the
00104   // exception record, if any; assertion points to assertion information,
00105   // if any.
00106   //
00107   // If a FilterCallback returns true, Breakpad will continue processing,
00108   // attempting to write a minidump.  If a FilterCallback returns false,
00109   // Breakpad will immediately report the exception as unhandled without
00110   // writing a minidump, allowing another handler the opportunity to handle it.
00111   typedef bool (*FilterCallback)(void* context, EXCEPTION_POINTERS* exinfo,
00112                                  MDRawAssertionInfo* assertion);
00113 
00114   // A callback function to run after the minidump has been written.
00115   // minidump_id is a unique id for the dump, so the minidump
00116   // file is <dump_path><minidump_id>.dmp.  context is the parameter supplied
00117   // by the user as callback_context when the handler was created.  exinfo
00118   // points to the exception record, or NULL if no exception occurred.
00119   // succeeded indicates whether a minidump file was successfully written.
00120   // assertion points to information about an assertion if the handler was
00121   // invoked by an assertion.
00122   //
00123   // If an exception occurred and the callback returns true, Breakpad will treat
00124   // the exception as fully-handled, suppressing any other handlers from being
00125   // notified of the exception.  If the callback returns false, Breakpad will
00126   // treat the exception as unhandled, and allow another handler to handle it.
00127   // If there are no other handlers, Breakpad will report the exception to the
00128   // system as unhandled, allowing a debugger or native crash dialog the
00129   // opportunity to handle the exception.  Most callback implementations
00130   // should normally return the value of |succeeded|, or when they wish to
00131   // not report an exception of handled, false.  Callbacks will rarely want to
00132   // return true directly (unless |succeeded| is true).
00133   //
00134   // For out-of-process dump generation, dump path and minidump ID will always
00135   // be NULL. In case of out-of-process dump generation, the dump path and
00136   // minidump id are controlled by the server process and are not communicated
00137   // back to the crashing process.
00138   typedef bool (*MinidumpCallback)(const wchar_t* dump_path,
00139                                    const wchar_t* minidump_id,
00140                                    void* context,
00141                                    EXCEPTION_POINTERS* exinfo,
00142                                    MDRawAssertionInfo* assertion,
00143                                    bool succeeded);
00144 
00145   // HandlerType specifies which types of handlers should be installed, if
00146   // any.  Use HANDLER_NONE for an ExceptionHandler that remains idle,
00147   // without catching any failures on its own.  This type of handler may
00148   // still be triggered by calling WriteMinidump.  Otherwise, use a
00149   // combination of the other HANDLER_ values, or HANDLER_ALL to install
00150   // all handlers.
00151   enum HandlerType {
00152     HANDLER_NONE = 0,
00153     HANDLER_EXCEPTION = 1 << 0,          // SetUnhandledExceptionFilter
00154     HANDLER_INVALID_PARAMETER = 1 << 1,  // _set_invalid_parameter_handler
00155     HANDLER_PURECALL = 1 << 2,           // _set_purecall_handler
00156     HANDLER_ALL = HANDLER_EXCEPTION |
00157                   HANDLER_INVALID_PARAMETER |
00158                   HANDLER_PURECALL
00159   };
00160 
00161   // Creates a new ExceptionHandler instance to handle writing minidumps.
00162   // Before writing a minidump, the optional filter callback will be called.
00163   // Its return value determines whether or not Breakpad should write a
00164   // minidump.  Minidump files will be written to dump_path, and the optional
00165   // callback is called after writing the dump file, as described above.
00166   // handler_types specifies the types of handlers that should be installed.
00167   ExceptionHandler(const wstring& dump_path,
00168                    FilterCallback filter,
00169                    MinidumpCallback callback,
00170                    void* callback_context,
00171                    int handler_types);
00172 
00173   // Creates a new ExceptionHandler instance that can attempt to perform
00174   // out-of-process dump generation if pipe_name is not NULL. If pipe_name is
00175   // NULL, or if out-of-process dump generation registration step fails,
00176   // in-process dump generation will be used. This also allows specifying
00177   // the dump type to generate.
00178   ExceptionHandler(const wstring& dump_path,
00179                    FilterCallback filter,
00180                    MinidumpCallback callback,
00181                    void* callback_context,
00182                    int handler_types,
00183                    MINIDUMP_TYPE dump_type,
00184                    const wchar_t* pipe_name,
00185                    const CustomClientInfo* custom_info);
00186 
00187   // As above, creates a new ExceptionHandler instance to perform
00188   // out-of-process dump generation if the given pipe_handle is not NULL.
00189   ExceptionHandler(const wstring& dump_path,
00190                    FilterCallback filter,
00191                    MinidumpCallback callback,
00192                    void* callback_context,
00193                    int handler_types,
00194                    MINIDUMP_TYPE dump_type,
00195                    HANDLE pipe_handle,
00196                    const CustomClientInfo* custom_info);
00197 
00198   // ExceptionHandler that ENSURES out-of-process dump generation.  Expects a
00199   // crash generation client that is already registered with a crash generation
00200   // server.  Takes ownership of the passed-in crash_generation_client.
00201   //
00202   // Usage example:
00203   //   crash_generation_client = new CrashGenerationClient(..);
00204   //   if (crash_generation_client->Register()) {
00205   //     // Registration with the crash generation server succeeded.
00206   //     // Out-of-process dump generation is guaranteed.
00207   //     g_handler = new ExceptionHandler(.., crash_generation_client, ..);
00208   //     return true;
00209   //   }
00210   ExceptionHandler(const wstring& dump_path,
00211                    FilterCallback filter,
00212                    MinidumpCallback callback,
00213                    void* callback_context,
00214                    int handler_types,
00215                    CrashGenerationClient* crash_generation_client);
00216 
00217   ~ExceptionHandler();
00218 
00219   // Get and set the minidump path.
00220   wstring dump_path() const { return dump_path_; }
00221   void set_dump_path(const wstring &dump_path) {
00222     dump_path_ = dump_path;
00223     dump_path_c_ = dump_path_.c_str();
00224     UpdateNextID();  // Necessary to put dump_path_ in next_minidump_path_.
00225   }
00226 
00227   // Requests that a previously reported crash be uploaded.
00228   bool RequestUpload(DWORD crash_id);
00229 
00230   // Writes a minidump immediately.  This can be used to capture the
00231   // execution state independently of a crash.  Returns true on success.
00232   bool WriteMinidump();
00233 
00234   // Writes a minidump immediately, with the user-supplied exception
00235   // information.
00236   bool WriteMinidumpForException(EXCEPTION_POINTERS* exinfo);
00237 
00238   // Convenience form of WriteMinidump which does not require an
00239   // ExceptionHandler instance.
00240   static bool WriteMinidump(const wstring &dump_path,
00241                             MinidumpCallback callback, void* callback_context);
00242 
00243   // Write a minidump of |child| immediately.  This can be used to
00244   // capture the execution state of |child| independently of a crash.
00245   // Pass a meaningful |child_blamed_thread| to make that thread in
00246   // the child process the one from which a crash signature is
00247   // extracted.
00248   static bool WriteMinidumpForChild(HANDLE child,
00249                                     DWORD child_blamed_thread,
00250                                     const wstring& dump_path,
00251                                     MinidumpCallback callback,
00252                                     void* callback_context);
00253 
00254   // Get the thread ID of the thread requesting the dump (either the exception
00255   // thread or any other thread that called WriteMinidump directly).  This
00256   // may be useful if you want to include additional thread state in your
00257   // dumps.
00258   DWORD get_requesting_thread_id() const { return requesting_thread_id_; }
00259 
00260   // Controls behavior of EXCEPTION_BREAKPOINT and EXCEPTION_SINGLE_STEP.
00261   bool get_handle_debug_exceptions() const { return handle_debug_exceptions_; }
00262   void set_handle_debug_exceptions(bool handle_debug_exceptions) {
00263     handle_debug_exceptions_ = handle_debug_exceptions;
00264   }
00265 
00266   // Returns whether out-of-process dump generation is used or not.
00267   bool IsOutOfProcess() const { return crash_generation_client_.get() != NULL; }
00268 
00269   // Calling RegisterAppMemory(p, len) causes len bytes starting
00270   // at address p to be copied to the minidump when a crash happens.
00271   void RegisterAppMemory(void* ptr, size_t length);
00272   void UnregisterAppMemory(void* ptr);
00273 
00274  private:
00275   friend class AutoExceptionHandler;
00276 
00277   // Initializes the instance with given values.
00278   void Initialize(const wstring& dump_path,
00279                   FilterCallback filter,
00280                   MinidumpCallback callback,
00281                   void* callback_context,
00282                   int handler_types,
00283                   MINIDUMP_TYPE dump_type,
00284                   const wchar_t* pipe_name,
00285                   HANDLE pipe_handle,
00286                   CrashGenerationClient* crash_generation_client,
00287                   const CustomClientInfo* custom_info);
00288 
00289   // Function pointer type for MiniDumpWriteDump, which is looked up
00290   // dynamically.
00291   typedef BOOL (WINAPI *MiniDumpWriteDump_type)(
00292       HANDLE hProcess,
00293       DWORD dwPid,
00294       HANDLE hFile,
00295       MINIDUMP_TYPE DumpType,
00296       CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
00297       CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
00298       CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
00299 
00300   // Function pointer type for UuidCreate, which is looked up dynamically.
00301   typedef RPC_STATUS (RPC_ENTRY *UuidCreate_type)(UUID* Uuid);
00302 
00303   // Runs the main loop for the exception handler thread.
00304   static DWORD WINAPI ExceptionHandlerThreadMain(void* lpParameter);
00305 
00306   // Called on the exception thread when an unhandled exception occurs.
00307   // Signals the exception handler thread to handle the exception.
00308   static LONG WINAPI HandleException(EXCEPTION_POINTERS* exinfo);
00309 
00310 #if _MSC_VER >= 1400  // MSVC 2005/8
00311   // This function will be called by some CRT functions when they detect
00312   // that they were passed an invalid parameter.  Note that in _DEBUG builds,
00313   // the CRT may display an assertion dialog before calling this function,
00314   // and the function will not be called unless the assertion dialog is
00315   // dismissed by clicking "Ignore."
00316   static void HandleInvalidParameter(const wchar_t* expression,
00317                                      const wchar_t* function,
00318                                      const wchar_t* file,
00319                                      unsigned int line,
00320                                      uintptr_t reserved);
00321 #endif  // _MSC_VER >= 1400
00322 
00323   // This function will be called by the CRT when a pure virtual
00324   // function is called.
00325   static void HandlePureVirtualCall();
00326 
00327   // This is called on the exception thread or on another thread that
00328   // the user wishes to produce a dump from.  It calls
00329   // WriteMinidumpWithException on the handler thread, avoiding stack
00330   // overflows and inconsistent dumps due to writing the dump from
00331   // the exception thread.  If the dump is requested as a result of an
00332   // exception, exinfo contains exception information, otherwise, it
00333   // is NULL.  If the dump is requested as a result of an assertion
00334   // (such as an invalid parameter being passed to a CRT function),
00335   // assertion contains data about the assertion, otherwise, it is NULL.
00336   bool WriteMinidumpOnHandlerThread(EXCEPTION_POINTERS* exinfo,
00337                                     MDRawAssertionInfo* assertion);
00338 
00339   // This function is called on the handler thread.  It calls into
00340   // WriteMinidumpWithExceptionForProcess() with a handle to the
00341   // current process.  requesting_thread_id is the ID of the thread
00342   // that requested the dump.  If the dump is requested as a result of
00343   // an exception, exinfo contains exception information, otherwise,
00344   // it is NULL.
00345   bool WriteMinidumpWithException(DWORD requesting_thread_id,
00346                                   EXCEPTION_POINTERS* exinfo,
00347                                   MDRawAssertionInfo* assertion);
00348 
00349   // This function is used as a callback when calling MinidumpWriteDump,
00350   // in order to add additional memory regions to the dump.
00351   static BOOL CALLBACK MinidumpWriteDumpCallback(
00352       PVOID context,
00353       const PMINIDUMP_CALLBACK_INPUT callback_input,
00354       PMINIDUMP_CALLBACK_OUTPUT callback_output);
00355 
00356   // This function does the actual writing of a minidump.  It is
00357   // called on the handler thread.  requesting_thread_id is the ID of
00358   // the thread that requested the dump, if that information is
00359   // meaningful.  If the dump is requested as a result of an
00360   // exception, exinfo contains exception information, otherwise, it
00361   // is NULL.  process is the one that will be dumped.  If
00362   // requesting_thread_id is meaningful and should be added to the
00363   // minidump, write_requester_stream is |true|.
00364   bool WriteMinidumpWithExceptionForProcess(DWORD requesting_thread_id,
00365                                             EXCEPTION_POINTERS* exinfo,
00366                                             MDRawAssertionInfo* assertion,
00367                                             HANDLE process,
00368                                             bool write_requester_stream);
00369 
00370   // Generates a new ID and stores it in next_minidump_id_, and stores the
00371   // path of the next minidump to be written in next_minidump_path_.
00372   void UpdateNextID();
00373 
00374   FilterCallback filter_;
00375   MinidumpCallback callback_;
00376   void* callback_context_;
00377 
00378   scoped_ptr<CrashGenerationClient> crash_generation_client_;
00379 
00380   // The directory in which a minidump will be written, set by the dump_path
00381   // argument to the constructor, or set_dump_path.
00382   wstring dump_path_;
00383 
00384   // The basename of the next minidump to be written, without the extension.
00385   wstring next_minidump_id_;
00386 
00387   // The full pathname of the next minidump to be written, including the file
00388   // extension.
00389   wstring next_minidump_path_;
00390 
00391   // Pointers to C-string representations of the above.  These are set when
00392   // the above wstring versions are set in order to avoid calling c_str during
00393   // an exception, as c_str may attempt to allocate heap memory.  These
00394   // pointers are not owned by the ExceptionHandler object, but their lifetimes
00395   // should be equivalent to the lifetimes of the associated wstring, provided
00396   // that the wstrings are not altered.
00397   const wchar_t* dump_path_c_;
00398   const wchar_t* next_minidump_id_c_;
00399   const wchar_t* next_minidump_path_c_;
00400 
00401   HMODULE dbghelp_module_;
00402   MiniDumpWriteDump_type minidump_write_dump_;
00403   MINIDUMP_TYPE dump_type_;
00404 
00405   HMODULE rpcrt4_module_;
00406   UuidCreate_type uuid_create_;
00407 
00408   // Tracks the handler types that were installed according to the
00409   // handler_types constructor argument.
00410   int handler_types_;
00411 
00412   // When installed_handler_ is true, previous_filter_ is the unhandled
00413   // exception filter that was set prior to installing ExceptionHandler as
00414   // the unhandled exception filter and pointing it to |this|.  NULL indicates
00415   // that there is no previous unhandled exception filter.
00416   LPTOP_LEVEL_EXCEPTION_FILTER previous_filter_;
00417 
00418 #if _MSC_VER >= 1400  // MSVC 2005/8
00419   // Beginning in VC 8, the CRT provides an invalid parameter handler that will
00420   // be called when some CRT functions are passed invalid parameters.  In
00421   // earlier CRTs, the same conditions would cause unexpected behavior or
00422   // crashes.
00423   _invalid_parameter_handler previous_iph_;
00424 #endif  // _MSC_VER >= 1400
00425 
00426   // The CRT allows you to override the default handler for pure
00427   // virtual function calls.
00428   _purecall_handler previous_pch_;
00429 
00430   // The exception handler thread.
00431   HANDLE handler_thread_;
00432 
00433   // True if the exception handler is being destroyed.
00434   // Starting with MSVC 2005, Visual C has stronger guarantees on volatile vars.
00435   // It has release semantics on write and acquire semantics on reads.
00436   // See the msdn documentation.
00437   volatile bool is_shutdown_;
00438 
00439   // The critical section enforcing the requirement that only one exception be
00440   // handled by a handler at a time.
00441   CRITICAL_SECTION handler_critical_section_;
00442 
00443   // Semaphores used to move exception handling between the exception thread
00444   // and the handler thread.  handler_start_semaphore_ is signalled by the
00445   // exception thread to wake up the handler thread when an exception occurs.
00446   // handler_finish_semaphore_ is signalled by the handler thread to wake up
00447   // the exception thread when handling is complete.
00448   HANDLE handler_start_semaphore_;
00449   HANDLE handler_finish_semaphore_;
00450 
00451   // The next 2 fields contain data passed from the requesting thread to
00452   // the handler thread.
00453 
00454   // The thread ID of the thread requesting the dump (either the exception
00455   // thread or any other thread that called WriteMinidump directly).
00456   DWORD requesting_thread_id_;
00457 
00458   // The exception info passed to the exception handler on the exception
00459   // thread, if an exception occurred.  NULL for user-requested dumps.
00460   EXCEPTION_POINTERS* exception_info_;
00461 
00462   // If the handler is invoked due to an assertion, this will contain a
00463   // pointer to the assertion information.  It is NULL at other times.
00464   MDRawAssertionInfo* assertion_;
00465 
00466   // The return value of the handler, passed from the handler thread back to
00467   // the requesting thread.
00468   bool handler_return_value_;
00469 
00470   // If true, the handler will intercept EXCEPTION_BREAKPOINT and
00471   // EXCEPTION_SINGLE_STEP exceptions.  Leave this false (the default)
00472   // to not interfere with debuggers.
00473   bool handle_debug_exceptions_;
00474 
00475   // Callers can request additional memory regions to be included in
00476   // the dump.
00477   AppMemoryList app_memory_info_;
00478 
00479   // A stack of ExceptionHandler objects that have installed unhandled
00480   // exception filters.  This vector is used by HandleException to determine
00481   // which ExceptionHandler object to route an exception to.  When an
00482   // ExceptionHandler is created with install_handler true, it will append
00483   // itself to this list.
00484   static vector<ExceptionHandler*>* handler_stack_;
00485 
00486   // The index of the ExceptionHandler in handler_stack_ that will handle the
00487   // next exception.  Note that 0 means the last entry in handler_stack_, 1
00488   // means the next-to-last entry, and so on.  This is used by HandleException
00489   // to support multiple stacked Breakpad handlers.
00490   static LONG handler_stack_index_;
00491 
00492   // handler_stack_critical_section_ guards operations on handler_stack_ and
00493   // handler_stack_index_. The critical section is initialized by the
00494   // first instance of the class and destroyed by the last instance of it.
00495   static CRITICAL_SECTION handler_stack_critical_section_;
00496 
00497   // The number of instances of this class.
00498   static volatile LONG instance_count_;
00499 
00500   // disallow copy ctor and operator=
00501   explicit ExceptionHandler(const ExceptionHandler &);
00502   void operator=(const ExceptionHandler &);
00503 };
00504 
00505 }  // namespace google_breakpad
00506 
00507 #pragma warning(pop)
00508 
00509 #endif  // CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__