OVR_DebugHelp.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. /************************************************************************************
  2. Filename : OVR_DebugHelp.h
  3. Content : Platform-independent exception handling interface
  4. Created : October 6, 2014
  5. Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. ************************************************************************************/
  16. #ifndef OVR_DebugHelp_h
  17. #define OVR_DebugHelp_h
  18. #include "OVR_Types.h"
  19. #include "OVR_String.h"
  20. #include "OVR_Threads.h"
  21. #include "OVR_Atomic.h"
  22. #include "OVR_Nullptr.h"
  23. #include "OVR_System.h"
  24. #include <stdio.h>
  25. #include <time.h>
  26. #if defined(OVR_OS_WIN32) || defined(OVR_OS_WIN64)
  27. #include "OVR_Win32_IncludeWindows.h"
  28. #elif defined(OVR_OS_APPLE)
  29. #include <pthread.h>
  30. #include <mach/thread_status.h>
  31. #include <mach/mach_types.h>
  32. extern "C" void* MachHandlerThreadFunctionStatic(void*);
  33. extern "C" int catch_mach_exception_raise_state_identity_OVR(mach_port_t, mach_port_t, mach_port_t, exception_type_t, mach_exception_data_type_t*,
  34. mach_msg_type_number_t, int*, thread_state_t, mach_msg_type_number_t, thread_state_t, mach_msg_type_number_t*);
  35. #elif defined(OVR_OS_LINUX)
  36. #include <pthread.h>
  37. #endif
  38. OVR_DISABLE_MSVC_WARNING(4351) // new behavior: elements of array will be default initialized
  39. namespace OVR {
  40. // Thread identifiers
  41. //typedef void* ThreadHandle; // Already defined by OVR Threads. Same as Windows thread handle, Unix pthread_t.
  42. //typedef void* ThreadId; // Already defined by OVR Threads. Used by Windows as DWORD thread id, by Unix as pthread_t.
  43. typedef uintptr_t ThreadSysId; // System thread identifier. Used by Windows the same as ThreadId (DWORD), thread_act_t on Mac/BSD, lwp id on Linux.
  44. // Thread constants
  45. // To do: Move to OVR Threads
  46. #define OVR_THREADHANDLE_INVALID ((ThreadHandle*)nullptr)
  47. #define OVR_THREADID_INVALID ((ThreadId*)nullptr)
  48. #define OVR_THREADSYSID_INVALID ((uintptr_t)0)
  49. OVR::ThreadSysId ConvertThreadHandleToThreadSysId(OVR::ThreadHandle threadHandle);
  50. OVR::ThreadHandle ConvertThreadSysIdToThreadHandle(OVR::ThreadSysId threadSysId); // The returned handle must be freed with FreeThreadHandle.
  51. void FreeThreadHandle(OVR::ThreadHandle threadHandle); // Frees the handle returned by ConvertThreadSysIdToThreadHandle.
  52. OVR::ThreadSysId GetCurrentThreadSysId();
  53. // CPUContext
  54. #if defined(OVR_OS_MS)
  55. typedef CONTEXT CPUContext;
  56. #elif defined(OVR_OS_MAC)
  57. struct CPUContext
  58. {
  59. x86_thread_state_t threadState; // This works for both x86 and x64.
  60. x86_float_state_t floatState;
  61. x86_debug_state_t debugState;
  62. x86_avx_state_t avxState;
  63. x86_exception_state exceptionState;
  64. CPUContext() { memset(this, 0, sizeof(CPUContext)); }
  65. };
  66. #elif defined(OVR_OS_LINUX)
  67. typedef int CPUContext; // To do.
  68. #endif
  69. // Tells if the current process appears to be running under a debugger. Does not attempt to
  70. // detect the case of stealth debuggers (malware-related for example).
  71. bool OVRIsDebuggerPresent();
  72. // Exits the process with the given exit code.
  73. #if !defined(OVR_NORETURN)
  74. #if defined(OVR_CC_MSVC)
  75. #define OVR_NORETURN __declspec(noreturn)
  76. #else
  77. #define OVR_NORETURN __attribute__((noreturn))
  78. #endif
  79. #endif
  80. OVR_NORETURN void ExitProcess(intptr_t processReturnValue);
  81. // Returns the instruction pointer of the caller for the position right after the call.
  82. OVR_NO_INLINE void GetInstructionPointer(void*& pInstruction);
  83. // Returns the stack base and limit addresses for the given thread, or for the current thread if the threadHandle is default.
  84. // The stack limit is a value less than the stack base on most platforms, as stacks usually grow downward.
  85. // Some platforms (e.g. Microsoft) have dynamically resizing stacks, in which case the stack limit reflects the current limit.
  86. void GetThreadStackBounds(void*& pStackBase, void*& pStackLimit, ThreadHandle threadHandle = OVR_THREADHANDLE_INVALID);
  87. /// Used by KillCdeclFunction and RestoreCdeclFunction
  88. ///
  89. struct SavedFunction
  90. {
  91. void* Function;
  92. uint8_t Size;
  93. uint8_t Data[15];
  94. SavedFunction() : Function(nullptr), Size(0){}
  95. };
  96. /// Overwrites the implementation of a statically linked function with an implementation
  97. /// that unilaterally returns the given int32_t value. Works regardless of the arguments
  98. /// passed to that function by the caller. This version is specific to cdecl functions
  99. /// as opposed to Microsoft stdcall functions. Requires the ability to use VirtualProtect
  100. /// to change the code memory to be writable. Returns true if the operation was successful.
  101. ///
  102. /// Since this function overwrites the memory of the existing function implementation,
  103. /// it reequires the function to have at least enough bytes for this. If functionReturnValue
  104. /// is zero then pFunction must be at least three bytes in size. If functionReturnValue is
  105. /// non-zero then pFunction must be at least six bytes in size.
  106. ///
  107. /// Example usage:
  108. /// int __cdecl _CrtIsValidHeapPointer(const void* heapPtr);
  109. ///
  110. /// void main(int, char*[]){
  111. /// KillCdeclFunction(_CrtIsValidHeapPointer, TRUE); // Make _CrtIsValidHeapPointer always return true.
  112. /// }
  113. ///
  114. bool KillCdeclFunction(void* pFunction, int32_t functionReturnValue, SavedFunction* pSavedFunction = nullptr);
  115. /// This version is for functions that return void. It causes them to immediately return.
  116. ///
  117. /// Example usage:
  118. /// void __cdecl _CrtCheckMemory();
  119. ///
  120. /// void main(int, char*[]){
  121. /// KillCdeclFunction(_CrtCheckMemory);
  122. /// }
  123. ///
  124. bool KillCdeclFunction(void* pFunction, SavedFunction* pSavedFunction = nullptr);
  125. /// Restores a function which was previously killed by KillCdeclFunction.
  126. ///
  127. /// Example usage:
  128. /// void main(int, char*[]){
  129. /// SavedFunction savedFunction
  130. /// KillCdeclFunction(_CrtCheckMemory, &savedFunction);
  131. /// [...]
  132. /// RestoreCdeclFunction(&savedFunction);
  133. /// }
  134. ///
  135. bool RestoreCdeclFunction(SavedFunction* pSavedFunction);
  136. /// Smart class which temporarily kills a function and restores it upon scope completion.
  137. ///
  138. /// Example usage:
  139. /// void main(int, char*[]){
  140. /// TempCdeclFunctionKill tempKill(_CrtIsValidHeapPointer, TRUE);
  141. /// [...]
  142. /// }
  143. ///
  144. struct TempCdeclFunctionKill
  145. {
  146. TempCdeclFunctionKill(void* pFunction, int32_t functionReturnValue) : Success(false), FunctionPtr(nullptr), SavedFunctionData()
  147. { Success = KillCdeclFunction(pFunction, functionReturnValue, &SavedFunctionData); }
  148. TempCdeclFunctionKill(void* pFunction) : Success(false), FunctionPtr(nullptr), SavedFunctionData()
  149. { Success = KillCdeclFunction(pFunction, &SavedFunctionData); }
  150. ~TempCdeclFunctionKill()
  151. { if(Success) RestoreCdeclFunction(&SavedFunctionData); }
  152. bool Success;
  153. void* FunctionPtr;
  154. SavedFunction SavedFunctionData;
  155. };
  156. // OVR_MAX_PATH
  157. // Max file path length (for most uses).
  158. // To do: move this to OVR_File.
  159. #if !defined(OVR_MAX_PATH)
  160. #if defined(OVR_OS_MS) // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
  161. #define OVR_MAX_PATH 260 // Windows can use paths longer than this in some cases (network paths, UNC paths).
  162. #else
  163. #define OVR_MAX_PATH 1024 // This isn't a strict limit on all Unix-based platforms.
  164. #endif
  165. #endif
  166. // ModuleHandle
  167. #if defined(OVR_OS_MS)
  168. typedef void* ModuleHandle; // from LoadLibrary()
  169. #elif defined(OVR_OS_APPLE) || defined(OVR_OS_UNIX)
  170. typedef void* ModuleHandle; // from dlopen()
  171. #endif
  172. #define OVR_MODULEHANDLE_INVALID ((ModuleHandle*)nullptr)
  173. // Module info constants
  174. static const ModuleHandle kMIHandleInvalid = OVR_MODULEHANDLE_INVALID;
  175. static const uint64_t kMIAddressInvalid = 0xffffffffffffffffull;
  176. static const uint64_t kMISizeInvalid = 0xffffffffffffffffull;
  177. static const int32_t kMILineNumberInvalid = -1;
  178. static const int32_t kMIFunctionOffsetInvalid = -1;
  179. static const uint64_t kMIBaseAddressInvalid = 0xffffffffffffffffull;
  180. static const uint64_t kMIBaseAddressUnspecified = 0xffffffffffffffffull;
  181. struct ModuleInfo
  182. {
  183. ModuleHandle handle;
  184. uint64_t baseAddress; // The actual runtime base address of the module. May be different from the base address specified in the debug symbol file.
  185. uint64_t size;
  186. char filePath[OVR_MAX_PATH];
  187. char name[32];
  188. char type[8]; // Unix-specific. e.g. __TEXT
  189. char permissions[8]; // Unix specific. e.g. "drwxr-xr-x"
  190. ModuleInfo() : handle(kMIHandleInvalid), baseAddress(kMIBaseAddressInvalid), size(0), filePath(), name(){}
  191. };
  192. // Refers to symbol info for an instruction address.
  193. // Info includes function name, source code file/line, and source code itself.
  194. struct SymbolInfo
  195. {
  196. uint64_t address;
  197. uint64_t size;
  198. const ModuleInfo* pModuleInfo;
  199. char filePath[OVR_MAX_PATH];
  200. int32_t fileLineNumber;
  201. char function[128]; // This is a fixed size because we need to use it during application exceptions.
  202. int32_t functionOffset;
  203. char sourceCode[1024]; // This is a string representing the code itself and not a file path to the code.
  204. SymbolInfo() : address(kMIAddressInvalid), size(kMISizeInvalid), pModuleInfo(nullptr), filePath(),
  205. fileLineNumber(kMILineNumberInvalid), function(), functionOffset(kMIFunctionOffsetInvalid), sourceCode() {}
  206. };
  207. // Implements support for reading thread lists, module lists, backtraces, and backtrace symbols.
  208. class SymbolLookup
  209. {
  210. public:
  211. SymbolLookup();
  212. ~SymbolLookup();
  213. static bool Initialize();
  214. static bool IsInitialized();
  215. static void Shutdown();
  216. void AddSourceCodeDirectory(const char* pDirectory);
  217. // Should be disabled when within an exception handler.
  218. void EnableMemoryAllocation(bool enabled);
  219. // Refresh our view of the symbols and modules present within the current process.
  220. bool Refresh();
  221. // Retrieves the backtrace (call stack) of the given thread. There may be some per-platform restrictions on this.
  222. // Returns the number written, which will be <= addressArrayCapacity.
  223. // This may not work on some platforms unless stack frames are enabled.
  224. // For Microsoft platforms the platformThreadContext is CONTEXT*.
  225. // For Apple platforms the platformThreadContext is x86_thread_state_t* or arm_thread_state_t*.
  226. // If threadSysIdHelp is non-zero, it may be used by the implementation to help produce a better backtrace.
  227. size_t GetBacktrace(void* addressArray[], size_t addressArrayCapacity, size_t skipCount = 0, void* platformThreadContext = nullptr, OVR::ThreadSysId threadSysIdHelp = OVR_THREADSYSID_INVALID);
  228. // Retrieves the backtrace for the given ThreadHandle.
  229. // Returns the number written, which will be <= addressArrayCapacity.
  230. size_t GetBacktraceFromThreadHandle(void* addressArray[], size_t addressArrayCapacity, size_t skipCount = 0, OVR::ThreadHandle threadHandle = OVR_THREADHANDLE_INVALID);
  231. // Retrieves the backtrace for the given ThreadSysId.
  232. // Returns the number written, which will be <= addressArrayCapacity.
  233. size_t GetBacktraceFromThreadSysId(void* addressArray[], size_t addressArrayCapacity, size_t skipCount = 0, OVR::ThreadSysId threadSysId = OVR_THREADSYSID_INVALID);
  234. // Gets a list of the modules (e.g. DLLs) present in the current process.
  235. // Writes as many ModuleInfos as possible to pModuleInfoArray.
  236. // Returns the required count of ModuleInfos, which will be > moduleInfoArrayCapacity if the capacity needs to be larger.
  237. size_t GetModuleInfoArray(ModuleInfo* pModuleInfoArray, size_t moduleInfoArrayCapacity);
  238. // Retrieves a list of the current threads. Unless the process is paused the list is volatile.
  239. // Returns the required capacity, which may be larger than threadArrayCapacity.
  240. // Either array can be NULL to specify that it's not written to.
  241. // For Windows the caller needs to CloseHandle the returned ThreadHandles. This can be done by calling DoneThreadList.
  242. size_t GetThreadList(ThreadHandle* threadHandleArray, ThreadSysId* threadSysIdArray, size_t threadArrayCapacity);
  243. // Frees any references to thread handles or ids returned by GetThreadList;
  244. void DoneThreadList(ThreadHandle* threadHandleArray, ThreadSysId* threadSysIdArray, size_t threadArrayCount);
  245. // Writes a given thread's callstack with symbols to the given output.
  246. // It may not be safe to call this from an exception handler, as sOutput allocates memory.
  247. bool ReportThreadCallstack(OVR::String& sOutput, size_t skipCount = 0, ThreadSysId threadSysId = OVR_THREADSYSID_INVALID);
  248. // Writes all thread's callstacks with symbols to the given output.
  249. // It may not be safe to call this from an exception handler, as sOutput allocates memory.
  250. bool ReportThreadCallstacks(OVR::String& sOutput, size_t skipCount = 0);
  251. // Writes all loaded modules to the given output string.
  252. // It may not be safe to call this from an exception handler, as sOutput allocates memory.
  253. bool ReportModuleInformation(OVR::String& sOutput);
  254. // Retrieves symbol info for the given address.
  255. bool LookupSymbol(uint64_t address, SymbolInfo& symbolInfo);
  256. bool LookupSymbols(uint64_t* addressArray, SymbolInfo* pSymbolInfoArray, size_t arraySize);
  257. const ModuleInfo* GetModuleInfoForAddress(uint64_t address); // The returned ModuleInfo points to an internal structure.
  258. protected:
  259. bool RefreshModuleList();
  260. protected:
  261. bool AllowMemoryAllocation; // True by default. If true then we allow allocating memory (and as a result provide less information). This is useful for when in an exception handler.
  262. bool ModuleListUpdated;
  263. ModuleInfo ModuleInfoArray[256]; // Cached list of modules we use. This is a fixed size because we need to use it during application exceptions.
  264. size_t ModuleInfoArraySize;
  265. };
  266. // ExceptionInfo
  267. // We need to be careful to avoid data types that can allocate memory while we are
  268. // handling an exception, as the memory system may be corrupted at that point in time.
  269. struct ExceptionInfo
  270. {
  271. tm time; // GM time.
  272. time_t timeVal; // GM time_t (seconds since 1970).
  273. void* backtrace[64];
  274. size_t backtraceCount;
  275. ThreadHandle threadHandle; //
  276. ThreadSysId threadSysId; //
  277. char threadName[32]; // Cannot be an allocating String object.
  278. void* pExceptionInstructionAddress;
  279. void* pExceptionMemoryAddress;
  280. CPUContext cpuContext;
  281. char exceptionDescription[1024]; // Cannot be an allocating String object.
  282. SymbolInfo symbolInfo; // SymbolInfo for the exception location.
  283. #if defined(OVR_OS_MS)
  284. EXCEPTION_RECORD exceptionRecord; // This is a Windows SDK struct.
  285. #elif defined(OVR_OS_APPLE)
  286. uint64_t exceptionType; // e.g. EXC_BAD_INSTRUCTION, EXC_BAD_ACCESS, etc.
  287. uint32_t cpuExceptionId; // The x86/x64 CPU trap id.
  288. uint32_t cpuExceptionIdError; // The x86/x64 CPU trap id extra info.
  289. int64_t machExceptionData[4]; // Kernel exception code info.
  290. int machExceptionDataCount; // Count of valid entries.
  291. #endif
  292. ExceptionInfo();
  293. };
  294. // Implments support for asynchronous exception handling and basic exception report generation.
  295. // If you are implementing exception handling for a commercial application and want auto-uploading
  296. // functionality you may want to consider using something like Google Breakpad. This exception handler
  297. // is for in-application debug/diagnostic services, though it can write a report that has similar
  298. // information to Breakpad or OS-provided reports such as Apple .crash files.
  299. //
  300. // Example usage:
  301. // ExceptionHandler exceptionHandler;
  302. //
  303. // int main(int, char**)
  304. // {
  305. // exceptionHandler.Enable(true);
  306. // exceptionHandler.SetExceptionListener(pSomeListener, 0); // Optional listener hook.
  307. // }
  308. //
  309. class ExceptionHandler
  310. {
  311. public:
  312. ExceptionHandler();
  313. ~ExceptionHandler();
  314. // Enables or disables handling by installing or uninstalling an exception handler.
  315. // If you merely want to temporarily pause handling then it may be better to cause PauseHandling,
  316. // as that's a lighter weight solution.
  317. bool Enable(bool enable);
  318. // Pauses handling. Exceptions will be caught but immediately passed on to the next handler
  319. // without taking any action. Pauses are additive and calls to Pause(true) must be eventually
  320. // matched to Pause(false). This function can be called from multiple threads simultaneously.
  321. // Returns the new pause count.
  322. int PauseHandling(bool pause);
  323. // Some report info can be considered private information of the user, such as the current process list,
  324. // computer name, IP address or other identifying info, etc. We should not report this information for
  325. // external users unless they agree to this.
  326. void EnableReportPrivacy(bool enable);
  327. struct ExceptionListener
  328. {
  329. virtual ~ExceptionListener(){}
  330. virtual int HandleException(uintptr_t userValue, ExceptionHandler* pExceptionHandler, ExceptionInfo* pExceptionInfo, const char* reportFilePath) = 0;
  331. };
  332. void SetExceptionListener(ExceptionListener* pExceptionListener, uintptr_t userValue);
  333. // What we do after handling the exception.
  334. enum ExceptionResponse
  335. {
  336. kERContinue, // Continue execution. Will result in the exception being re-generated unless the application has fixed the cause. Similar to Windows EXCEPTION_CONTINUE_EXECUTION.
  337. kERHandle, // Causes the OS to handle the exception as it normally would. Similar to Windows EXCEPTION_EXECUTE_HANDLER.
  338. kERTerminate, // Exit the application.
  339. kERThrow, // Re-throw the exception. Other handlers may catch it. Similar to Windows EXCEPTION_CONTINUE_SEARCH.
  340. kERDefault // Usually set to kERTerminate.
  341. };
  342. void SetExceptionResponse(ExceptionResponse er)
  343. { exceptionResponse = er; }
  344. // Allws you to add an arbitrary description of the current application, which will be added to exception reports.
  345. void SetAppDescription(const char* appDescription);
  346. // If the report path has a "%s" in its name, then assume the path is a sprintf format and write it
  347. // with the %s specified as a date/time string.
  348. // The report path can be "default" to signify that you want to use the default user location.
  349. // Passing NULL for exceptionReportPath or exceptionMinidumpPath causes those files to not be written.
  350. // By default both the exceptionReportPath and exceptionMinidumpPath are NULL.
  351. // Example usage:
  352. // handler.SetExceptionPaths("/Users/Current/Exceptions/Exception %s.txt");
  353. void SetExceptionPaths(const char* exceptionReportPath, const char* exceptionMinidumpPath = nullptr);
  354. // Calls SetExceptionPaths in the appropriate convention for each operating system
  355. // Windows: %AppData%\Organization\Application
  356. // Mac: ~/Library/Logs/DiagnosticReports/Organization/Application"
  357. // Linux: ~/Library/Organization/Application
  358. // exceptionFormat and minidumpFormat define the file names in the format above
  359. // with the %s specified as a date/time string.
  360. void SetPathsFromNames(const char* organizationName, const char* ApplicationName, const char* exceptionFormat = "Exception Report (%s).txt", const char* minidumpFormat = "Exception Minidump (%s).mdmp");
  361. // Allows you to specify base directories for code paths, which can be used to associate exception addresses to lines
  362. // of code as opposed to just file names and line numbers, or function names plus binary offsets.
  363. void SetCodeBaseDirectoryPaths(const char* codeBaseDirectoryPathArray[], size_t codeBaseDirectoryPathCount);
  364. // Writes lines into the current report.
  365. void WriteReportLine(const char* pLine);
  366. void WriteReportLineF(const char* format, ...);
  367. // Retrieves a directory path which ends with a path separator.
  368. // Returns the required strlen of the path.
  369. // Guarantees the presence of the directory upon returning true.
  370. static size_t GetCrashDumpDirectory(char* directoryPath, size_t directoryPathCapacity);
  371. // Given an exception report at a given file path, returns a string suitable for displaying in a message
  372. // box or similar user interface during the handling of an exception. The returned string must be passed
  373. // to FreeMessageBoxText when complete.
  374. static const char* GetExceptionUIText(const char* exceptionReportPath);
  375. static void FreeExceptionUIText(const char* messageBoxText);
  376. // Writes a deadlock report similar to an exception report. Since there is no allocation risk, an exception handler is created for this log.
  377. static void ReportDeadlock(const char* threadName, const char* organizationName = nullptr, const char* applicationName = nullptr);
  378. protected:
  379. // Write one log line to log file, console, syslog, and debug output.
  380. // If LogFile is null, it will not write to the log file.
  381. // The buffer must be null-terminated.
  382. void writeLogLine(const char* buffer, int length);
  383. void WriteExceptionDescription();
  384. void WriteReport();
  385. void WriteThreadCallstack(ThreadHandle threadHandle, ThreadSysId threadSysId, const char* additionalInfo);
  386. void WriteMiniDump();
  387. // Runtime constants
  388. bool enabled;
  389. OVR::AtomicInt<int> pauseCount; // 0 means unpaused. 1+ means paused.
  390. bool reportPrivacyEnabled; // Defaults to true.
  391. ExceptionResponse exceptionResponse; // Defaults to kERHandle
  392. ExceptionListener* exceptionListener;
  393. uintptr_t exceptionListenerUserValue;
  394. String appDescription;
  395. String codeBasePathArray[6]; // 6 is arbitrary.
  396. char reportFilePath[OVR_MAX_PATH];// May be an encoded path, in that it has "%s" in it or is named "default". See reporFiletPathActual for the runtime actual report path.
  397. int miniDumpFlags;
  398. char miniDumpFilePath[OVR_MAX_PATH];
  399. FILE* LogFile; // Can/should we use OVR Files for this?
  400. char scratchBuffer[4096];
  401. // Runtime variables
  402. bool exceptionOccurred;
  403. OVR::AtomicInt<uint32_t> handlingBusy;
  404. char reportFilePathActual[OVR_MAX_PATH];
  405. char minidumpFilePathActual[OVR_MAX_PATH];
  406. int terminateReturnValue;
  407. ExceptionInfo exceptionInfo;
  408. SymbolLookup symbolLookup;
  409. #if defined(OVR_OS_MS)
  410. void* vectoredHandle;
  411. LPTOP_LEVEL_EXCEPTION_FILTER previousFilter;
  412. LPEXCEPTION_POINTERS pExceptionPointers;
  413. friend LONG WINAPI Win32ExceptionFilter(LPEXCEPTION_POINTERS pExceptionPointers);
  414. LONG ExceptionFilter(LPEXCEPTION_POINTERS pExceptionPointers);
  415. //handles exception in a new thread, used for stack overflow
  416. static unsigned WINAPI ExceptionHandlerThreadExec(void * callingHandler);
  417. #elif defined(OVR_OS_APPLE)
  418. struct SavedExceptionPorts
  419. {
  420. SavedExceptionPorts() : count(0) { memset(this, 0, sizeof(SavedExceptionPorts)); }
  421. mach_msg_type_number_t count;
  422. exception_mask_t masks[6];
  423. exception_handler_t ports[6];
  424. exception_behavior_t behaviors[6];
  425. thread_state_flavor_t flavors[6];
  426. };
  427. friend void* ::MachHandlerThreadFunctionStatic(void*);
  428. friend int ::catch_mach_exception_raise_state_identity_OVR(mach_port_t, mach_port_t, mach_port_t, exception_type_t,
  429. mach_exception_data_type_t*, mach_msg_type_number_t, int*, thread_state_t,
  430. mach_msg_type_number_t, thread_state_t, mach_msg_type_number_t*);
  431. bool InitMachExceptionHandler();
  432. void ShutdownMachExceptionHandler();
  433. void* MachHandlerThreadFunction();
  434. kern_return_t HandleMachException(mach_port_t port, mach_port_t thread, mach_port_t task, exception_type_t exceptionType,
  435. mach_exception_data_type_t* pExceptionDetail, mach_msg_type_number_t exceptionDetailCount,
  436. int* pFlavor, thread_state_t pOldState, mach_msg_type_number_t oldStateCount, thread_state_t pNewState,
  437. mach_msg_type_number_t* pNewStateCount);
  438. kern_return_t ForwardMachException(mach_port_t thread, mach_port_t task, exception_type_t exceptionType,
  439. mach_exception_data_t pExceptionDetail, mach_msg_type_number_t exceptionDetailCount);
  440. bool machHandlerInitialized;
  441. mach_port_t machExceptionPort;
  442. SavedExceptionPorts machExceptionPortsSaved;
  443. volatile bool machThreadShouldContinue;
  444. volatile bool machThreadExecuting;
  445. pthread_t machThread;
  446. #elif defined(OVR_OS_LINUX)
  447. // To do.
  448. #endif
  449. };
  450. // Identifies basic exception types for the CreateException function.
  451. enum CreateExceptionType
  452. {
  453. kCETAccessViolation, // Read or write to inaccessable memory.
  454. kCETAlignment, // Misaligned read or write.
  455. kCETDivideByZero, // Integer divide by zero.
  456. kCETFPU, // Floating point / VPU exception.
  457. kCETIllegalInstruction, // Illegal opcode.
  458. kCETStackCorruption, // Stack frame was corrupted.
  459. kCETStackOverflow, // Stack ran out of space, often due to infinite recursion.
  460. kCETTrap // System/OS trap (system call).
  461. };
  462. // Creates an exception of the given type, primarily for testing.
  463. void CreateException(CreateExceptionType exceptionType);
  464. //-----------------------------------------------------------------------------
  465. // GUI Exception Listener
  466. //
  467. // When this exception handler is called, it will verify that the application
  468. // is not being debugged at that instant. If not, then it will present a GUI
  469. // to the user containing error information.
  470. // Initially the exception listener is not silenced.
  471. class GUIExceptionListener : public ExceptionHandler::ExceptionListener
  472. {
  473. public:
  474. GUIExceptionListener();
  475. virtual int HandleException(uintptr_t userValue,
  476. ExceptionHandler* pExceptionHandler,
  477. ExceptionInfo* pExceptionInfo,
  478. const char* reportFilePath) OVR_OVERRIDE;
  479. protected:
  480. ExceptionHandler Handler;
  481. };
  482. } // namespace OVR
  483. OVR_RESTORE_MSVC_WARNING()
  484. #endif // OVR_DebugHelp_h