crashrpt
CrashHandler.h
1 /*************************************************************************************
2 This file is a part of CrashRpt library.
3 Copyright (c) 2003-2013 The CrashRpt project authors. All Rights Reserved.
4 
5 Use of this source code is governed by a BSD-style license
6 that can be found in the License.txt file in the root of the source
7 tree. All contributing project authors may
8 be found in the Authors.txt file in the root of the source tree.
9 ***************************************************************************************/
10 
11 // File: CrashHandler.h
12 // Description: Exception handling functionality.
13 // Authors: mikecarruth, zexspectrum
14 // Date: 2009
15 
16 #pragma once
17 #include "stdafx.h"
18 #include "CrashRpt.h"
19 #include "Utility.h"
20 #include "CritSec.h"
21 #include "SharedMem.h"
22 #include "Prefastdef.h"
23 
24 /* This structure contains pointer to the exception handlers for a thread.*/
26 {
28  {
29  m_prevTerm = NULL;
30  m_prevUnexp = NULL;
31  m_prevSigFPE = NULL;
32  m_prevSigILL = NULL;
33  m_prevSigSEGV = NULL;
34  }
35 
36  terminate_handler m_prevTerm; // Previous terminate handler
37  unexpected_handler m_prevUnexp; // Previous unexpected handler
38  void (__cdecl *m_prevSigFPE)(int); // Previous FPE handler
39  void (__cdecl *m_prevSigILL)(int); // Previous SIGILL handler
40  void (__cdecl *m_prevSigSEGV)(int); // Previous illegal storage access handler
41 };
42 
43 // Sets the last error message (for the caller thread).
44 int crSetErrorMsg(PTSTR pszErrorMsg);
45 
46 // This structure describes a file item (a file included into crash report).
47 struct FileItem
48 {
49  FileItem()
50  {
51  m_bMakeCopy = FALSE;
52  m_bAllowDelete = FALSE;
53  }
54 
55  CString m_sSrcFilePath; // Path to the original file.
56  CString m_sDstFileName; // Destination file name (as seen in ZIP archive).
57  CString m_sDescription; // Description.
58  BOOL m_bMakeCopy; // Should we make a copy of this file on crash?
59  // If set, the file will be copied to crash report folder and that copy will be included into crash report,
60  // otherwise the file will be included from its original location (not guaranteing that file is the same it was
61  // at the moment of crash).
62  BOOL m_bAllowDelete; // Whether to allow user deleting the file from context menu of Error Report Details dialog.
63 };
64 
65 // Contains information about a registry key included into a crash report.
66 struct RegKeyInfo
67 {
68  RegKeyInfo()
69  {
70  m_bAllowDelete = false;
71  }
72 
73  CString m_sDstFileName; // Destination file name (as seen in ZIP archive).
74  bool m_bAllowDelete; // Whether to allow user deleting the file from context menu of Error Report Details dialog.
75 };
76 
77 // This class is used to set exception handlers, catch exceptions
78 // and launch crash report sender process.
80 {
81 public:
82 
83  // Default constructor.
84  CCrashHandler();
85 
86  // Destructor.
87  virtual ~CCrashHandler();
88 
89  // Initializes the crash handler object.
90  int Init(
91  __in_opt LPCTSTR lpcszAppName = NULL,
92  __in_opt LPCTSTR lpcszAppVersion = NULL,
93  __in_opt LPCTSTR lpcszCrashSenderPath = NULL,
94  __in_opt LPGETLOGFILE lpfnCallback = NULL,
95  __in_opt LPCTSTR lpcszTo = NULL,
96  __in_opt LPCTSTR lpcszSubject = NULL,
97  __in_opt LPCTSTR lpcszUrl = NULL,
98  __in_opt UINT (*puPriorities)[5] = NULL,
99  DWORD dwFlags = 0,
100  __in_opt LPCTSTR lpcszPrivacyPolicyURL = NULL,
101  __in_opt LPCTSTR lpcszDebugHelpDLLPath = NULL,
102  MINIDUMP_TYPE MiniDumpType = MiniDumpNormal,
103  __in_opt LPCTSTR lpcszErrorReportSaveDir = NULL,
104  __in_opt LPCTSTR lpcszRestartCmdLine = NULL,
105  __in_opt LPCTSTR lpcszLangFilePath = NULL,
106  __in_opt LPCTSTR lpcszEmailText = NULL,
107  __in_opt LPCTSTR lpcszSmtpProxy = NULL,
108  __in_opt LPCTSTR lpcszCustomSenderIcon = NULL,
109  __in_opt LPCTSTR lpcszSmtpLogin = NULL,
110  __in_opt LPCTSTR lpcszSmtpPassword = NULL,
111  __in_opt int nRestartTimeout = 0);
112 
113  // Returns TRUE if object was initialized.
114  BOOL IsInitialized();
115 
116  // Frees all used resources.
117  int Destroy();
118 
119  // Sets crash callback function (wide-char version).
120  int SetCrashCallbackW(PFNCRASHCALLBACKW pfnCallback, LPVOID pUserParam);
121 
122  // Sets crash callback function (multi-byte version).
123  int SetCrashCallbackA(PFNCRASHCALLBACKA pfnCallback, LPVOID pUserParam);
124 
125  // Adds a file to the crash report.
126  int AddFile(__in_z LPCTSTR lpFile, __in_opt LPCTSTR lpDestFile,
127  __in_opt LPCTSTR lpDesc, DWORD dwFlags);
128 
129  // Adds a named text property to the report.
130  int AddProperty(CString sPropName, CString sPropValue);
131 
132  // Adds desktop screenshot of crash into error report.
133  int AddScreenshot(DWORD dwFlags, int nJpegQuality);
134 
135  // Starts a video recording of desktop state;
136  // if crash will happen sometime, the video will be included into crash report.
137  int AddVideo(DWORD dwFlags, int nDuration, int nFrameInterval, SIZE* pDesiredFrameSize, HWND hWndParent);
138 
139  // Adds a registry key to crash report.
140  int AddRegKey(__in_z LPCTSTR szRegKey, __in_z LPCTSTR szDstFileName, DWORD dwFlags);
141 
142  // Generates error report
143  int GenerateErrorReport(__in_opt PCR_EXCEPTION_INFO pExceptionInfo = NULL);
144 
145  // Sets/unsets exception handlers for the entire process
146  int SetProcessExceptionHandlers(DWORD dwFlags);
147  int UnSetProcessExceptionHandlers();
148 
149  // Sets/unsets exception handlers for the caller thread
150  int SetThreadExceptionHandlers(DWORD dwFlags);
151  int UnSetThreadExceptionHandlers();
152 
153  // Returns flags.
154  DWORD GetFlags();
155 
156  // Returns the crash handler object (singleton).
157  static CCrashHandler* GetCurrentProcessCrashHandler();
158 
159  // Releases the singleton of this crash handler object.
160  static void ReleaseCurrentProcessCrashHandler();
161 
162  /* Exception handler functions. */
163 
164  // Structured exception handler (SEH handler)
165  static LONG WINAPI SehHandler(__in PEXCEPTION_POINTERS pExceptionPtrs);
166  static DWORD WINAPI StackOverflowThreadFunction(LPVOID threadParameter);
167  // C++ terminate handler
168  static void __cdecl TerminateHandler();
169  // C++ unexpected handler
170  static void __cdecl UnexpectedHandler();
171 
172 #if _MSC_VER>=1300
173  // C++ pure virtual call handler
174  static void __cdecl PureCallHandler();
175 #endif
176 
177 #if _MSC_VER>=1300 && _MSC_VER<1400
178  // Buffer overrun handler (deprecated in newest versions of Visual C++).
179  static void __cdecl SecurityHandler(int code, void *x);
180 #endif
181 
182 #if _MSC_VER>=1400
183  // C++ Invalid parameter handler.
184  static void __cdecl InvalidParameterHandler(const wchar_t* expression,
185  const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved);
186 #endif
187 
188 #if _MSC_VER>=1300
189  // C++ new operator fault (memory exhaustion) handler
190  static int __cdecl NewHandler(size_t);
191 #endif
192 
193  // Signal handlers
194  static void SigabrtHandler(int);
195  static void SigfpeHandler(int /*code*/, int subcode);
196  static void SigintHandler(int);
197  static void SigillHandler(int);
198  static void SigsegvHandler(int);
199  static void SigtermHandler(int);
200 
201  /* Crash report generation methods */
202 
203  // Collects current state of CPU registers.
204  void GetExceptionPointers(
205  DWORD dwExceptionCode,
206  EXCEPTION_POINTERS* pExceptionPointers);
207 
208  // Packs crash description into shared memory.
209  CRASH_DESCRIPTION* PackCrashInfoIntoSharedMem(__in CSharedMem* pSharedMem, BOOL bTempMem);
210  // Packs a string.
211  DWORD PackString(CString str);
212  // Packs a file item.
213  DWORD PackFileItem(FileItem& fi);
214  // Packs a custom user property.
215  DWORD PackProperty(CString sName, CString sValue);
216  // Packs a registry key.
217  DWORD PackRegKey(CString sKeyName, RegKeyInfo& rki);
218 
219  // Launches the CrashSender.exe process.
220  int LaunchCrashSender(
221  LPCTSTR szCmdLineParams,
222  BOOL bWait,
223  __out_opt HANDLE* phProcess);
224 
225  // Returns TRUE if CrashSender.exe process is still alive.
226  BOOL IsSenderProcessAlive();
227 
228  // Sets internal pointers to exception handlers to NULL.
229  void InitPrevExceptionHandlerPointers();
230 
231  // Initializes several internal fields before each crash.
232  int PerCrashInit();
233 
234  // Pack configuration info into shared memory.
235  void Repack();
236 
237  // Update in shared memory
238  void UpdateEmailSubject(LPCWSTR pszSubject);
239 
240  // Acqure exclusive access to this crash handler.
241  void CrashLock(BOOL bLock);
242 
243  // Calls the crash callback function (if the callback function was specified by user).
244  int CallBack(int nStage, CR_EXCEPTION_INFO* pExInfo);
245 
246  /* Private member variables. */
247 
248  // Singleton of the CCrashHandler class.
249  static CCrashHandler* m_pProcessCrashHandler;
250 
251  // Previous SEH exception filter.
252  LPTOP_LEVEL_EXCEPTION_FILTER m_oldSehHandler;
253 
254 #if _MSC_VER>=1300
255  _purecall_handler m_prevPurec; // Previous pure virtual call exception filter.
256  _PNH m_prevNewHandler; // Previous new operator exception filter.
257 #endif
258 
259 #if _MSC_VER>=1400
260  _invalid_parameter_handler m_prevInvpar; // Previous invalid parameter exception filter.
261 #endif
262 
263 #if _MSC_VER>=1300 && _MSC_VER<1400
264  _secerr_handler_func m_prevSec; // Previous security exception filter.
265 #endif
266 
267  void (__cdecl *m_prevSigABRT)(int); // Previous SIGABRT handler.
268  void (__cdecl *m_prevSigINT)(int); // Previous SIGINT handler.
269  void (__cdecl *m_prevSigTERM)(int); // Previous SIGTERM handler.
270 
271  // List of exception handlers installed for worker threads of this process.
272  std::map<DWORD, ThreadExceptionHandlers> m_ThreadExceptionHandlers;
273  CCritSec m_csThreadExceptionHandlers; // Synchronization lock for m_ThreadExceptionHandlers.
274 
275  BOOL m_bInitialized; // Flag telling if this object was initialized.
276  CString m_sAppName; // Application name.
277  CString m_sAppVersion; // Application version.
278  CString m_sCrashGUID; // Crash GUID.
279  CString m_sImageName; // Process image name.
280  DWORD m_dwFlags; // Flags.
281  MINIDUMP_TYPE m_MinidumpType; // Minidump type.
282  CString m_sRestartCmdLine; // App restart command line.
283  int m_nRestartTimeout; // Restart timeout.
284  CString m_sUrl; // Url to use when sending error report over HTTP.
285  CString m_sEmailTo; // E-mail recipient.
286  int m_nSmtpPort; // SMTP port.
287  CString m_sSmtpProxyServer; // SMTP proxy.
288  int m_nSmtpProxyPort; // SMTP proxy port.
289  CString m_sSmtpLogin; // SMTP login.
290  CString m_sSmtpPassword; // SMTP password.
291  CString m_sEmailSubject; // E-mail subject.
292  CString m_sEmailText; // E-mail text.
293  UINT m_uPriorities[3]; // Delivery priorities.
294  CString m_sPrivacyPolicyURL; // Privacy policy URL.
295  CString m_sPathToCrashSender; // Path to CrashSender.exe
296  CString m_sLangFileName; // Language file.
297  CString m_sPathToDebugHelpDll; // Path to dbghelp.dll.
298  CString m_sUnsentCrashReportsFolder; // Path to the folder where to save error reports.
299  LPGETLOGFILE m_lpfnCallback; // Client crash callback (deprecated).
300  BOOL m_bAddScreenshot; // Should we add screenshot?
301  DWORD m_dwScreenshotFlags; // Screenshot flags.
302  int m_nJpegQuality; // Quality of JPEG screenshot images.
303  BOOL m_bAddVideo; // Wether to add video recording.
304  DWORD m_dwVideoFlags; // Flags for video recording.
305  int m_nVideoDuration; // Video duration.
306  int m_nVideoFrameInterval; // Video frame interval.
307  SIZE m_DesiredFrameSize; // Video frame size.
308  HWND m_hWndVideoParent; // Parent window for video recording dialog.
309  CString m_sCustomSenderIcon; // Resource name that can be used as custom Error Report dialog icon.
310  std::map<CString, FileItem> m_files; // File items to include.
311  std::map<CString, CString> m_props; // User-defined properties to include.
312  std::map<CString, RegKeyInfo> m_RegKeys; // Registry keys to dump.
313  CCritSec m_csCrashLock; // Critical section used to synchronize thread access to this object.
314  HANDLE m_hEvent; // Event used to synchronize CrashRpt.dll with CrashSender.exe.
315  HANDLE m_hEvent2; // Another event used to synchronize CrashRpt.dll with CrashSender.exe.
316  CSharedMem m_SharedMem; // Shared memory.
317  CRASH_DESCRIPTION* m_pCrashDesc; // Pointer to crash description shared mem view.
318  CSharedMem* m_pTmpSharedMem; // Used temporarily
319  CRASH_DESCRIPTION* m_pTmpCrashDesc; // Used temporarily
320  HANDLE m_hSenderProcess; // Handle to CrashSender.exe process.
321  PFNCRASHCALLBACKW m_pfnCallback2W; // Client crash callback.
322  PFNCRASHCALLBACKA m_pfnCallback2A; // Client crash callback.
323  LPVOID m_pCallbackParam; // User-specified argument for callback function.
324  std::string m_sErrorReportDirA; // Error report directory name (multi-byte).
325  std::wstring m_sErrorReportDirW; // Error report directory name (wide-char).
326  int m_nCallbackRetCode; // Return code of the callback function.
327  BOOL m_bContinueExecution; // Whether to terminate process (the default) or to continue execution after crash.
328 };
329 
330 
Defines the interface for the CrashRpt.DLL.
Definition: SharedMem.h:127
BOOL(CALLBACK * LPGETLOGFILE)(__reserved LPVOID lpvState)
Client crash callback function prototype.
Definition: CrashRpt.h:93
Definition: CritSec.h:23
SAL macro switches.
int(CALLBACK * PFNCRASHCALLBACKW)(CR_CRASH_CALLBACK_INFOW *pInfo)
Client crash callback function prototype.
Definition: CrashRpt.h:382
Definition: CrashHandler.h:66
Definition: CrashHandler.h:25
Definition: CrashHandler.h:79
This structure contains information about the crash.
Definition: CrashRpt.h:179
Definition: CrashHandler.h:47
Definition: inftrees.h:24
int(CALLBACK * PFNCRASHCALLBACKA)(CR_CRASH_CALLBACK_INFOA *pInfo)
Client crash callback function prototype.
Definition: CrashRpt.h:387
Definition: SharedMem.h:67