Counter Strike : Global Offensive Source Code
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.

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