Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

687 lines
24 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. //=============================================================================//
  6. #include "pch_tier0.h"
  7. #include "tier0/minidump.h"
  8. #include "tier0/platform.h"
  9. #if defined( _WIN32 ) && !defined( _X360 )
  10. #if _MSC_VER >= 1300
  11. #include "tier0/valve_off.h"
  12. #define WIN_32_LEAN_AND_MEAN
  13. #include <windows.h>
  14. #include <dbghelp.h>
  15. #include <time.h>
  16. // MiniDumpWriteDump() function declaration (so we can just get the function directly from windows)
  17. typedef BOOL (WINAPI *MINIDUMPWRITEDUMP)
  18. (
  19. HANDLE hProcess,
  20. DWORD dwPid,
  21. HANDLE hFile,
  22. MINIDUMP_TYPE DumpType,
  23. CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
  24. CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
  25. CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam
  26. );
  27. // counter used to make sure minidump names are unique
  28. static int g_nMinidumpsWritten = 0;
  29. // process-wide prefix to use for minidumps
  30. static tchar g_rgchMinidumpFilenamePrefix[MAX_PATH];
  31. // Process-wide comment to put into minidumps
  32. static char g_rgchMinidumpComment[2048];
  33. //-----------------------------------------------------------------------------
  34. // Purpose: Creates a new file and dumps the exception info into it
  35. // Input : uStructuredExceptionCode - windows exception code, unused.
  36. // pExceptionInfo - call stack.
  37. // minidumpType - type of minidump to write.
  38. // ptchMinidumpFileNameBuffer - if not-NULL points to a writable tchar buffer
  39. // of length at least _MAX_PATH to contain the name
  40. // of the written minidump file on return.
  41. //-----------------------------------------------------------------------------
  42. bool WriteMiniDumpUsingExceptionInfo(
  43. unsigned int uStructuredExceptionCode,
  44. _EXCEPTION_POINTERS * pExceptionInfo,
  45. int minidumpType,
  46. const char *pszFilenameSuffix,
  47. tchar *ptchMinidumpFileNameBuffer /* = NULL */
  48. )
  49. {
  50. if ( ptchMinidumpFileNameBuffer )
  51. {
  52. *ptchMinidumpFileNameBuffer = tchar( 0 );
  53. }
  54. // get the function pointer directly so that we don't have to include the .lib, and that
  55. // we can easily change it to using our own dll when this code is used on win98/ME/2K machines
  56. HMODULE hDbgHelpDll = ::LoadLibrary( "DbgHelp.dll" );
  57. if ( !hDbgHelpDll )
  58. return false;
  59. bool bReturnValue = false;
  60. MINIDUMPWRITEDUMP pfnMiniDumpWrite = (MINIDUMPWRITEDUMP) ::GetProcAddress( hDbgHelpDll, "MiniDumpWriteDump" );
  61. if ( pfnMiniDumpWrite )
  62. {
  63. // create a unique filename for the minidump based on the current time and module name
  64. time_t currTime = ::time( NULL );
  65. struct tm * pTime = ::localtime( &currTime );
  66. ++g_nMinidumpsWritten;
  67. // If they didn't set a dump prefix, then set one for them using the module name
  68. if ( g_rgchMinidumpFilenamePrefix[0] == TCHAR(0) )
  69. {
  70. tchar rgchModuleName[MAX_PATH];
  71. #ifdef TCHAR_IS_WCHAR
  72. ::GetModuleFileNameW( NULL, rgchModuleName, sizeof(rgchModuleName) / sizeof(tchar) );
  73. #else
  74. ::GetModuleFileName( NULL, rgchModuleName, sizeof(rgchModuleName) / sizeof(tchar) );
  75. #endif
  76. // strip off the rest of the path from the .exe name
  77. tchar *pch = _tcsrchr( rgchModuleName, '.' );
  78. if ( pch )
  79. {
  80. *pch = 0;
  81. }
  82. pch = _tcsrchr( rgchModuleName, '\\' );
  83. if ( pch )
  84. {
  85. // move past the last slash
  86. pch++;
  87. }
  88. else
  89. {
  90. pch = _T("unknown");
  91. }
  92. strcpy( g_rgchMinidumpFilenamePrefix, pch );
  93. }
  94. // can't use the normal string functions since we're in tier0
  95. tchar rgchFileName[MAX_PATH];
  96. _sntprintf( rgchFileName, sizeof(rgchFileName) / sizeof(tchar),
  97. _T("%s_%d%02d%02d_%02d%02d%02d_%d%hs%hs.mdmp"),
  98. g_rgchMinidumpFilenamePrefix,
  99. pTime->tm_year + 1900, /* Year less 2000 */
  100. pTime->tm_mon + 1, /* month (0 - 11 : 0 = January) */
  101. pTime->tm_mday, /* day of month (1 - 31) */
  102. pTime->tm_hour, /* hour (0 - 23) */
  103. pTime->tm_min, /* minutes (0 - 59) */
  104. pTime->tm_sec, /* seconds (0 - 59) */
  105. g_nMinidumpsWritten, // ensures the filename is unique
  106. ( pszFilenameSuffix != NULL ) ? "_" : "",
  107. ( pszFilenameSuffix != NULL ) ? pszFilenameSuffix : ""
  108. );
  109. // Ensure null-termination.
  110. rgchFileName[ Q_ARRAYSIZE(rgchFileName) - 1 ] = 0;
  111. // Create directory, if our dump filename had a directory in it
  112. for ( char *pSlash = rgchFileName ; *pSlash != '\0' ; ++pSlash )
  113. {
  114. char c = *pSlash;
  115. if ( c == '/' || c == '\\' )
  116. {
  117. *pSlash = '\0';
  118. ::CreateDirectory( rgchFileName, NULL );
  119. *pSlash = c;
  120. }
  121. }
  122. BOOL bMinidumpResult = FALSE;
  123. #ifdef TCHAR_IS_WCHAR
  124. HANDLE hFile = ::CreateFileW( rgchFileName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
  125. #else
  126. HANDLE hFile = ::CreateFile( rgchFileName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
  127. #endif
  128. if ( hFile )
  129. {
  130. // dump the exception information into the file
  131. _MINIDUMP_EXCEPTION_INFORMATION ExInfo;
  132. ExInfo.ThreadId = ::GetCurrentThreadId();
  133. ExInfo.ExceptionPointers = pExceptionInfo;
  134. ExInfo.ClientPointers = FALSE;
  135. // Do we have a comment?
  136. MINIDUMP_USER_STREAM_INFORMATION StreamInformationHeader;
  137. MINIDUMP_USER_STREAM UserStreams[1];
  138. memset( &StreamInformationHeader, 0, sizeof(StreamInformationHeader) );
  139. StreamInformationHeader.UserStreamArray = UserStreams;
  140. if ( g_rgchMinidumpComment[0] != '\0' )
  141. {
  142. MINIDUMP_USER_STREAM *pCommentStream = &UserStreams[StreamInformationHeader.UserStreamCount++];
  143. pCommentStream->Type = CommentStreamA;
  144. pCommentStream->Buffer = g_rgchMinidumpComment;
  145. pCommentStream->BufferSize = (ULONG)strlen(g_rgchMinidumpComment)+1;
  146. }
  147. bMinidumpResult = (*pfnMiniDumpWrite)( ::GetCurrentProcess(), ::GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)minidumpType, &ExInfo, &StreamInformationHeader, NULL );
  148. ::CloseHandle( hFile );
  149. // Clear comment for next time
  150. g_rgchMinidumpComment[0] = '\0';
  151. if ( bMinidumpResult )
  152. {
  153. bReturnValue = true;
  154. if ( ptchMinidumpFileNameBuffer )
  155. {
  156. // Copy the file name from "pSrc = rgchFileName" into "pTgt = ptchMinidumpFileNameBuffer"
  157. tchar *pTgt = ptchMinidumpFileNameBuffer;
  158. tchar const *pSrc = rgchFileName;
  159. while ( ( *( pTgt ++ ) = *( pSrc ++ ) ) != tchar( 0 ) )
  160. continue;
  161. }
  162. }
  163. // fall through to trying again
  164. }
  165. // mark any failed minidump writes by renaming them
  166. if ( !bMinidumpResult )
  167. {
  168. tchar rgchFailedFileName[_MAX_PATH];
  169. _sntprintf( rgchFailedFileName, sizeof(rgchFailedFileName) / sizeof(tchar), "(failed)%s", rgchFileName );
  170. // Ensure null-termination.
  171. rgchFailedFileName[ Q_ARRAYSIZE(rgchFailedFileName) - 1 ] = 0;
  172. rename( rgchFileName, rgchFailedFileName );
  173. }
  174. }
  175. ::FreeLibrary( hDbgHelpDll );
  176. // call the log flush function if one is registered to try to flush any logs
  177. //CallFlushLogFunc();
  178. return bReturnValue;
  179. }
  180. void InternalWriteMiniDumpUsingExceptionInfo( unsigned int uStructuredExceptionCode, _EXCEPTION_POINTERS * pExceptionInfo, const char *pszFilenameSuffix )
  181. {
  182. // If this is is a real crash (not an assert or one we purposefully triggered), then try to write a full dump
  183. // only do this on our GC (currently GC is 64-bit, so we can use a #define rather than some run-time switch
  184. #ifdef _WIN64
  185. if ( uStructuredExceptionCode != EXCEPTION_BREAKPOINT )
  186. {
  187. if ( WriteMiniDumpUsingExceptionInfo( uStructuredExceptionCode, pExceptionInfo, MiniDumpWithFullMemory, pszFilenameSuffix ) )
  188. {
  189. return;
  190. }
  191. }
  192. #endif
  193. // First try to write it with all the indirectly referenced memory (ie: a large file).
  194. // If that doesn't work, then write a smaller one.
  195. int iType = MiniDumpWithDataSegs | MiniDumpWithIndirectlyReferencedMemory;
  196. if ( !WriteMiniDumpUsingExceptionInfo( uStructuredExceptionCode, pExceptionInfo, (MINIDUMP_TYPE)iType, pszFilenameSuffix ) )
  197. {
  198. iType = MiniDumpWithDataSegs;
  199. WriteMiniDumpUsingExceptionInfo( uStructuredExceptionCode, pExceptionInfo, (MINIDUMP_TYPE)iType, pszFilenameSuffix );
  200. }
  201. }
  202. // minidump function to use
  203. static FnMiniDump g_pfnWriteMiniDump = InternalWriteMiniDumpUsingExceptionInfo;
  204. //-----------------------------------------------------------------------------
  205. // Purpose: Set a function to call which will write our minidump, overriding
  206. // the default function
  207. // Input : pfn - Pointer to minidump function to set
  208. // Output : Previously set function
  209. //-----------------------------------------------------------------------------
  210. FnMiniDump SetMiniDumpFunction( FnMiniDump pfn )
  211. {
  212. FnMiniDump pfnTemp = g_pfnWriteMiniDump;
  213. g_pfnWriteMiniDump = pfn;
  214. return pfnTemp;
  215. }
  216. //-----------------------------------------------------------------------------
  217. // Unhandled exceptions
  218. //-----------------------------------------------------------------------------
  219. static FnMiniDump g_UnhandledExceptionFunction;
  220. static LONG STDCALL ValveUnhandledExceptionFilter( _EXCEPTION_POINTERS* pExceptionInfo )
  221. {
  222. uint uStructuredExceptionCode = pExceptionInfo->ExceptionRecord->ExceptionCode;
  223. g_UnhandledExceptionFunction( uStructuredExceptionCode, pExceptionInfo, 0 );
  224. return EXCEPTION_CONTINUE_SEARCH;
  225. }
  226. void MinidumpSetUnhandledExceptionFunction( FnMiniDump pfn )
  227. {
  228. g_UnhandledExceptionFunction = pfn;
  229. SetUnhandledExceptionFilter( ValveUnhandledExceptionFilter );
  230. }
  231. //-----------------------------------------------------------------------------
  232. // Purpose: set prefix to use for filenames
  233. //-----------------------------------------------------------------------------
  234. void SetMinidumpFilenamePrefix( const char *pszPrefix )
  235. {
  236. #ifdef TCHAR_IS_WCHAR
  237. mbstowcs( g_rgchMinidumpFilenamePrefix, pszPrefix, sizeof(g_rgchMinidumpFilenamePrefix) / sizeof(g_rgchMinidumpFilenamePrefix[0]) - 1 );
  238. #else
  239. strncpy( g_rgchMinidumpFilenamePrefix, pszPrefix, sizeof(g_rgchMinidumpFilenamePrefix) / sizeof(g_rgchMinidumpFilenamePrefix[0]) - 1 );
  240. #endif
  241. }
  242. //-----------------------------------------------------------------------------
  243. // Purpose: set comment to put into minidumps
  244. //-----------------------------------------------------------------------------
  245. void SetMinidumpComment( const char *pszComment )
  246. {
  247. if ( pszComment == NULL )
  248. pszComment = "";
  249. strncpy( g_rgchMinidumpComment, pszComment, sizeof(g_rgchMinidumpComment) - 1 );
  250. }
  251. //-----------------------------------------------------------------------------
  252. // Purpose: writes out a minidump from the current process
  253. //-----------------------------------------------------------------------------
  254. void WriteMiniDump( const char *pszFilenameSuffix )
  255. {
  256. // throw an exception so we can catch it and get the stack info
  257. __try
  258. {
  259. ::RaiseException
  260. (
  261. EXCEPTION_BREAKPOINT, // dwExceptionCode
  262. EXCEPTION_NONCONTINUABLE, // dwExceptionFlags
  263. 0, // nNumberOfArguments,
  264. NULL // const ULONG_PTR* lpArguments
  265. );
  266. // Never get here (non-continuable exception)
  267. }
  268. // Write the minidump from inside the filter (GetExceptionInformation() is only
  269. // valid in the filter)
  270. __except ( g_pfnWriteMiniDump( EXCEPTION_BREAKPOINT, GetExceptionInformation(), pszFilenameSuffix ), EXCEPTION_EXECUTE_HANDLER )
  271. {
  272. }
  273. }
  274. DBG_OVERLOAD bool g_bInException = false;
  275. //-----------------------------------------------------------------------------
  276. // Purpose: Catches and writes out any exception throw by the specified function.
  277. // Input: pfn - Function to call within protective exception block
  278. // pv - Void pointer to pass that function
  279. //-----------------------------------------------------------------------------
  280. void CatchAndWriteMiniDump( FnWMain pfn, int argc, tchar *argv[] )
  281. {
  282. CatchAndWriteMiniDumpEx( pfn, argc, argv, k_ECatchAndWriteMiniDumpAbort );
  283. }
  284. // message types
  285. enum ECatchAndWriteFunctionType
  286. {
  287. k_eSCatchAndWriteFunctionTypeInvalid = 0,
  288. k_eSCatchAndWriteFunctionTypeWMain = 1, // typedef void (*FnWMain)( int , tchar *[] );
  289. k_eSCatchAndWriteFunctionTypeWMainIntReg = 2, // typedef int (*FnWMainIntRet)( int , tchar *[] );
  290. k_eSCatchAndWriteFunctionTypeVoidPtr = 3, // typedef void (*FnVoidPtrFn)( void * );
  291. };
  292. struct CatchAndWriteContext_t
  293. {
  294. ECatchAndWriteFunctionType m_eType;
  295. void *m_pfn;
  296. int *m_pargc;
  297. tchar ***m_pargv;
  298. void **m_ppv;
  299. ECatchAndWriteMinidumpAction m_eAction;
  300. void Set( ECatchAndWriteFunctionType eType, ECatchAndWriteMinidumpAction eAction, void *pfn, int *pargc, tchar **pargv[], void **ppv )
  301. {
  302. m_eType = eType;
  303. m_eAction = eAction;
  304. m_pfn = pfn;
  305. m_pargc = pargc;
  306. m_pargv = pargv;
  307. m_ppv = ppv;
  308. ErrorIfNot( m_pfn, ( "CatchAndWriteContext_t::Set w/o a function pointer!" ) );
  309. }
  310. int Invoke()
  311. {
  312. switch ( m_eType )
  313. {
  314. default:
  315. case k_eSCatchAndWriteFunctionTypeInvalid:
  316. break;
  317. case k_eSCatchAndWriteFunctionTypeWMain:
  318. ErrorIfNot( m_pargc && m_pargv, ( "CatchAndWriteContext_t::Invoke with bogus argc/argv" ) );
  319. ((FnWMain)m_pfn)( *m_pargc, *m_pargv );
  320. break;
  321. case k_eSCatchAndWriteFunctionTypeWMainIntReg:
  322. ErrorIfNot( m_pargc && m_pargv, ( "CatchAndWriteContext_t::Invoke with bogus argc/argv" ) );
  323. return ((FnWMainIntRet)m_pfn)( *m_pargc, *m_pargv );
  324. case k_eSCatchAndWriteFunctionTypeVoidPtr:
  325. ErrorIfNot( m_ppv, ( "CatchAndWriteContext_t::Invoke with bogus void *ptr" ) );
  326. ((FnVoidPtrFn)m_pfn)( *m_ppv );
  327. break;
  328. }
  329. return 0;
  330. }
  331. };
  332. //-----------------------------------------------------------------------------
  333. // Purpose: Catches and writes out any exception throw by the specified function
  334. // Input: pfn - Function to call within protective exception block
  335. // pv - Void pointer to pass that function
  336. // eAction - Specifies what to do if it catches an exception
  337. //-----------------------------------------------------------------------------
  338. #if defined(_PS3)
  339. int CatchAndWriteMiniDump_Impl( CatchAndWriteContext_t &ctx )
  340. {
  341. // we dont handle minidumps on ps3
  342. return ctx.Invoke();
  343. }
  344. #else
  345. static const char *GetExceptionCodeName( unsigned long code )
  346. {
  347. switch ( code )
  348. {
  349. case EXCEPTION_ACCESS_VIOLATION: return "accessviolation";
  350. case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "arrayboundsexceeded";
  351. case EXCEPTION_BREAKPOINT: return "breakpoint";
  352. case EXCEPTION_DATATYPE_MISALIGNMENT: return "datatypemisalignment";
  353. case EXCEPTION_FLT_DENORMAL_OPERAND: return "fltdenormaloperand";
  354. case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "fltdividebyzero";
  355. case EXCEPTION_FLT_INEXACT_RESULT: return "fltinexactresult";
  356. case EXCEPTION_FLT_INVALID_OPERATION: return "fltinvalidoperation";
  357. case EXCEPTION_FLT_OVERFLOW: return "fltoverflow";
  358. case EXCEPTION_FLT_STACK_CHECK: return "fltstackcheck";
  359. case EXCEPTION_FLT_UNDERFLOW: return "fltunderflow";
  360. case EXCEPTION_INT_DIVIDE_BY_ZERO: return "intdividebyzero";
  361. case EXCEPTION_INT_OVERFLOW: return "intoverflow";
  362. case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "noncontinuableexception";
  363. case EXCEPTION_PRIV_INSTRUCTION: return "privinstruction";
  364. case EXCEPTION_SINGLE_STEP: return "singlestep";
  365. }
  366. // Unknown exception
  367. return "crash";
  368. }
  369. int CatchAndWriteMiniDump_Impl( CatchAndWriteContext_t &ctx )
  370. {
  371. // Sorry, this is the only action currently implemented!
  372. Assert( ctx.m_eAction == k_ECatchAndWriteMiniDumpAbort );
  373. if ( Plat_IsInDebugSession() )
  374. {
  375. // don't mask exceptions when running in the debugger
  376. return ctx.Invoke();
  377. }
  378. // g_DumpHelper.Init();
  379. // Win32 code gets to use a special handler
  380. #if defined( _WIN32 )
  381. __try
  382. {
  383. return ctx.Invoke();
  384. }
  385. __except ( g_pfnWriteMiniDump( GetExceptionCode(), GetExceptionInformation(), GetExceptionCodeName( GetExceptionCode() ) ), EXCEPTION_EXECUTE_HANDLER )
  386. {
  387. TerminateProcess( GetCurrentProcess(), EXIT_FAILURE ); // die, die RIGHT NOW! (don't call exit() so destructors will not get run)
  388. }
  389. // if we get here, we definitely are not in an exception handler
  390. g_bInException = false;
  391. return 0;
  392. #else
  393. // if ( ctx.m_pargv != 0 )
  394. // {
  395. // g_DumpHelper.ComputeExeNameFromArgv0( (*ctx.m_pargv)[ 0 ] );
  396. // }
  397. //
  398. // ICrashHandler *handler = g_DumpHelper.GetHandlerAPI();
  399. // CCrashHandlerScope scope( handler, g_DumpHelper.GetProduct(), g_DumpHelper.GetVersion(), g_DumpHelper.GetBuildID(), false );
  400. // if ( handler )
  401. // handler->SetSteamID( g_DumpHelper.GetSteamID() );
  402. return ctx.Invoke();
  403. #endif
  404. }
  405. #endif // _PS3
  406. //-----------------------------------------------------------------------------
  407. // Purpose: Catches and writes out any exception throw by the specified function
  408. // Input: pfn - Function to call within protective exception block
  409. // pv - Void pointer to pass that function
  410. // eAction - Specifies what to do if it catches an exception
  411. //-----------------------------------------------------------------------------
  412. void CatchAndWriteMiniDumpEx( FnWMain pfn, int argc, tchar *argv[], ECatchAndWriteMinidumpAction eAction )
  413. {
  414. CatchAndWriteContext_t ctx;
  415. ctx.Set( k_eSCatchAndWriteFunctionTypeWMain, eAction, (void *)pfn, &argc, &argv, NULL );
  416. CatchAndWriteMiniDump_Impl( ctx );
  417. }
  418. //-----------------------------------------------------------------------------
  419. // Purpose: Catches and writes out any exception throw by the specified function
  420. // Input: pfn - Function to call within protective exception block
  421. // pv - Void pointer to pass that function
  422. // eAction - Specifies what to do if it catches an exception
  423. //-----------------------------------------------------------------------------
  424. int CatchAndWriteMiniDumpExReturnsInt( FnWMainIntRet pfn, int argc, tchar *argv[], ECatchAndWriteMinidumpAction eAction )
  425. {
  426. CatchAndWriteContext_t ctx;
  427. ctx.Set( k_eSCatchAndWriteFunctionTypeWMainIntReg, eAction, (void *)pfn, &argc, &argv, NULL );
  428. return CatchAndWriteMiniDump_Impl( ctx );
  429. }
  430. //-----------------------------------------------------------------------------
  431. // Purpose: Catches and writes out any exception throw by the specified function
  432. // Input: pfn - Function to call within protective exception block
  433. // pv - Void pointer to pass that function
  434. // eAction - Specifies what to do if it catches an exception
  435. //-----------------------------------------------------------------------------
  436. void CatchAndWriteMiniDumpExForVoidPtrFn( FnVoidPtrFn pfn, void *pv, ECatchAndWriteMinidumpAction eAction )
  437. {
  438. CatchAndWriteContext_t ctx;
  439. ctx.Set( k_eSCatchAndWriteFunctionTypeVoidPtr, eAction, (void *)pfn, NULL, NULL, &pv );
  440. CatchAndWriteMiniDump_Impl( ctx );
  441. }
  442. //-----------------------------------------------------------------------------
  443. // Purpose: Catches and writes out any exception throw by the specified function
  444. // Input: pfn - Function to call within protective exception block
  445. // pv - Void pointer to pass that function
  446. // bExitQuietly - If true (for client) just exit after mindump, with no visible error for user
  447. // If false, re-throws.
  448. //-----------------------------------------------------------------------------
  449. void CatchAndWriteMiniDumpForVoidPtrFn( FnVoidPtrFn pfn, void *pv, bool bExitQuietly )
  450. {
  451. return CatchAndWriteMiniDumpExForVoidPtrFn( pfn, pv, bExitQuietly ? k_ECatchAndWriteMiniDumpAbort : k_ECatchAndWriteMiniDumpReThrow );
  452. }
  453. /*
  454. Call this function to ensure that your program actually crashes when it crashes.
  455. Oh my god.
  456. When 64-bit Windows came out it turns out that it wasn't possible to throw
  457. and catch exceptions from user-mode, through kernel-mode, and back to user
  458. mode. Therefore, for crashes that happen in kernel callbacks such as Window
  459. procs Microsoft had to decide either to always crash when an exception
  460. is thrown (including an SEH such as an access violation) or else always silently
  461. swallow the exception.
  462. They chose badly.
  463. Therefore, for the last five or so years, programs on 64-bit Windows have been
  464. silently swallowing *some* exceptions. As a concrete example, consider this code:
  465. case WM_PAINT:
  466. {
  467. hdc = BeginPaint(hWnd, &ps);
  468. char* p = new char;
  469. *(int*)0 = 0;
  470. delete p;
  471. EndPaint(hWnd, &ps);
  472. }
  473. break;
  474. It's in a WindowProc handling a paint message so it will generally be called from
  475. kernel mode. Therefore the crash in the middle of it is, by default, 'handled' for
  476. us. The "delete p;" and EndPaint() never happen. This means that the process is
  477. left in an indeterminate state. It also means that our error reporting never sees
  478. the exception. It is effectively as though there is a __try/__except handler at the
  479. kernel boundary and any crashes cause the stack to be unwound (without destructors
  480. being run) to the kernel boundary where execution continues.
  481. Charming.
  482. The fix is to use the Get/SetProcessUserModeExceptionPolicy API to tell Windows
  483. that we don't want to struggle on after crashing.
  484. For more scary details see this article. It actually suggests using the compatibility
  485. manifest, but that does not appear to work.
  486. http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/
  487. */
  488. void EnableCrashingOnCrashes()
  489. {
  490. typedef BOOL (WINAPI *tGetProcessUserModeExceptionPolicy)(LPDWORD lpFlags);
  491. typedef BOOL (WINAPI *tSetProcessUserModeExceptionPolicy)(DWORD dwFlags);
  492. #define PROCESS_CALLBACK_FILTER_ENABLED 0x1
  493. HMODULE kernel32 = LoadLibraryA("kernel32.dll");
  494. tGetProcessUserModeExceptionPolicy pGetProcessUserModeExceptionPolicy = (tGetProcessUserModeExceptionPolicy)GetProcAddress(kernel32, "GetProcessUserModeExceptionPolicy");
  495. tSetProcessUserModeExceptionPolicy pSetProcessUserModeExceptionPolicy = (tSetProcessUserModeExceptionPolicy)GetProcAddress(kernel32, "SetProcessUserModeExceptionPolicy");
  496. if (pGetProcessUserModeExceptionPolicy && pSetProcessUserModeExceptionPolicy)
  497. {
  498. DWORD dwFlags;
  499. if (pGetProcessUserModeExceptionPolicy(&dwFlags))
  500. {
  501. pSetProcessUserModeExceptionPolicy(dwFlags & ~PROCESS_CALLBACK_FILTER_ENABLED); // turn off bit 1
  502. }
  503. }
  504. }
  505. #else
  506. PLATFORM_INTERFACE void WriteMiniDump( const char *pszFilenameSuffix )
  507. {
  508. }
  509. PLATFORM_INTERFACE void CatchAndWriteMiniDump( FnWMain pfn, int argc, tchar *argv[] )
  510. {
  511. pfn( argc, argv );
  512. }
  513. #endif
  514. #elif defined(_X360 )
  515. PLATFORM_INTERFACE void WriteMiniDump( const char *pszFilenameSuffix )
  516. {
  517. DmCrashDump(false);
  518. }
  519. #else // !_WIN32
  520. #include "tier0/minidump.h"
  521. PLATFORM_INTERFACE void WriteMiniDump( const char *pszFilenameSuffix )
  522. {
  523. }
  524. PLATFORM_INTERFACE void CatchAndWriteMiniDump( FnWMain pfn, int argc, tchar *argv[] )
  525. {
  526. pfn( argc, argv );
  527. }
  528. #endif
  529. // User minidump stream info comment strings.
  530. //
  531. // Single header string of 512 bytes set via MinidumpUserStreamInfoSetHeader.
  532. static char g_UserStreamInfoHeader[ 512 ];
  533. // Array of 32 round robin 128 byte strings set via MinidumpUserStreamInfoAppend.
  534. static char g_UserStreamInfo[ 64 ][ 128 ];
  535. static int g_UserStreamInfoIndex = 0;
  536. // Set the single g_UserStreamInfoHeader string.
  537. void MinidumpUserStreamInfoSetHeader( const char *pFormat, ... )
  538. {
  539. va_list marker;
  540. va_start( marker, pFormat );
  541. _vsnprintf( g_UserStreamInfoHeader, ARRAYSIZE( g_UserStreamInfoHeader ), pFormat, marker );
  542. g_UserStreamInfoHeader[ ARRAYSIZE( g_UserStreamInfoHeader ) - 1 ] = 0;
  543. va_end( marker );
  544. }
  545. // Set the next comment in the g_UserStreamInfo array.
  546. void MinidumpUserStreamInfoAppend( const char *pFormat, ... )
  547. {
  548. va_list marker;
  549. char *pData = g_UserStreamInfo[ g_UserStreamInfoIndex ];
  550. const int DataSize = ARRAYSIZE( g_UserStreamInfo[ g_UserStreamInfoIndex ] );
  551. // Add tick count just so we have a general idea of when this event happened.
  552. _snprintf( pData, DataSize, "[%x]", Plat_MSTime() );
  553. pData[ DataSize - 1 ] = 0;
  554. size_t HeaderLen = strlen( pData );
  555. va_start( marker, pFormat );
  556. _vsnprintf( pData + HeaderLen, DataSize - HeaderLen, pFormat, marker );
  557. pData[ DataSize - 1 ] = 0;
  558. va_end( marker );
  559. // Bump up index, and go back to 0 if we've hit the end.
  560. g_UserStreamInfoIndex++;
  561. if( g_UserStreamInfoIndex >= ARRAYSIZE( g_UserStreamInfo ) )
  562. {
  563. g_UserStreamInfoIndex = 0;
  564. }
  565. }
  566. // Retrieve the string given the Index.
  567. // Index 0: header string
  568. // Index 1+: comment string
  569. // Returns NULL when you've reached the end of the comment string array
  570. // Empty strings ("\0") can be returned if comment hasn't been set
  571. const char *MinidumpUserStreamInfoGet( int Index )
  572. {
  573. if( ( Index < 0 ) || ( Index >= (ARRAYSIZE( g_UserStreamInfo ) + 1) ) ) //+1 because we map 0 to the header
  574. return NULL;
  575. if( Index == 0 )
  576. return g_UserStreamInfoHeader;
  577. Index = ( (Index + (ARRAYSIZE( g_UserStreamInfo ) - 1)) + //subtract 1 in a way that circularly wraps. Since 0 maps to the header, the comment indices are 1 based
  578. g_UserStreamInfoIndex ) //start with our oldest comment
  579. % ARRAYSIZE( g_UserStreamInfo ); //circular buffer wrapping
  580. return g_UserStreamInfo[ Index ];
  581. }