FaultInjection.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Copyright (c) ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. #include "CommonCorePch.h"
  7. #ifdef FAULT_INJECTION
  8. #include "io.h"
  9. #include "share.h"
  10. #undef DBGHELP_TRANSLATE_TCHAR
  11. #define _NO_CVCONST_H
  12. // dbghelp.h is not clean with warning 4091
  13. #pragma warning(push)
  14. #pragma warning(disable: 4091) /* warning C4091: 'typedef ': ignored on left of '' when no variable is declared */
  15. #include <dbghelp.h>
  16. #pragma warning(pop)
  17. namespace Js
  18. {
  19. #pragma region helpers
  20. #define FIDELAYLOAD(fn) static decltype(fn)* pfn##fn = nullptr
  21. FIDELAYLOAD(SymInitialize);
  22. FIDELAYLOAD(SymCleanup);
  23. FIDELAYLOAD(SymFromAddrW);
  24. FIDELAYLOAD(SymFromNameW);
  25. FIDELAYLOAD(SymEnumSymbolsW);
  26. FIDELAYLOAD(SymGetModuleInfoW64);
  27. FIDELAYLOAD(SymMatchStringW);
  28. FIDELAYLOAD(SymSetOptions);
  29. FIDELAYLOAD(MiniDumpWriteDump);
  30. FIDELAYLOAD(SymFunctionTableAccess64);
  31. FIDELAYLOAD(SymGetModuleBase64);
  32. FIDELAYLOAD(StackWalk64);
  33. #undef FIDELAYLOAD
  34. template<typename CharT>
  35. bool isEqualIgnoreCase(CharT c1, CharT c2)
  36. {
  37. return c1 == c2
  38. || ((c2 <= 'Z') && (c1 >= 'a') && (c1 - c2 == 'a' - 'A'))
  39. || ((c1 <= 'Z') && (c2 >= 'a') && (c2 - c1 == 'a' - 'A'));
  40. }
  41. template<typename CharT>
  42. CharT *stristr(const CharT * cs1,
  43. const CharT * cs2)
  44. {
  45. CharT *cp = (CharT *)cs1;
  46. CharT *s1, *s2;
  47. if (!*cs2)
  48. return (CharT *)cs1;
  49. while (*cp)
  50. {
  51. s1 = cp;
  52. s2 = (CharT *)cs2;
  53. while (*s1 && *s2 && isEqualIgnoreCase(*s1, *s2))
  54. s1++, s2++;
  55. if (!*s2)
  56. return cp;
  57. cp++;
  58. }
  59. return nullptr;
  60. }
  61. static char16* trimRight(_Inout_z_ char16* str)
  62. {
  63. auto tmp = str + wcslen(str);
  64. while (!isprint(*--tmp));
  65. *(tmp + 1) = _u('\0');
  66. return str;
  67. }
  68. static int8 const* hexTable = []()->int8*{
  69. static int8 hex[256] = { 0 };
  70. memset(hex, 0xff, 256);
  71. for (int8 i = '0'; i <= '9'; i++) hex[i] = i - '0';
  72. for (int8 i = 'a'; i <= 'f'; i++) hex[i] = i - 'a' + 10;
  73. for (int8 i = 'A'; i <= 'F'; i++) hex[i] = i - 'A' + 10;
  74. return hex;
  75. }();
  76. template<typename CharT>
  77. static UINT_PTR HexStrToAddress(const CharT* str)
  78. {
  79. UINT_PTR address = 0;
  80. while (*str == '0' || *str == '`' || *str == 'x' || *str == 'X')
  81. str++; // leading zero
  82. do
  83. {
  84. if (*str == '`') // amd64 address
  85. continue;
  86. if (hexTable[*str & 0xff] < 0)
  87. return address;
  88. address = 16 * address + hexTable[*str & 0xff];
  89. } while (*(++str));
  90. return address;
  91. }
  92. #if _M_X64
  93. // for amd64 jit frame, RtlCaptureStackBackTrace stops walking after hitting jit frame on amd64
  94. _NOINLINE
  95. WORD StackTrace64(_In_ DWORD FramesToSkip,
  96. _In_ DWORD FramesToCapture,
  97. _Out_writes_to_(FramesToCapture, return) PVOID * BackTrace,
  98. _Out_opt_ PDWORD BackTraceHash,
  99. _In_opt_ const CONTEXT* pCtx = nullptr)
  100. {
  101. CONTEXT Context;
  102. UNWIND_HISTORY_TABLE UnwindHistoryTable;
  103. PRUNTIME_FUNCTION RuntimeFunction;
  104. PVOID HandlerData;
  105. ULONG64 EstablisherFrame;
  106. ULONG64 ImageBase;
  107. ULONG Frame = 0;
  108. if (BackTraceHash)
  109. {
  110. *BackTraceHash = 0;
  111. }
  112. if (pCtx == nullptr)
  113. {
  114. RtlCaptureContext(&Context);
  115. }
  116. else
  117. {
  118. memcpy(&Context, pCtx, sizeof(CONTEXT));
  119. }
  120. RtlZeroMemory(&UnwindHistoryTable, sizeof(UNWIND_HISTORY_TABLE));
  121. while (true)
  122. {
  123. RuntimeFunction = RtlLookupFunctionEntry(Context.Rip, &ImageBase, &UnwindHistoryTable);
  124. if (!RuntimeFunction)
  125. {
  126. Context.Rip = (ULONG64)(*(PULONG64)Context.Rsp);
  127. Context.Rsp += 8;
  128. }
  129. else
  130. {
  131. RtlVirtualUnwind(UNW_FLAG_NHANDLER, ImageBase, Context.Rip, RuntimeFunction,
  132. &Context, &HandlerData, &EstablisherFrame, NULL /* ContextPointers */);
  133. }
  134. if (!Context.Rip)
  135. {
  136. break;
  137. }
  138. if (FramesToSkip > 0)
  139. {
  140. FramesToSkip--;
  141. continue;
  142. }
  143. if (Frame >= FramesToCapture)
  144. {
  145. break;
  146. }
  147. BackTrace[Frame] = (PVOID)Context.Rip;
  148. if (BackTraceHash)
  149. {
  150. *BackTraceHash += (Context.Rip & 0xffffffff);
  151. }
  152. Frame++;
  153. }
  154. return (WORD)Frame;
  155. }
  156. #define CaptureStack(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash) \
  157. StackTrace64(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash)
  158. #elif defined (_M_IX86)
  159. #pragma optimize( "g", off )
  160. #pragma warning( push )
  161. #pragma warning( disable : 4748 )
  162. #pragma warning( disable : 4995 )
  163. WORD StackTrace86(
  164. _In_ DWORD FramesToSkip,
  165. _In_ DWORD FramesToCapture,
  166. _Out_writes_to_(FramesToCapture, return) PVOID * BackTrace,
  167. _Inout_opt_ PDWORD BackTraceHash,
  168. __in_opt CONST PCONTEXT InitialContext = NULL
  169. )
  170. {
  171. _Analysis_assume_(FramesToSkip >= 0);
  172. _Analysis_assume_(FramesToCapture >= 0);
  173. DWORD MachineType;
  174. CONTEXT Context;
  175. STACKFRAME64 StackFrame;
  176. if (InitialContext == NULL)
  177. {
  178. //RtlCaptureContext( &Context );
  179. ZeroMemory(&Context, sizeof(CONTEXT));
  180. Context.ContextFlags = CONTEXT_CONTROL;
  181. __asm
  182. {
  183. Label:
  184. mov[Context.Ebp], ebp;
  185. mov[Context.Esp], esp;
  186. mov eax, [Label];
  187. mov[Context.Eip], eax;
  188. }
  189. }
  190. else
  191. {
  192. CopyMemory(&Context, InitialContext, sizeof(CONTEXT));
  193. }
  194. ZeroMemory(&StackFrame, sizeof(STACKFRAME64));
  195. MachineType = IMAGE_FILE_MACHINE_I386;
  196. StackFrame.AddrPC.Offset = Context.Eip;
  197. StackFrame.AddrPC.Mode = AddrModeFlat;
  198. StackFrame.AddrFrame.Offset = Context.Ebp;
  199. StackFrame.AddrFrame.Mode = AddrModeFlat;
  200. StackFrame.AddrStack.Offset = Context.Esp;
  201. StackFrame.AddrStack.Mode = AddrModeFlat;
  202. WORD FrameCount = 0;
  203. while (FrameCount < FramesToSkip + FramesToCapture)
  204. {
  205. if (!pfnStackWalk64(MachineType, GetCurrentProcess(), GetCurrentThread(), &StackFrame,
  206. NULL, NULL, pfnSymFunctionTableAccess64, pfnSymGetModuleBase64, NULL))
  207. {
  208. break;
  209. }
  210. if (StackFrame.AddrPC.Offset != 0)
  211. {
  212. if (FrameCount >= FramesToSkip)
  213. {
  214. #pragma warning(suppress: 22102)
  215. #pragma warning(suppress: 26014)
  216. BackTrace[FrameCount - FramesToSkip] = (PVOID)StackFrame.AddrPC.Offset;
  217. if (BackTraceHash)
  218. {
  219. *BackTraceHash += (StackFrame.AddrPC.Offset & 0xffffffff);
  220. }
  221. }
  222. FrameCount++;
  223. }
  224. else
  225. {
  226. break;
  227. }
  228. }
  229. if (FrameCount > FramesToSkip)
  230. {
  231. return (WORD)(FrameCount - FramesToSkip);
  232. }
  233. else
  234. {
  235. return 0;
  236. }
  237. }
  238. #pragma warning( pop )
  239. #pragma optimize( "", on )
  240. #define CaptureStack(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash) \
  241. RtlCaptureStackBackTrace(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash)
  242. #else
  243. #define CaptureStack(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash) \
  244. RtlCaptureStackBackTrace(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash)
  245. #endif
  246. struct SymbolInfoPackage : public SYMBOL_INFO_PACKAGEW
  247. {
  248. SymbolInfoPackage() { Init(); }
  249. void Init()
  250. {
  251. si.SizeOfStruct = sizeof(SYMBOL_INFOW);
  252. si.MaxNameLen = sizeof(name);
  253. }
  254. };
  255. struct ModuleInfo : public IMAGEHLP_MODULEW64
  256. {
  257. ModuleInfo() { Init(); }
  258. void Init()
  259. {
  260. SizeOfStruct = sizeof(IMAGEHLP_MODULEW64);
  261. }
  262. };
  263. bool FaultInjection::InitializeSym()
  264. {
  265. if (symInitialized)
  266. {
  267. return true;
  268. }
  269. // load dbghelp APIs
  270. if (hDbgHelp == NULL)
  271. {
  272. hDbgHelp = LoadLibraryEx(_u("dbghelp.dll"), 0, 0);
  273. }
  274. if (hDbgHelp == NULL)
  275. {
  276. fwprintf(stderr, _u("Failed to load dbghelp.dll for stack walking, gle=0x%08x\n"), GetLastError());
  277. fflush(stderr);
  278. return false;
  279. }
  280. #define FIDELAYLOAD(fn) pfn##fn = (decltype(fn)*)GetProcAddress(hDbgHelp, #fn); \
  281. if (pfn##fn == nullptr){\
  282. fwprintf(stderr, _u("Failed to load sigs:%s\n"), _u(#fn)); \
  283. fflush(stderr); \
  284. return false; \
  285. }
  286. FIDELAYLOAD(SymInitialize);
  287. FIDELAYLOAD(SymCleanup);
  288. FIDELAYLOAD(SymFromAddrW);
  289. FIDELAYLOAD(SymFromNameW);
  290. FIDELAYLOAD(SymEnumSymbolsW);
  291. FIDELAYLOAD(SymGetModuleInfoW64);
  292. FIDELAYLOAD(SymMatchStringW);
  293. FIDELAYLOAD(SymSetOptions);
  294. FIDELAYLOAD(MiniDumpWriteDump);
  295. FIDELAYLOAD(SymFunctionTableAccess64);
  296. FIDELAYLOAD(SymGetModuleBase64);
  297. FIDELAYLOAD(StackWalk64);
  298. #undef FIDELAYLOAD
  299. // TODO: StackBackTrace.cpp also call SymInitialize, but this can only be called once before cleanup
  300. if (!pfnSymInitialize(GetCurrentProcess(), NULL, TRUE))
  301. {
  302. fwprintf(stderr, _u("SymInitialize failed, gle=0x%08x\n"), GetLastError());
  303. fflush(stderr);
  304. return false;
  305. }
  306. symInitialized = true;
  307. return true;
  308. }
  309. #pragma endregion helpers
  310. FaultInjection FaultInjection::Global;
  311. static CriticalSection cs_Sym; // for Sym* method is not thread safe
  312. const auto& globalFlags = Js::Configuration::Global.flags;
  313. PVOID FaultInjection::vectoredExceptionHandler = nullptr;
  314. DWORD FaultInjection::exceptionFilterRemovalLastError = 0;
  315. THREAD_LOCAL int(*Js::FaultInjection::pfnHandleAV)(int, PEXCEPTION_POINTERS) = nullptr;
  316. static SymbolInfoPackage sip;
  317. static ModuleInfo mi;
  318. const char16* crashStackStart = _u("=====Callstack for this exception=======\n");
  319. const char16* crashStackEnd = _u("=====End of callstack for this exception=======\n");
  320. const char16* injectionStackStart = _u("=====Fault injecting record=====\n");
  321. const char16* injectionStackEnd = _u("=====End of Fault injecting record=====\n");
  322. typedef struct _RANGE{
  323. UINT_PTR startAddress;
  324. UINT_PTR endAddress;
  325. }RANGE, *PRANGE;
  326. typedef struct _FUNCTION_SIGNATURES
  327. {
  328. int count;
  329. RANGE signatures[ANYSIZE_ARRAY];
  330. } FUNCTION_SIGNATURES, *PFUNCTION_SIGNATURES;
  331. // function address ranges of each signature
  332. // use for faster address matching instead of symbol table lookup when reproducing
  333. PFUNCTION_SIGNATURES baselineFuncSigs[FaultInjection::MAX_FRAME_COUNT] = { 0 };
  334. // record hit count of each frame when Faults are injected.
  335. unsigned int stackMatchRank[FaultInjection::MAX_FRAME_COUNT] = { 0 };
  336. #define FAULT_TYPE(x) _u(#x),\
  337. const char16 *FaultInjection::FaultTypeNames[] =
  338. {
  339. #include "FaultTypes.h"
  340. };
  341. #undef FAULT_TYPE
  342. static_assert(sizeof(FaultInjection::FaultTypeNames) == FaultInjection::FaultType::FaultTypeCount*sizeof(char16*),
  343. "FaultTypeNames count is wrong");
  344. void FaultInjection::FaultInjectionTypes::EnableType(FaultType type)
  345. {
  346. Assert(type >= 0 && type < FaultType::FaultTypeCount);
  347. setBit(type, 1);
  348. }
  349. bool FaultInjection::FaultInjectionTypes::IsEnabled(FaultType type)
  350. {
  351. Assert(type >= 0 && type < FaultType::FaultTypeCount);
  352. return getBit(type) == 0x1;
  353. }
  354. bool FaultInjection::FaultInjectionTypes::IsEnabled(const char16* name)
  355. {
  356. for (int type = 0; type < FaultType::FaultTypeCount; type++)
  357. {
  358. if (wcscmp(FaultTypeNames[type], name) == 0)
  359. return getBit(type) == 0x1;
  360. }
  361. AssertMsg(false, "Unknown fault type name");
  362. return false;
  363. }
  364. FaultInjection::FaultInjection()
  365. {
  366. stackMatchInitialized = Uninitialized;
  367. countOfInjectionPoints = 0;
  368. hDbgHelp = NULL;
  369. InjectionFirstRecord = nullptr;
  370. InjectionLastRecordRef = &InjectionFirstRecord;
  371. InjectionRecordsCount = 0;
  372. FaultInjectionCookie = 0;
  373. baselineFrameCount = 0;
  374. stackHashOfAllInjectionPointsSize = 256;
  375. stackHashOfAllInjectionPoints = (ULONG_PTR*)malloc(stackHashOfAllInjectionPointsSize*sizeof(ULONG_PTR));
  376. faultInjectionTypes = nullptr;
  377. symInitialized = false;
  378. for (int i = 0; i < MAX_FRAME_COUNT; i++)
  379. {
  380. baselineStack[i] = nullptr;
  381. baselineAddresses[i] = 0;
  382. }
  383. }
  384. FaultInjection::~FaultInjection()
  385. {
  386. RemoveExceptionFilters();
  387. // when fault injection count only is passing from jscript.config(in case of running on 3rd part host)
  388. // and the host don't have code to output the fault injection count, we still able to do the fault injection test
  389. if (globalFlags.FaultInjection == FaultMode::CountOnly
  390. || globalFlags.FaultInjection == FaultMode::StackMatchCountOnly)
  391. {
  392. fprintf(stderr, "FaultInjection - Total Allocation Count:%u\n", countOfInjectionPoints);
  393. fflush(stderr);
  394. FILE *fp;
  395. char countFileName[64];
  396. sprintf_s(countFileName, "ChakraFaultInjectionCount_%u.txt", GetCurrentProcessId());
  397. if (fopen_s(&fp, countFileName, "w") == 0)
  398. {
  399. fprintf(fp, "FaultInjection - Total Allocation Count:%u\n", countOfInjectionPoints);
  400. fflush(fp);
  401. fclose(fp);
  402. }
  403. for (int i = 0; i < MAX_FRAME_COUNT; i++)
  404. {
  405. if (stackMatchRank[i] == 0)
  406. {
  407. break;
  408. }
  409. fwprintf(stderr, _u("FaultInjection stack matching rank %d: %u\n"), i + 1, stackMatchRank[i]);
  410. }
  411. fflush(stderr);
  412. }
  413. if (globalFlags.FaultInjection == StackHashCountOnly)
  414. {
  415. FILE *fp;
  416. if (fopen_s(&fp, "ChakraFaultInjectionHashes.txt", "w") == 0)
  417. {
  418. for (uint i = 0; i < countOfInjectionPoints; i++)
  419. {
  420. fprintf(fp, "%p\n", (void*)stackHashOfAllInjectionPoints[i]);
  421. }
  422. fflush(fp);
  423. fclose(fp);
  424. }
  425. }
  426. free(stackHashOfAllInjectionPoints);
  427. stackHashOfAllInjectionPoints = nullptr;
  428. if (globalFlags.FaultInjection == FaultMode::DisplayAvailableFaultTypes)
  429. {
  430. Output::Print(_u("Available Fault Types:\n"));
  431. for (int i = 0; i < FaultType::FaultTypeCount; i++)
  432. {
  433. Output::Print(_u("%d-%s\n"), i, FaultTypeNames[i]);
  434. }
  435. Output::Flush();
  436. }
  437. InjectionRecord* head = InjectionFirstRecord;
  438. while (head != nullptr)
  439. {
  440. InjectionRecord* next = head->next;
  441. if (head->StackData)
  442. {
  443. free(head->StackData);
  444. }
  445. free(head);
  446. head = next;
  447. }
  448. for (int i = 0; i < MAX_FRAME_COUNT; i++)
  449. {
  450. if (baselineStack[i])
  451. {
  452. free(baselineStack[i]);
  453. }
  454. if (baselineFuncSigs[i])
  455. {
  456. free(baselineFuncSigs[i]);
  457. }
  458. }
  459. if (stackMatchInitialized == Succeeded)
  460. {
  461. pfnSymCleanup(GetCurrentProcess());
  462. }
  463. if (hDbgHelp)
  464. {
  465. FreeLibrary(hDbgHelp);
  466. }
  467. if (faultInjectionTypes)
  468. {
  469. faultInjectionTypes->~FaultInjectionTypes();
  470. NoCheckHeapDelete(faultInjectionTypes);
  471. }
  472. }
  473. bool FaultInjection::IsFaultEnabled(FaultType faultType)
  474. {
  475. if (!faultInjectionTypes)
  476. {
  477. faultInjectionTypes = NoCheckHeapNew(FaultInjectionTypes);
  478. if ((const char16*)globalFlags.FaultInjectionType == nullptr)
  479. {
  480. // no -FaultInjectionType specified, inject all
  481. faultInjectionTypes->EnableAll();
  482. }
  483. else
  484. {
  485. ParseFaultTypes(globalFlags.FaultInjectionType);
  486. }
  487. }
  488. return faultInjectionTypes->IsEnabled(faultType);
  489. }
  490. bool FaultInjection::IsFaultInjectionOn(FaultType faultType)
  491. {
  492. return globalFlags.FaultInjection >= 0 //-FaultInjection switch
  493. && IsFaultEnabled(faultType);
  494. }
  495. void FaultInjection::ParseFaultTypes(const char16* szFaultTypes)
  496. {
  497. auto charCount = wcslen(szFaultTypes) + 1;
  498. char16* szTypes = (char16*)malloc(charCount*sizeof(char16));
  499. AssertMsg(szTypes, "OOM in FaultInjection Infra");
  500. wcscpy_s(szTypes, charCount, szFaultTypes);
  501. const char16* delims = _u(",");
  502. char16 *nextTok = nullptr;
  503. char16* tok = wcstok_s(szTypes, delims, &nextTok);
  504. while (tok != NULL)
  505. {
  506. if (wcslen(tok) > 0)
  507. {
  508. if (iswdigit(tok[0]))
  509. {
  510. auto numType = _wtoi(tok);
  511. for (int i = 0; i< FaultType::FaultTypeCount; i++)
  512. {
  513. if (numType & (1 << i))
  514. {
  515. faultInjectionTypes->EnableType(i);
  516. }
  517. }
  518. }
  519. else if (tok[0] == _u('#'))
  520. {
  521. // FaultInjectionType:#1-4,#6 format, not flags
  522. auto tok1 = tok + 1;
  523. if (wcslen(tok1)>0 && iswdigit(tok1[0]))
  524. {
  525. char16* pDash = wcschr(tok1, _u('-'));
  526. if (pDash)
  527. {
  528. for (int i = _wtoi(tok1); i <= _wtoi(pDash + 1); i++)
  529. {
  530. faultInjectionTypes->EnableType(i);
  531. }
  532. }
  533. else
  534. {
  535. faultInjectionTypes->EnableType(_wtoi(tok1));
  536. }
  537. }
  538. }
  539. else
  540. {
  541. for (int i = 0; i < FaultType::FaultTypeCount; i++)
  542. {
  543. if (_wcsicmp(FaultTypeNames[i], tok) == 0)
  544. {
  545. faultInjectionTypes->EnableType(i);
  546. break;
  547. }
  548. }
  549. }
  550. }
  551. tok = wcstok_s(NULL, delims, &nextTok);
  552. }
  553. free(szTypes);
  554. }
  555. static void SmashLambda(_Inout_z_ char16* str)
  556. {
  557. //jscript9test!<lambda_dc7f9e8c591f1832700d6567e43faa6c>::operator()
  558. const char16 lambdaSig[] = _u("<lambda_");
  559. const int lambdaSigLen = (int)wcslen(lambdaSig);
  560. auto temp = str;
  561. while (temp != nullptr)
  562. {
  563. auto lambdaStart = wcsstr(temp, lambdaSig);
  564. temp = nullptr;
  565. if (lambdaStart != nullptr)
  566. {
  567. auto lambdaEnd = wcschr(lambdaStart, _u('>'));
  568. temp = lambdaEnd;
  569. if (lambdaEnd != nullptr && lambdaEnd - lambdaStart == lambdaSigLen + 32)
  570. {
  571. lambdaStart += lambdaSigLen;
  572. while (lambdaStart < lambdaEnd)
  573. {
  574. *(lambdaStart++) = _u('?');
  575. }
  576. }
  577. }
  578. }
  579. }
  580. bool FaultInjection::EnsureStackMatchInfraInitialized()
  581. {
  582. if (stackMatchInitialized == Succeeded)
  583. {
  584. return true;
  585. }
  586. else if (stackMatchInitialized == FailedToInitialize)
  587. {
  588. // previous try to initialize and failed
  589. return false;
  590. }
  591. else if (stackMatchInitialized == Uninitialized)
  592. {
  593. stackMatchInitialized = FailedToInitialize; //tried
  594. if (!InitializeSym())
  595. {
  596. return false;
  597. }
  598. // read baseline stack file
  599. FILE *fp = nullptr;
  600. const char16 *stackFile = globalFlags.FaultInjectionStackFile;//default: _u("stack.txt");
  601. auto err = _wfopen_s(&fp, stackFile, _u("r"));
  602. if (err != 0 || fp == nullptr)
  603. {
  604. fwprintf(stderr, _u("Failed to load %s, gle=0x%08x\n"), stackFile, GetLastError());
  605. fflush(stderr);
  606. return false;
  607. }
  608. char16 buffer[MAX_SYM_NAME]; // assume the file is normal
  609. unsigned int maxLineCount =
  610. (globalFlags.FaultInjectionStackLineCount < 0
  611. || globalFlags.FaultInjectionStackLineCount > MAX_FRAME_COUNT
  612. || globalFlags.FaultInjection == FaultMode::StackMatchCountOnly)
  613. ? MAX_FRAME_COUNT : globalFlags.FaultInjectionStackLineCount;
  614. while (fgetws(buffer, MAX_SYM_NAME, fp))
  615. {
  616. if (wcscmp(buffer, injectionStackStart) == 0)
  617. {
  618. baselineFrameCount = 0;
  619. continue;
  620. }
  621. if (baselineFrameCount >= maxLineCount)
  622. {
  623. continue; // don't break because we can hit the start marker and reset
  624. }
  625. const char16 jscript9test[] = _u("jscript9test!");
  626. const char16 jscript9[] = _u("jscript9!");
  627. char16* symbolStart = stristr(buffer, jscript9test);
  628. if (symbolStart == nullptr)
  629. {
  630. symbolStart = stristr(buffer, jscript9);
  631. }
  632. if (symbolStart == nullptr)
  633. {
  634. continue;// no "jscript9test!", skip this line
  635. }
  636. if (wcsstr(symbolStart, _u("Js::FaultInjection")) != NULL)
  637. { // skip faultinjection infra frames.
  638. continue;
  639. }
  640. auto plus = wcschr(symbolStart, _u('+'));
  641. if (plus)
  642. {
  643. *plus = _u('\0');
  644. }
  645. else
  646. {
  647. trimRight(symbolStart);
  648. }
  649. SmashLambda(symbolStart);
  650. size_t len = wcslen(symbolStart);
  651. if (baselineStack[baselineFrameCount] == nullptr)
  652. {
  653. baselineStack[baselineFrameCount] = (char16*)malloc((len + 1)*sizeof(char16));
  654. AssertMsg(baselineStack[baselineFrameCount], "OOM in FaultInjection Infra");
  655. }
  656. else
  657. {
  658. auto tmp = (char16*)realloc(baselineStack[baselineFrameCount], (len + 1)*sizeof(char16));
  659. AssertMsg(tmp, "OOM in FaultInjection Infra");
  660. baselineStack[baselineFrameCount] = tmp;
  661. }
  662. wcscpy_s(baselineStack[baselineFrameCount], len + 1, symbolStart);
  663. baselineFrameCount++;
  664. }
  665. fclose(fp);
  666. OutputDebugString(_u("Fault will be injected when hit following stack:\n"));
  667. for (uint i = 0; i<baselineFrameCount; i++)
  668. {
  669. OutputDebugString(baselineStack[i]);
  670. OutputDebugString(_u("\n"));
  671. if (wcschr(baselineStack[i], '*') != nullptr || wcschr(baselineStack[i], '?') != nullptr)
  672. {
  673. continue; // there's wildcard in this line, don't use address matching
  674. }
  675. // enum symbols, if succeed we compare with address when doing stack matching
  676. pfnSymEnumSymbolsW(GetCurrentProcess(), 0, baselineStack[i],
  677. [](_In_ PSYMBOL_INFOW pSymInfo, _In_ ULONG SymbolSize, _In_opt_ PVOID UserContext)->BOOL
  678. {
  679. Assert(UserContext != nullptr); // did passed in the user context
  680. if (pSymInfo->Size > 0)
  681. {
  682. PFUNCTION_SIGNATURES* sigs = (PFUNCTION_SIGNATURES*)UserContext;
  683. int count = (*sigs) == nullptr ? 0 : (*sigs)->count;
  684. auto tmp = (PFUNCTION_SIGNATURES)realloc(*sigs, sizeof(FUNCTION_SIGNATURES) + count*sizeof(RANGE));
  685. AssertMsg(tmp, "OOM when allocating for FaultInjection Stack matching objects");
  686. *sigs = tmp;
  687. (*sigs)->count = count;
  688. (*sigs)->signatures[count].startAddress = (UINT_PTR)pSymInfo->Address;
  689. (*sigs)->signatures[count].endAddress = (UINT_PTR)(pSymInfo->Address + pSymInfo->Size);
  690. (*sigs)->count++;
  691. }
  692. return TRUE;
  693. }, &baselineFuncSigs[i]);
  694. }
  695. stackMatchInitialized = Succeeded; // initialized
  696. return true;
  697. }
  698. return false;
  699. }
  700. bool FaultInjection::IsCurrentStackMatch()
  701. {
  702. AutoCriticalSection autocs(&cs_Sym); // sym* API is thread unsafe
  703. if (!EnsureStackMatchInfraInitialized())
  704. {
  705. return false;
  706. }
  707. DWORD64 dwSymDisplacement = 0;
  708. auto hProcess = GetCurrentProcess();
  709. static void* framesBuffer[FaultInjection::MAX_FRAME_COUNT];
  710. auto frameCount = CaptureStack(0, MAX_FRAME_COUNT, framesBuffer, 0);
  711. uint n = 0;
  712. for (uint i = 0; i < frameCount; i++)
  713. {
  714. if (n >= baselineFrameCount)
  715. {
  716. return true;
  717. }
  718. if (!AutoSystemInfo::Data.IsJscriptModulePointer(framesBuffer[i]))
  719. { // skip non-Chakra frame
  720. continue;
  721. }
  722. bool match = false;
  723. if (baselineFuncSigs[n] != nullptr)
  724. {
  725. for (int j = 0; j<baselineFuncSigs[n]->count; j++)
  726. {
  727. match = baselineFuncSigs[n]->signatures[j].startAddress <= (UINT_PTR)framesBuffer[i]
  728. && (UINT_PTR)framesBuffer[i] < baselineFuncSigs[n]->signatures[j].endAddress;
  729. if (match)
  730. {
  731. break;
  732. }
  733. }
  734. }
  735. else
  736. {
  737. // fallback to symbol name matching
  738. sip.Init();
  739. if (!pfnSymFromAddrW(hProcess, (DWORD64)framesBuffer[i], &dwSymDisplacement, &sip.si))
  740. {
  741. continue;
  742. }
  743. SmashLambda(sip.si.Name);
  744. // Only search sigs name, can use wildcard in baseline file
  745. match = stristr(baselineStack[n], sip.si.Name) != nullptr
  746. || pfnSymMatchStringW(sip.si.Name, baselineStack[n], false);// wildcard
  747. }
  748. if (match)
  749. {
  750. stackMatchRank[n]++;
  751. if (n == 0)
  752. {
  753. n++;
  754. continue;
  755. }
  756. }
  757. else if (n > 0)
  758. {
  759. return false;
  760. }
  761. // First line in baseline is found, moving forward.
  762. if (n > 0)
  763. {
  764. n++;
  765. }
  766. }
  767. return false;
  768. }
  769. static bool faultInjectionDebug = false;
  770. static bool triedToInstallExceptionFilter = false;
  771. static CriticalSection csFautInjection;
  772. void FaultInjection::InstallExceptionFilters()
  773. {
  774. if (triedToInstallExceptionFilter)
  775. {
  776. return;
  777. }
  778. AutoCriticalSection autoCS(&csFautInjection);
  779. if (triedToInstallExceptionFilter)
  780. {
  781. return;
  782. }
  783. triedToInstallExceptionFilter = true;
  784. if (GetEnvironmentVariable(_u("FAULTINJECTION_DEBUG"), nullptr, 0) != 0)
  785. {
  786. faultInjectionDebug = true;
  787. }
  788. if (globalFlags.FaultInjection >= 0)
  789. {
  790. // initialize symbol system here instead of inside the exception filter
  791. // because some hard stack overflow can happen in SymInitialize
  792. // when the exception filter is handling stack overflow exception
  793. if (!FaultInjection::Global.InitializeSym())
  794. {
  795. return;
  796. }
  797. //C28725: Use Watson instead of this SetUnhandledExceptionFilter.
  798. #pragma prefast(suppress: 28725)
  799. SetUnhandledExceptionFilter([](_In_ struct _EXCEPTION_POINTERS *ExceptionInfo)->LONG
  800. {
  801. return FaultInjectionExceptionFilter(ExceptionInfo);
  802. });
  803. vectoredExceptionHandler = AddVectoredExceptionHandler(0, [](_In_ struct _EXCEPTION_POINTERS *ExceptionInfo)->LONG
  804. {
  805. switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
  806. {
  807. // selected fatal exceptions:
  808. case STATUS_ACCESS_VIOLATION:
  809. {
  810. if (pfnHandleAV
  811. && pfnHandleAV(ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo) == EXCEPTION_CONTINUE_EXECUTION)
  812. {
  813. return EXCEPTION_CONTINUE_EXECUTION;
  814. }
  815. }
  816. case STATUS_ASSERTION_FAILURE:
  817. case STATUS_STACK_OVERFLOW:
  818. FaultInjectionExceptionFilter(ExceptionInfo);
  819. TerminateProcess(::GetCurrentProcess(), ExceptionInfo->ExceptionRecord->ExceptionCode);
  820. default:
  821. return EXCEPTION_CONTINUE_SEARCH;
  822. }
  823. });
  824. }
  825. }
  826. void FaultInjection::RemoveExceptionFilters()
  827. {
  828. //C28725: Use Watson instead of this SetUnhandledExceptionFilter.
  829. #pragma prefast(suppress: 28725)
  830. SetUnhandledExceptionFilter(nullptr);
  831. if (vectoredExceptionHandler != nullptr)
  832. {
  833. RemoveVectoredExceptionHandler(vectoredExceptionHandler);
  834. // remove the handler from the list second time.
  835. // This code is called inside an exception handler, when the exception handler is called,
  836. // the refcount of the handler in ntdll!LdrpVectorHandlerList is increased,
  837. // so need to call RemoveVectoredExceptionHandler twice to really remove the handler from the list
  838. // otherwise the exception from the handler itself will re-enter the handler
  839. RemoveVectoredExceptionHandler(vectoredExceptionHandler);
  840. vectoredExceptionHandler = nullptr;
  841. }
  842. }
  843. // Calculate stack hash by adding the addresses (only jscript9 frames)
  844. UINT_PTR FaultInjection::CalculateStackHash(void* frames[], WORD frameCount, WORD framesToSkip)
  845. {
  846. UINT_PTR hash = 0;
  847. for (int i = framesToSkip; i < frameCount; i++)
  848. {
  849. if (AutoSystemInfo::Data.IsJscriptModulePointer(frames[i]))
  850. {
  851. hash += (UINT_PTR)frames[i] - AutoSystemInfo::Data.dllLoadAddress;
  852. }
  853. }
  854. return hash;
  855. }
  856. // save the stack data for dump debugging use
  857. // to get list of fault injection points:
  858. // !list -t jscript9test!Js::FaultInjection::InjectionRecord.next -e -x "dps @$extret @$extret+0x128" poi(@@c++(&jscript9test!Js::FaultInjection::Global.InjectionFirstRecord))
  859. // to rebuild the stack (locals are available)
  860. // .cxr @@C++(&jscript9test!Js::FaultInjection::Global.InjectionFirstRecord->Context)
  861. _NOINLINE void FaultInjection::dumpCurrentStackData(LPCWSTR name /*= nullptr*/, size_t size /*= 0*/)
  862. {
  863. #if !defined(_M_ARM32_OR_ARM64)
  864. static bool keepBreak = true; // for disabling following breakpoint by editing the value
  865. if (keepBreak && IsDebuggerPresent())
  866. {
  867. DebugBreak();
  868. }
  869. InjectionRecord* record = (InjectionRecord*)malloc(sizeof(InjectionRecord));
  870. if (record == nullptr) return;
  871. ZeroMemory(record, sizeof(InjectionRecord));
  872. auto _stackbasepointer = ((PNT_TIB)NtCurrentTeb())->StackBase;
  873. // context
  874. RtlCaptureContext(&record->Context);
  875. #if _M_X64
  876. auto& _stackpointer = record->Context.Rsp;
  877. auto& _basepointer = record->Context.Rbp;
  878. #elif _M_IX86
  879. auto& _stackpointer = record->Context.Esp;
  880. auto& _basepointer = record->Context.Ebp;
  881. #endif
  882. typedef decltype(_stackpointer) spType;
  883. record->StackDataLength = (spType)_stackbasepointer - _stackpointer;
  884. record->StackData = malloc(record->StackDataLength);
  885. if (record->StackData)
  886. {
  887. memcpy(record->StackData, (void*)_stackpointer, record->StackDataLength);
  888. _basepointer = _basepointer + (spType)record->StackData - _stackpointer;
  889. _stackpointer = (spType)record->StackData; // for .cxr switching to this state
  890. }
  891. if (name)
  892. {
  893. wcscpy_s(record->name, name);
  894. }
  895. record->allocSize = size;
  896. // stack frames
  897. record->FrameCount = CaptureStack(0, MAX_FRAME_COUNT, record->StackFrames, 0);
  898. // hash
  899. record->hash = CalculateStackHash(record->StackFrames, record->FrameCount, 2);
  900. fwprintf(stderr, _u("***FI: Fault Injected, StackHash:%p\n"), (void*)record->hash);
  901. fflush(stderr);
  902. *InjectionLastRecordRef = record;
  903. InjectionLastRecordRef = &record->next;
  904. InjectionRecordsCount++;
  905. #endif // _M_ARM || _M_ARM64
  906. }
  907. bool FaultInjection::ShouldInjectFault(FaultType fType, LPCWSTR name, size_t size)
  908. {
  909. bool shouldInjectionFault = ShouldInjectFaultHelper(fType, name, size);
  910. if (shouldInjectionFault && fType != FaultType::ScriptTerminationOnDispose)
  911. {
  912. dumpCurrentStackData(name, size);
  913. }
  914. return shouldInjectionFault;
  915. }
  916. bool FaultInjection::ShouldInjectFaultHelper(FaultType fType, LPCWSTR name, size_t size)
  917. {
  918. if (globalFlags.FaultInjection < 0)
  919. {
  920. return false; // no -FaultInjection switch
  921. }
  922. if (globalFlags.FaultInjectionFilter && _wcsicmp(globalFlags.FaultInjectionFilter, name) != 0)
  923. {
  924. return false;
  925. }
  926. if (globalFlags.FaultInjectionAllocSize >= 0 && size != (size_t)globalFlags.FaultInjectionAllocSize)
  927. {
  928. return false;
  929. }
  930. // install exception filter to smart dump for faultinjection
  931. // when reproducing in debugger, only let debugger catch the exception
  932. // can't do this in ctor because the global flags are not initialized yet
  933. InstallExceptionFilters();
  934. bool validInjectionPoint = IsFaultEnabled(fType);
  935. if (!validInjectionPoint)
  936. {
  937. return false;
  938. }
  939. bool shouldInjectionFault = false;
  940. switch (globalFlags.FaultInjection)
  941. {
  942. case CountEquals:
  943. //Fault inject on count only when equal
  944. if (countOfInjectionPoints == (uint)globalFlags.FaultInjectionCount)
  945. {
  946. shouldInjectionFault = true;
  947. }
  948. break;
  949. case CountEqualsOrAbove:
  950. //Fault inject on count greater than or equal
  951. if (countOfInjectionPoints >= (uint)globalFlags.FaultInjectionCount)
  952. {
  953. shouldInjectionFault = true;
  954. }
  955. break;
  956. case StackMatch:
  957. // We don't care about the fault if we already passed in terms of count, or the stack doesn't match
  958. if (countOfInjectionPoints > (uint)globalFlags.FaultInjectionCount || !IsCurrentStackMatch())
  959. {
  960. validInjectionPoint = false;
  961. }
  962. else // otherwise determine if we will be injecting this time around
  963. {
  964. shouldInjectionFault = countOfInjectionPoints == (uint)globalFlags.FaultInjectionCount || globalFlags.FaultInjectionCount == -1;
  965. }
  966. break;
  967. case StackMatchCountOnly:
  968. validInjectionPoint = IsCurrentStackMatch();
  969. break;
  970. case StackHashCountOnly:
  971. {
  972. // extend the storage when necessary
  973. if (countOfInjectionPoints > stackHashOfAllInjectionPointsSize)
  974. {
  975. stackHashOfAllInjectionPointsSize += 1024;
  976. auto extended = (ULONG_PTR*)realloc(stackHashOfAllInjectionPoints,
  977. stackHashOfAllInjectionPointsSize*sizeof(ULONG_PTR));
  978. AssertMsg(extended, "OOM in FaultInjection Infra");
  979. stackHashOfAllInjectionPoints = extended;
  980. }
  981. void* StackFrames[MAX_FRAME_COUNT];
  982. auto FrameCount = CaptureStack(0, MAX_FRAME_COUNT, StackFrames, 0);
  983. UINT_PTR hash = CalculateStackHash(StackFrames, FrameCount, 2);
  984. stackHashOfAllInjectionPoints[countOfInjectionPoints] = hash;
  985. break;
  986. }
  987. case CountOnly:
  988. break;
  989. case DisplayAvailableFaultTypes:
  990. case InstallExceptionHandlerOnly:
  991. return false;
  992. default:
  993. AssertMsg(false, "Invalid FaultInjection mode");
  994. break;
  995. }
  996. if (validInjectionPoint)
  997. {
  998. countOfInjectionPoints++;
  999. }
  1000. // try to lookup stack hash, to see if it matches
  1001. if (!shouldInjectionFault)
  1002. {
  1003. const UINT_PTR expectedHash = HexStrToAddress((LPCWSTR)globalFlags.FaultInjectionStackHash);
  1004. if (expectedHash != 0)
  1005. {
  1006. void* StackFrames[MAX_FRAME_COUNT];
  1007. auto FrameCount = CaptureStack(0, MAX_FRAME_COUNT, StackFrames, 0);
  1008. UINT_PTR hash = CalculateStackHash(StackFrames, FrameCount, 2);
  1009. if (hash == expectedHash)
  1010. {
  1011. shouldInjectionFault = true;
  1012. }
  1013. }
  1014. }
  1015. return shouldInjectionFault;
  1016. }
  1017. // For faster fault injection test run, filter out the AVs on same IP/hash
  1018. void FaultInjection::FaultInjectionAnalyzeException(_EXCEPTION_POINTERS *ep)
  1019. {
  1020. #if !defined(_M_ARM32_OR_ARM64) // not support ARM for now, add support in case we run fault injection on ARM
  1021. AutoCriticalSection autocs(&cs_Sym);
  1022. CONTEXT* pContext = ep->ContextRecord;
  1023. // always show stack for crash and fault injection points in console,
  1024. // this can be used for additional stack matching repro
  1025. HANDLE hProcess = GetCurrentProcess();
  1026. DWORD64 dwSymDisplacement = 0;
  1027. auto printFrame = [&](LPVOID addr)
  1028. {
  1029. sip.Init();
  1030. if (pfnSymFromAddrW(hProcess, (DWORD64)addr, &dwSymDisplacement, &sip.si))
  1031. {
  1032. mi.Init();
  1033. pfnSymGetModuleInfoW64(hProcess, (DWORD64)addr, &mi);
  1034. fwprintf(stderr, _u("%s!%s+0x%llx\n"), mi.ModuleName, sip.si.Name, (ULONGLONG)dwSymDisplacement);
  1035. }
  1036. else
  1037. {
  1038. fwprintf(stderr, _u("0x%p\n"), addr);
  1039. }
  1040. };
  1041. LPVOID backTrace[MAX_FRAME_COUNT] = { 0 };
  1042. DWORD64 displacements[MAX_FRAME_COUNT] = { 0 };
  1043. #if _M_IX86
  1044. WORD nStackCount = StackTrace86(0, MAX_FRAME_COUNT, backTrace, 0, pContext);
  1045. #elif _M_X64
  1046. WORD nStackCount = StackTrace64(0, MAX_FRAME_COUNT, backTrace, 0, pContext);
  1047. #else
  1048. WORD nStackCount = CaptureStack(0, MAX_FRAME_COUNT, backTrace, 0);
  1049. #endif
  1050. // Print current crash stacks
  1051. fwprintf(stderr, crashStackStart);
  1052. for (int i = 0; i < nStackCount; i++)
  1053. {
  1054. printFrame(backTrace[i]);
  1055. displacements[i] = dwSymDisplacement;
  1056. }
  1057. LPVOID internalExceptionAddr = nullptr;
  1058. for (int i = 0; i < nStackCount - 1 && internalExceptionAddr == nullptr; i++)
  1059. {
  1060. if (backTrace[i] == (char*)Js::Throw::FatalInternalError + displacements[i])
  1061. {
  1062. internalExceptionAddr = backTrace[i + 1];
  1063. }
  1064. else if (backTrace[i] == (char*)Js::Throw::ReportAssert + displacements[i])
  1065. {
  1066. if (backTrace[i + 1] == (char*)Js::Throw::InternalError + displacements[i + 1])
  1067. {
  1068. // skip to next frame
  1069. }
  1070. else
  1071. {
  1072. internalExceptionAddr = backTrace[i + 1];
  1073. }
  1074. }
  1075. else if (backTrace[i] == (char*)Js::Throw::InternalError + displacements[i])
  1076. {
  1077. internalExceptionAddr = backTrace[i + 1];
  1078. }
  1079. }
  1080. fwprintf(stderr, crashStackEnd);
  1081. // Print fault injecting point stacks
  1082. auto record = InjectionFirstRecord;
  1083. while (record)
  1084. {
  1085. if (record->StackFrames)
  1086. {
  1087. fwprintf(stderr, injectionStackStart);
  1088. for (int i = 0; i < record->FrameCount; i++)
  1089. {
  1090. printFrame(backTrace[i]);
  1091. }
  1092. fwprintf(stderr, injectionStackEnd);
  1093. }
  1094. record = record->next;
  1095. }
  1096. // we called RaiseException() which always use RaiseException as exception address, restore the real exception addr
  1097. if (internalExceptionAddr != nullptr)
  1098. {
  1099. ep->ExceptionRecord->ExceptionAddress = internalExceptionAddr;
  1100. }
  1101. bool needDump = true;
  1102. uintptr_t ip = (uintptr_t)ep->ExceptionRecord->ExceptionAddress;
  1103. uintptr_t offset = 0;
  1104. // static to not use local stack space since stack space might be low at this point
  1105. THREAD_LOCAL static char16 modulePath[MAX_PATH + 1];
  1106. THREAD_LOCAL static WCHAR filename[MAX_PATH + 1];
  1107. HMODULE mod = nullptr;
  1108. GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCTSTR>(ip), &mod);
  1109. offset = ip - (uintptr_t)mod;
  1110. auto& faultModule = modulePath;
  1111. GetModuleFileName(mod, faultModule, MAX_PATH);
  1112. fwprintf(stderr, _u("***FI: Exception: %08x, module: %s, offset: 0x%p\n"),
  1113. ep->ExceptionRecord->ExceptionCode, faultModule, (void*)offset);
  1114. //analyze duplication
  1115. uintptr_t savedOffset = 0;
  1116. auto& mainModule = modulePath;
  1117. PlatformAgnostic::SystemInfo::GetBinaryLocation(mainModule, MAX_PATH);
  1118. // multiple session of Fault Injection run shares the single crash offset recording file
  1119. _snwprintf_s(filename, _TRUNCATE, _u("%s.FICrashes.txt"), mainModule);
  1120. auto fp = _wfsopen(filename, _u("a+t"), _SH_DENYNO);
  1121. if (fp != nullptr)
  1122. {
  1123. HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fp));
  1124. OVERLAPPED overlapped;
  1125. memset((void*)&overlapped, 0, sizeof(overlapped));
  1126. const int lockSize = 1024 * 64;
  1127. if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, lockSize, 0, &overlapped))
  1128. {
  1129. fwprintf(stderr, _u("LockFileEx(%ls) Failed when saving offset to file, gle=%8x\n"), filename, GetLastError());
  1130. fclose(fp);
  1131. }
  1132. else
  1133. { // file locked
  1134. char16 content[32] = { 0 };
  1135. while (fgetws(content, 31, fp))
  1136. {
  1137. savedOffset = HexStrToAddress(content);
  1138. if (offset == savedOffset)
  1139. {
  1140. // found duplicate so not creating dump
  1141. needDump = false;
  1142. }
  1143. }
  1144. if (needDump)
  1145. {
  1146. fwprintf(stderr, _u("This is new Exception\n"));
  1147. fwprintf(fp, _u("0x%p\n"), (void*)offset);
  1148. }
  1149. else
  1150. {
  1151. fwprintf(stderr, _u("This is not a new Exception\n"));
  1152. }
  1153. fflush(fp);
  1154. // save the hit count to a file, for bug prioritizing
  1155. _snwprintf_s(filename, _TRUNCATE, _u("%s.HitCount_%llx.txt"), mainModule, (long long)offset);
  1156. auto hcfp = _wfsopen(filename, _u("r+"), _SH_DENYNO);
  1157. if (!hcfp)
  1158. {
  1159. hcfp = _wfsopen(filename, _u("w+"), _SH_DENYNO);
  1160. }
  1161. if (hcfp)
  1162. {
  1163. auto count = 0;
  1164. fscanf_s(hcfp, "%d", &count);
  1165. count++;
  1166. fseek(hcfp, -ftell(hcfp), SEEK_CUR);
  1167. fwprintf(hcfp, _u("%d"), count);
  1168. fclose(hcfp);
  1169. }
  1170. fclose(fp);
  1171. UnlockFileEx(hFile, 0, lockSize, 0, &overlapped);
  1172. }
  1173. fflush(stderr);
  1174. }
  1175. if (globalFlags.FaultInjection == InstallExceptionHandlerOnly)
  1176. {
  1177. needDump = true;
  1178. }
  1179. // create dump for this crash
  1180. if (needDump)
  1181. {
  1182. THREAD_LOCAL static char16 dumpName[MAX_PATH + 1];
  1183. wcscpy_s(filename, globalFlags.Filename);
  1184. char16* jsFile = filename;
  1185. char16 *pch = jsFile;
  1186. // remove path and keep only alphabet and number to make a valid filename
  1187. while (*pch)
  1188. {
  1189. if (*pch == _u(':') || *pch == _u('\\'))
  1190. {
  1191. jsFile = pch + 1;
  1192. }
  1193. else if (!isalnum(*pch))
  1194. {
  1195. *pch = _u('_');
  1196. }
  1197. pch++;
  1198. }
  1199. // get dump file name
  1200. int suffix = 1;
  1201. const char16* fiType = _u("undefined");
  1202. if (globalFlags.FaultInjectionType != nullptr)
  1203. {
  1204. fiType = (LPCWSTR)globalFlags.FaultInjectionType;
  1205. }
  1206. while (true)
  1207. {
  1208. _snwprintf_s(dumpName, _TRUNCATE, _u("%s_%s_M%d_T%s_C%d_%llx_%llx_%d.dmp"),
  1209. mainModule, jsFile,
  1210. globalFlags.FaultInjection, fiType, globalFlags.FaultInjectionCount,
  1211. (ULONGLONG)offset, (ULONGLONG)ep->ExceptionRecord->ExceptionCode, suffix);
  1212. WIN32_FIND_DATAW data;
  1213. HANDLE hExist = FindFirstFile(dumpName, &data);
  1214. if (hExist == INVALID_HANDLE_VALUE)
  1215. {
  1216. FindClose(hExist);
  1217. break;
  1218. }
  1219. FindClose(hExist);
  1220. suffix++;
  1221. }
  1222. // writing the dump file
  1223. HANDLE hFile = CreateFile(dumpName, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  1224. if ((hFile == NULL) || (hFile == INVALID_HANDLE_VALUE))
  1225. {
  1226. fwprintf(stderr, _u("CreateFile <%s> failed. gle=0x%08x\n"), dumpName, GetLastError());
  1227. }
  1228. else
  1229. {
  1230. MINIDUMP_EXCEPTION_INFORMATION mdei;
  1231. mdei.ThreadId = GetCurrentThreadId();
  1232. mdei.ExceptionPointers = ep;
  1233. mdei.ClientPointers = FALSE;
  1234. MINIDUMP_TYPE mdt = (MINIDUMP_TYPE)(MiniDumpNormal
  1235. | MiniDumpWithFullMemory
  1236. | MiniDumpWithPrivateReadWriteMemory
  1237. | MiniDumpWithIndirectlyReferencedMemory
  1238. | MiniDumpWithThreadInfo);
  1239. // removing extension for windbg module name style
  1240. auto& jscript9Path = modulePath;
  1241. wcsncpy_s(jscript9Path, AutoSystemInfo::Data.GetJscriptDllFileName(),
  1242. wcslen(AutoSystemInfo::Data.GetJscriptDllFileName()) - 4);
  1243. char16* jscript9Name = jscript9Path + wcslen(jscript9Path);
  1244. while (*(jscript9Name - 1) != _u('\\') && jscript9Name > jscript9Path)
  1245. {
  1246. jscript9Name--;
  1247. }
  1248. // This buffer will be written to a dump stream when creating the minidump file.
  1249. // It contains windbg debugging instructions on how to figure out the injected faults,
  1250. // And the message will be showing in windbg while loading the minidump.
  1251. // If you need to add more instructions please increase the buffer capacity accordingly
  1252. THREAD_LOCAL static char16 dbgTip[1024];
  1253. if (InjectionFirstRecord == nullptr)
  1254. {
  1255. wcsncpy_s(dbgTip,
  1256. _u("\n")
  1257. _u("************************************************************\n")
  1258. _u("* The dump is made by FaultInjection framework, however, the fault is not actually injected yet.\n")
  1259. _u("************************************************************\n"), _TRUNCATE);
  1260. }
  1261. else
  1262. {
  1263. _snwprintf_s(dbgTip, _TRUNCATE, _u("\n")
  1264. _u("************************************************************\n")
  1265. _u("* To find the Fault Injecting points run following command: \n")
  1266. _u("* !list -t %s!Js::FaultInjection::InjectionRecord.next -e -x \"dps @$extret @$extret+0x128\" poi(@@c++(&%s!Js::FaultInjection::Global.InjectionFirstRecord))\n")
  1267. _u("* To rebuild the stack (locals are available):\n")
  1268. _u("* .cxr @@C++(&%s!Js::FaultInjection::Global.InjectionFirstRecord->Context)\n")
  1269. _u("************************************************************\n"), jscript9Name, jscript9Name, jscript9Name);
  1270. }
  1271. MINIDUMP_USER_STREAM UserStreams[1];
  1272. UserStreams[0].Type = CommentStreamW;
  1273. UserStreams[0].Buffer = dbgTip;
  1274. UserStreams[0].BufferSize = (ULONG)wcslen(dbgTip)*sizeof(char16);
  1275. MINIDUMP_USER_STREAM_INFORMATION musi;
  1276. musi.UserStreamCount = 1;
  1277. musi.UserStreamArray = UserStreams;
  1278. BOOL rv = pfnMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, mdt, (ep != 0) ? &mdei : 0, &musi, 0);
  1279. if (rv)
  1280. {
  1281. fwprintf(stderr, _u("Minidump created: %s\n"), dumpName);
  1282. }
  1283. else
  1284. {
  1285. fwprintf(stderr, _u("MiniDumpWriteDump failed. gle=0x%08x\n"), GetLastError());
  1286. }
  1287. CloseHandle(hFile);
  1288. }
  1289. }
  1290. fflush(stderr);
  1291. #endif //_M_ARM and _M_ARM64
  1292. }
  1293. static volatile bool inExceptionHandler = false;
  1294. LONG WINAPI FaultInjection::FaultInjectionExceptionFilter(_In_ struct _EXCEPTION_POINTERS *ExceptionInfo)
  1295. {
  1296. if (inExceptionHandler)
  1297. {
  1298. // re-entering, this can happen if RemoveExceptionFilters() failed because of stack overflow
  1299. // Let it crash and the postmortem debugger can catch it.
  1300. DebugBreak();
  1301. }
  1302. inExceptionHandler = true;
  1303. RemoveExceptionFilters();
  1304. // for debugging, can't hit here in windbg because of using vectored exception handling
  1305. if (faultInjectionDebug)
  1306. {
  1307. DebugBreak();
  1308. }
  1309. if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_STACK_OVERFLOW) // hard stack overflow
  1310. {
  1311. DebugBreak(); // let the postmortem debugger to create the dump, make sure they are filing bug with same bucket
  1312. }
  1313. __try
  1314. {
  1315. // sometimes the OS is really low memory and can't commit page for stack expanding
  1316. // even stack is not deep yet
  1317. FaultInjection::Global.FaultInjectionAnalyzeException(ExceptionInfo);
  1318. }
  1319. __except (EXCEPTION_EXECUTE_HANDLER)
  1320. {
  1321. DebugBreak();
  1322. }
  1323. inExceptionHandler = false;
  1324. return EXCEPTION_EXECUTE_HANDLER;
  1325. }
  1326. } //namespace Js
  1327. #endif //FAULT_INJECTION