forked from chakra-core/ChakraCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFaultInjection.cpp
More file actions
1391 lines (1260 loc) · 49 KB
/
FaultInjection.cpp
File metadata and controls
1391 lines (1260 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "CommonCorePch.h"
#ifdef FAULT_INJECTION
#include "io.h"
#include "share.h"
#undef DBGHELP_TRANSLATE_TCHAR
#define _NO_CVCONST_H
// dbghelp.h is not clean with warning 4091
#pragma warning(push)
#pragma warning(disable: 4091) /* warning C4091: 'typedef ': ignored on left of '' when no variable is declared */
#include <dbghelp.h>
#pragma warning(pop)
namespace Js
{
#pragma region helpers
#define FIDELAYLOAD(fn) static decltype(fn)* pfn##fn = nullptr
FIDELAYLOAD(SymInitialize);
FIDELAYLOAD(SymCleanup);
FIDELAYLOAD(SymFromAddrW);
FIDELAYLOAD(SymFromNameW);
FIDELAYLOAD(SymEnumSymbolsW);
FIDELAYLOAD(SymGetModuleInfoW64);
FIDELAYLOAD(SymMatchStringW);
FIDELAYLOAD(SymSetOptions);
FIDELAYLOAD(MiniDumpWriteDump);
FIDELAYLOAD(SymFunctionTableAccess64);
FIDELAYLOAD(SymGetModuleBase64);
FIDELAYLOAD(StackWalk64);
#undef FIDELAYLOAD
template<typename CharT>
bool isEqualIgnoreCase(CharT c1, CharT c2)
{
return c1 == c2
|| ((c2 <= 'Z') && (c1 >= 'a') && (c1 - c2 == 'a' - 'A'))
|| ((c1 <= 'Z') && (c2 >= 'a') && (c2 - c1 == 'a' - 'A'));
}
template<typename CharT>
CharT *stristr(const CharT * cs1,
const CharT * cs2)
{
CharT *cp = (CharT *)cs1;
CharT *s1, *s2;
if (!*cs2)
return (CharT *)cs1;
while (*cp)
{
s1 = cp;
s2 = (CharT *)cs2;
while (*s1 && *s2 && isEqualIgnoreCase(*s1, *s2))
s1++, s2++;
if (!*s2)
return cp;
cp++;
}
return nullptr;
}
static wchar_t* trimRight(_Inout_z_ wchar_t* str)
{
auto tmp = str + wcslen(str);
while (!isprint(*--tmp));
*(tmp + 1) = L'\0';
return str;
}
static int8 const* hexTable = []()->int8*{
static int8 hex[256] = { 0 };
memset(hex, 0xff, 256);
for (int8 i = '0'; i <= '9'; i++) hex[i] = i - '0';
for (int8 i = 'a'; i <= 'f'; i++) hex[i] = i - 'a' + 10;
for (int8 i = 'A'; i <= 'F'; i++) hex[i] = i - 'A' + 10;
return hex;
}();
template<typename CharT>
static UINT_PTR HexStrToAddress(const CharT* str)
{
UINT_PTR address = 0;
while (*str == '0' || *str == '`' || *str == 'x' || *str == 'X')
str++; // leading zero
do
{
if (*str == '`') // amd64 address
continue;
if (hexTable[*str & 0xff] < 0)
return address;
address = 16 * address + hexTable[*str & 0xff];
} while (*(++str));
return address;
}
#if _M_X64
// for amd64 jit frame, RtlCaptureStackBackTrace stops walking after hitting jit frame on amd64
__declspec(noinline)
WORD StackTrace64(_In_ DWORD FramesToSkip,
_In_ DWORD FramesToCapture,
_Out_writes_to_(FramesToCapture, return) PVOID * BackTrace,
_Out_opt_ PDWORD BackTraceHash,
_In_opt_ const CONTEXT* pCtx = nullptr)
{
CONTEXT Context;
KNONVOLATILE_CONTEXT_POINTERS NvContext;
UNWIND_HISTORY_TABLE UnwindHistoryTable;
PRUNTIME_FUNCTION RuntimeFunction;
PVOID HandlerData;
ULONG64 EstablisherFrame;
ULONG64 ImageBase;
ULONG Frame = 0;
if (BackTraceHash)
{
*BackTraceHash = 0;
}
if (pCtx == nullptr)
{
RtlCaptureContext(&Context);
}
else
{
memcpy(&Context, pCtx, sizeof(CONTEXT));
}
RtlZeroMemory(&UnwindHistoryTable, sizeof(UNWIND_HISTORY_TABLE));
while (true)
{
RuntimeFunction = RtlLookupFunctionEntry(Context.Rip, &ImageBase, &UnwindHistoryTable);
RtlZeroMemory(&NvContext, sizeof(KNONVOLATILE_CONTEXT_POINTERS));
if (!RuntimeFunction)
{
Context.Rip = (ULONG64)(*(PULONG64)Context.Rsp);
Context.Rsp += 8;
}
else
{
RtlVirtualUnwind(UNW_FLAG_NHANDLER, ImageBase, Context.Rip, RuntimeFunction,
&Context, &HandlerData, &EstablisherFrame, &NvContext);
}
if (!Context.Rip)
{
break;
}
if (FramesToSkip > 0)
{
FramesToSkip--;
continue;
}
if (Frame >= FramesToCapture)
{
break;
}
BackTrace[Frame] = (PVOID)Context.Rip;
if (BackTraceHash)
{
*BackTraceHash += (Context.Rip & 0xffffffff);
}
Frame++;
}
return (WORD)Frame;
}
#define CaptureStack(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash) \
StackTrace64(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash)
#elif defined (_M_IX86)
#pragma optimize( "g", off )
#pragma warning( push )
#pragma warning( disable : 4748 )
#pragma warning( disable : 4995 )
WORD StackTrace86(
_In_ DWORD FramesToSkip,
_In_ DWORD FramesToCapture,
_Out_writes_to_(FramesToCapture, return) PVOID * BackTrace,
_Inout_opt_ PDWORD BackTraceHash,
__in_opt CONST PCONTEXT InitialContext = NULL
)
{
_Analysis_assume_(FramesToSkip >= 0);
_Analysis_assume_(FramesToCapture >= 0);
DWORD MachineType;
CONTEXT Context;
STACKFRAME64 StackFrame;
if (InitialContext == NULL)
{
//RtlCaptureContext( &Context );
ZeroMemory(&Context, sizeof(CONTEXT));
Context.ContextFlags = CONTEXT_CONTROL;
__asm
{
Label:
mov[Context.Ebp], ebp;
mov[Context.Esp], esp;
mov eax, [Label];
mov[Context.Eip], eax;
}
}
else
{
CopyMemory(&Context, InitialContext, sizeof(CONTEXT));
}
ZeroMemory(&StackFrame, sizeof(STACKFRAME64));
MachineType = IMAGE_FILE_MACHINE_I386;
StackFrame.AddrPC.Offset = Context.Eip;
StackFrame.AddrPC.Mode = AddrModeFlat;
StackFrame.AddrFrame.Offset = Context.Ebp;
StackFrame.AddrFrame.Mode = AddrModeFlat;
StackFrame.AddrStack.Offset = Context.Esp;
StackFrame.AddrStack.Mode = AddrModeFlat;
WORD FrameCount = 0;
while (FrameCount < FramesToSkip + FramesToCapture)
{
if (!pfnStackWalk64(MachineType, GetCurrentProcess(), GetCurrentThread(), &StackFrame,
NULL, NULL, pfnSymFunctionTableAccess64, pfnSymGetModuleBase64, NULL))
{
break;
}
if (StackFrame.AddrPC.Offset != 0)
{
if (FrameCount >= FramesToSkip)
{
#pragma warning(suppress: 22102)
#pragma warning(suppress: 26014)
BackTrace[FrameCount - FramesToSkip] = (PVOID)StackFrame.AddrPC.Offset;
if (BackTraceHash)
{
*BackTraceHash += (StackFrame.AddrPC.Offset & 0xffffffff);
}
}
FrameCount++;
}
else
{
break;
}
}
if (FrameCount > FramesToSkip)
{
return (WORD)(FrameCount - FramesToSkip);
}
else
{
return 0;
}
}
#pragma warning( pop )
#pragma optimize( "g", on )
#define CaptureStack(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash) \
RtlCaptureStackBackTrace(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash)
#else
#define CaptureStack(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash) \
RtlCaptureStackBackTrace(FramesToSkip, FramesToCapture, BackTrace, BackTraceHash)
#endif
struct SymbolInfoPackage : public SYMBOL_INFO_PACKAGEW
{
SymbolInfoPackage() { Init(); }
void Init()
{
si.SizeOfStruct = sizeof(SYMBOL_INFOW);
si.MaxNameLen = sizeof(name);
}
};
struct ModuleInfo : public IMAGEHLP_MODULEW64
{
ModuleInfo() { Init(); }
void Init()
{
SizeOfStruct = sizeof(IMAGEHLP_MODULEW64);
}
};
bool FaultInjection::InitializeSym()
{
if (symInitialized)
{
return true;
}
// load dbghelp APIs
if (hDbgHelp == NULL)
{
hDbgHelp = LoadLibraryEx(L"dbghelp.dll", 0, 0);
}
if (hDbgHelp == NULL)
{
fwprintf(stderr, L"Failed to load dbghelp.dll for stack walking, gle=0x%08x\n", GetLastError());
fflush(stderr);
return false;
}
#define FIDELAYLOAD(fn) pfn##fn = (decltype(fn)*)GetProcAddress(hDbgHelp, #fn); \
if (pfn##fn == nullptr){\
fwprintf(stderr, L"Failed to load sigs:%s\n", L#fn); \
fflush(stderr); \
return false; \
}
FIDELAYLOAD(SymInitialize);
FIDELAYLOAD(SymCleanup);
FIDELAYLOAD(SymFromAddrW);
FIDELAYLOAD(SymFromNameW);
FIDELAYLOAD(SymEnumSymbolsW);
FIDELAYLOAD(SymGetModuleInfoW64);
FIDELAYLOAD(SymMatchStringW);
FIDELAYLOAD(SymSetOptions);
FIDELAYLOAD(MiniDumpWriteDump);
FIDELAYLOAD(SymFunctionTableAccess64);
FIDELAYLOAD(SymGetModuleBase64);
FIDELAYLOAD(StackWalk64);
#undef FIDELAYLOAD
// TODO: StackBackTrace.cpp also call SymInitialize, but this can only be called once before cleanup
if (!pfnSymInitialize(GetCurrentProcess(), NULL, TRUE))
{
fwprintf(stderr, L"SymInitialize failed, gle=0x%08x\n", GetLastError());
fflush(stderr);
return false;
}
symInitialized = true;
return true;
}
#pragma endregion helpers
FaultInjection FaultInjection::Global;
static CriticalSection cs_Sym; // for Sym* method is not thread safe
const auto& globalFlags = Js::Configuration::Global.flags;
PVOID FaultInjection::vectoredExceptionHandler = nullptr;
DWORD FaultInjection::exceptionFilterRemovalLastError = 0;
int(*Js::FaultInjection::pfnHandleAV)(int, PEXCEPTION_POINTERS) = nullptr;
static SymbolInfoPackage sip;
static ModuleInfo mi;
const wchar_t* crashStackStart = L"=====Callstack for this exception=======\n";
const wchar_t* crashStackEnd = L"=====End of callstack for this exception=======\n";
const wchar_t* injectionStackStart = L"=====Fault injecting record=====\n";
const wchar_t* injectionStackEnd = L"=====End of Fault injecting record=====\n";
typedef struct _RANGE{
UINT_PTR startAddress;
UINT_PTR endAddress;
}RANGE, *PRANGE;
typedef struct _FUNCTION_SIGNATURES
{
int count;
RANGE signatures[ANYSIZE_ARRAY];
} FUNCTION_SIGNATURES, *PFUNCTION_SIGNATURES;
// function address ranges of each signature
// use for faster address matching instead of symbol table lookup when reproing
PFUNCTION_SIGNATURES baselineFuncSigs[FaultInjection::MAX_FRAME_COUNT] = { 0 };
// record hit count of each frame when Faults are injected.
unsigned int stackMatchRank[FaultInjection::MAX_FRAME_COUNT] = { 0 };
#define FAULT_TYPE(x) L#x,\
wchar_t *FaultInjection::FaultTypeNames[] =
{
#include "FaultTypes.h"
};
#undef FAULT_TYPE
static_assert(sizeof(FaultInjection::FaultTypeNames) == FaultInjection::FaultType::FaultTypeCount*sizeof(wchar_t*),
"FaultTypeNames count is wrong");
void FaultInjection::FaultInjectionTypes::EnableType(FaultType type)
{
Assert(type >= 0 && type < FaultType::FaultTypeCount);
setBit(type, 1);
}
bool FaultInjection::FaultInjectionTypes::IsEnabled(FaultType type)
{
Assert(type >= 0 && type < FaultType::FaultTypeCount);
return getBit(type) == 0x1;
}
bool FaultInjection::FaultInjectionTypes::IsEnabled(const wchar_t* name)
{
for (int type = 0; type < FaultType::FaultTypeCount; type++)
{
if (wcscmp(FaultTypeNames[type], name) == 0)
return getBit(type) == 0x1;
}
AssertMsg(false, "Unknown fault type name");
return false;
}
FaultInjection::FaultInjection()
{
stackMatchInitialized = Uninitialized;
countOfInjectionPoints = 0;
hDbgHelp = NULL;
InjectionFirstRecord = nullptr;
InjectionLastRecordRef = &InjectionFirstRecord;
InjectionRecordsCount = 0;
FaultInjectionCookie = 0;
baselineFrameCount = 0;
stackHashOfAllInjectionPointsSize = 256;
stackHashOfAllInjectionPoints = (ULONG_PTR*)malloc(stackHashOfAllInjectionPointsSize*sizeof(ULONG_PTR));
faultInjectionTypes = nullptr;
symInitialized = false;
for (int i = 0; i < MAX_FRAME_COUNT; i++)
{
baselineStack[i] = nullptr;
baselineAddresses[i] = 0;
}
}
FaultInjection::~FaultInjection()
{
RemoveExceptionFilters();
// when fault injection count only is passing from jscript.config(in case of running on 3rd part host)
// and the host don't have code to output the fault injection count, we still able to do the fault injection test
if (globalFlags.FaultInjection == FaultMode::CountOnly
|| globalFlags.FaultInjection == FaultMode::StackMatchCountOnly)
{
fprintf(stderr, "FaultInjection - Total Allocation Count:%u\n", countOfInjectionPoints);
fflush(stderr);
FILE *fp;
char countFileName[64];
sprintf_s(countFileName, "ChakraFaultInjectionCount_%u.txt", GetCurrentProcessId());
if (fopen_s(&fp, countFileName, "w") == 0)
{
fprintf(fp, "FaultInjection - Total Allocation Count:%u\n", countOfInjectionPoints);
fflush(fp);
fclose(fp);
}
for (int i = 0; i < MAX_FRAME_COUNT; i++)
{
if (stackMatchRank[i] == 0)
{
break;
}
fwprintf(stderr, L"FaultInjection stack matching rank %d: %u\n", i + 1, stackMatchRank[i]);
}
fflush(stderr);
}
if (globalFlags.FaultInjection == StackHashCountOnly)
{
FILE *fp;
if (fopen_s(&fp, "ChakraFaultInjectionHashes.txt", "w") == 0)
{
for (uint i = 0; i < countOfInjectionPoints; i++)
{
fprintf(fp, "%p\n", (void*)stackHashOfAllInjectionPoints[i]);
}
fflush(fp);
fclose(fp);
}
}
free(stackHashOfAllInjectionPoints);
stackHashOfAllInjectionPoints = nullptr;
if (globalFlags.FaultInjection == FaultMode::DisplayAvailableFaultTypes)
{
Output::Print(L"Available Fault Types:\n");
for (int i = 0; i < FaultType::FaultTypeCount; i++)
{
Output::Print(L"%d-%s\n", i, FaultTypeNames[i]);
}
Output::Flush();
}
InjectionRecord* head = InjectionFirstRecord;
while (head != nullptr)
{
InjectionRecord* next = head->next;
if (head->StackData)
{
free(head->StackData);
}
free(head);
head = next;
}
for (int i = 0; i < MAX_FRAME_COUNT; i++)
{
if (baselineStack[i])
{
free(baselineStack[i]);
}
if (baselineFuncSigs[i])
{
free(baselineFuncSigs[i]);
}
}
if (stackMatchInitialized == Succeeded)
{
pfnSymCleanup(GetCurrentProcess());
}
if (hDbgHelp)
{
FreeLibrary(hDbgHelp);
}
if (faultInjectionTypes)
{
faultInjectionTypes->~FaultInjectionTypes();
NoCheckHeapDelete(faultInjectionTypes);
}
}
bool FaultInjection::IsFaultEnabled(FaultType faultType)
{
if (!faultInjectionTypes)
{
faultInjectionTypes = NoCheckHeapNew(FaultInjectionTypes);
if ((const wchar_t*)globalFlags.FaultInjectionType == nullptr)
{
// no -FaultInjectionType specified, inject all
faultInjectionTypes->EnableAll();
}
else
{
ParseFaultTypes(globalFlags.FaultInjectionType);
}
}
return faultInjectionTypes->IsEnabled(faultType);
}
bool FaultInjection::IsFaultInjectionOn(FaultType faultType)
{
return globalFlags.FaultInjection >= 0 //-FaultInjection switch
&& IsFaultEnabled(faultType);
}
void FaultInjection::ParseFaultTypes(const wchar_t* szFaultTypes)
{
auto charCount = wcslen(szFaultTypes) + 1;
wchar_t* szTypes = (wchar_t*)malloc(charCount*sizeof(wchar_t));
AssertMsg(szTypes, "OOM in FaultInjection Infra");
wcscpy_s(szTypes, charCount, szFaultTypes);
const wchar_t* delims = L",";
wchar_t *nextTok = nullptr;
wchar_t* tok = wcstok_s(szTypes, delims, &nextTok);
while (tok != NULL)
{
if (wcslen(tok) > 0)
{
if (iswdigit(tok[0]))
{
auto numType = _wtoi(tok);
for (int i = 0; i< FaultType::FaultTypeCount; i++)
{
if (numType & (1 << i))
{
faultInjectionTypes->EnableType(i);
}
}
}
else if (tok[0] == L'#')
{
// FaultInjectionType:#1-4,#6 format, not flags
auto tok1 = tok + 1;
if (wcslen(tok1)>0 && iswdigit(tok1[0]))
{
wchar_t* pDash = wcschr(tok1, L'-');
if (pDash)
{
for (int i = _wtoi(tok1); i <= _wtoi(pDash + 1); i++)
{
faultInjectionTypes->EnableType(i);
}
}
else
{
faultInjectionTypes->EnableType(_wtoi(tok1));
}
}
}
else
{
for (int i = 0; i < FaultType::FaultTypeCount; i++)
{
if (_wcsicmp(FaultTypeNames[i], tok) == 0)
{
faultInjectionTypes->EnableType(i);
break;
}
}
}
}
tok = wcstok_s(NULL, delims, &nextTok);
}
free(szTypes);
}
static void SmashLambda(_Inout_z_ wchar_t* str)
{
//jscript9test!<lambda_dc7f9e8c591f1832700d6567e43faa6c>::operator()
const wchar_t lambdaSig[] = L"<lambda_";
const int lambdaSigLen = (int)wcslen(lambdaSig);
auto temp = str;
while (temp != nullptr)
{
auto lambdaStart = wcsstr(temp, lambdaSig);
temp = nullptr;
if (lambdaStart != nullptr)
{
auto lambdaEnd = wcschr(lambdaStart, L'>');
temp = lambdaEnd;
if (lambdaEnd != nullptr && lambdaEnd - lambdaStart == lambdaSigLen + 32)
{
lambdaStart += lambdaSigLen;
while (lambdaStart < lambdaEnd)
{
*(lambdaStart++) = L'?';
}
}
}
}
}
bool FaultInjection::EnsureStackMatchInfraInitialized()
{
if (stackMatchInitialized == Succeeded)
{
return true;
}
else if (stackMatchInitialized == FailedToInitialize)
{
// previous try to initialize and failed
return false;
}
else if (stackMatchInitialized == Uninitialized)
{
stackMatchInitialized = FailedToInitialize; //tried
if (!InitializeSym())
{
return false;
}
// read baseline stack file
FILE *fp = nullptr;
const wchar_t *stackFile = globalFlags.FaultInjectionStackFile;//default: L"stack.txt";
auto err = _wfopen_s(&fp, stackFile, L"r");
if (err != 0 || fp == nullptr)
{
fwprintf(stderr, L"Failed to load %s, gle=0x%08x\n", stackFile, GetLastError());
fflush(stderr);
return false;
}
wchar_t buffer[MAX_SYM_NAME]; // assume the file is normal
unsigned int maxLineCount =
(globalFlags.FaultInjectionStackLineCount < 0
|| globalFlags.FaultInjectionStackLineCount > MAX_FRAME_COUNT
|| globalFlags.FaultInjection == FaultMode::StackMatchCountOnly)
? MAX_FRAME_COUNT : globalFlags.FaultInjectionStackLineCount;
while (fgetws(buffer, MAX_SYM_NAME, fp))
{
if (wcscmp(buffer, injectionStackStart) == 0)
{
baselineFrameCount = 0;
continue;
}
if (baselineFrameCount >= maxLineCount)
{
continue; // don't break because we can hit the start marker and reset
}
const wchar_t jscript9test[] = L"jscript9test!";
const wchar_t jscript9[] = L"jscript9!";
wchar_t* symbolStart = stristr(buffer, jscript9test);
if (symbolStart == nullptr)
{
symbolStart = stristr(buffer, jscript9);
}
if (symbolStart == nullptr)
{
continue;// no "jscript9test!", skip this line
}
if (wcsstr(symbolStart, L"Js::FaultInjection") != NULL)
{ // skip faultinjection infra frames.
continue;
}
auto plus = wcschr(symbolStart, L'+');
if (plus)
{
*plus = L'\0';
}
else
{
trimRight(symbolStart);
}
SmashLambda(symbolStart);
size_t len = wcslen(symbolStart);
if (baselineStack[baselineFrameCount] == nullptr)
{
baselineStack[baselineFrameCount] = (wchar_t*)malloc((len + 1)*sizeof(wchar_t));
AssertMsg(baselineStack[baselineFrameCount], "OOM in FaultInjection Infra");
}
else
{
auto tmp = (wchar_t*)realloc(baselineStack[baselineFrameCount], (len + 1)*sizeof(wchar_t));
AssertMsg(tmp, "OOM in FaultInjection Infra");
baselineStack[baselineFrameCount] = tmp;
}
wcscpy_s(baselineStack[baselineFrameCount], len + 1, symbolStart);
baselineFrameCount++;
}
fclose(fp);
OutputDebugString(L"Fault will be injected when hit following stack:\n");
for (uint i = 0; i<baselineFrameCount; i++)
{
OutputDebugString(baselineStack[i]);
OutputDebugString(L"\n");
if (wcschr(baselineStack[i], '*') != nullptr || wcschr(baselineStack[i], '?') != nullptr)
{
continue; // there's wildcard in this line, don't use address matching
}
// enum symbols, if succeed we compare with address when doing stack matching
pfnSymEnumSymbolsW(GetCurrentProcess(), 0, baselineStack[i],
[](_In_ PSYMBOL_INFOW pSymInfo, _In_ ULONG SymbolSize, _In_opt_ PVOID UserContext)->BOOL
{
Assert(UserContext != nullptr); // did passed in the user context
if (pSymInfo->Size > 0)
{
PFUNCTION_SIGNATURES* sigs = (PFUNCTION_SIGNATURES*)UserContext;
int count = (*sigs) == nullptr ? 0 : (*sigs)->count;
auto tmp = (PFUNCTION_SIGNATURES)realloc(*sigs, sizeof(FUNCTION_SIGNATURES) + count*sizeof(RANGE));
AssertMsg(tmp, "OOM when allocating for FaultInjection Stack matching objects");
*sigs = tmp;
(*sigs)->count = count;
(*sigs)->signatures[count].startAddress = (UINT_PTR)pSymInfo->Address;
(*sigs)->signatures[count].endAddress = (UINT_PTR)(pSymInfo->Address + pSymInfo->Size);
(*sigs)->count++;
}
return TRUE;
}, &baselineFuncSigs[i]);
}
stackMatchInitialized = Succeeded; // initialized
return true;
}
return false;
}
bool FaultInjection::IsCurrentStackMatch()
{
AutoCriticalSection autocs(&cs_Sym); // sym* API is thread unsafe
if (!EnsureStackMatchInfraInitialized())
{
return false;
}
DWORD64 dwSymDisplacement = 0;
auto hProcess = GetCurrentProcess();
static void* framesBuffer[FaultInjection::MAX_FRAME_COUNT];
auto frameCount = CaptureStack(0, MAX_FRAME_COUNT, framesBuffer, 0);
uint n = 0;
for (uint i = 0; i < frameCount; i++)
{
if (n >= baselineFrameCount)
{
return true;
}
if (!AutoSystemInfo::Data.IsJscriptModulePointer(framesBuffer[i]))
{ // skip non-Chakra frame
continue;
}
bool match = false;
if (baselineFuncSigs[n] != nullptr)
{
for (int j = 0; j<baselineFuncSigs[n]->count; j++)
{
match = baselineFuncSigs[n]->signatures[j].startAddress <= (UINT_PTR)framesBuffer[i]
&& (UINT_PTR)framesBuffer[i] < baselineFuncSigs[n]->signatures[j].endAddress;
if (match)
{
break;
}
}
}
else
{
// fallback to symbol name matching
sip.Init();
if (!pfnSymFromAddrW(hProcess, (DWORD64)framesBuffer[i], &dwSymDisplacement, &sip.si))
{
continue;
}
SmashLambda(sip.si.Name);
// Only search sigs name, can use wildcard in baseline file
match = stristr(baselineStack[n], sip.si.Name) != nullptr
|| pfnSymMatchStringW(sip.si.Name, baselineStack[n], false);// wildcard
}
if (match)
{
stackMatchRank[n]++;
if (n == 0)
{
n++;
continue;
}
}
else if (n > 0)
{
return false;
}
// First line in baseline is found, moving forward.
if (n > 0)
{
n++;
}
}
return false;
}
static bool faultInjectionDebug = false;
bool FaultInjection::InstallExceptionFilters()
{
if (GetEnvironmentVariable(L"FAULTINJECTION_DEBUG", nullptr, 0) != 0)
{
faultInjectionDebug = true;
}
if (globalFlags.FaultInjection >= 0 && !IsDebuggerPresent())
{
// initialize symbol system here instead of inside the exception filter
// because some hard stack overflow can happen in SymInitialize
// when the exception filter is handling stack overflow exception
if (!FaultInjection::Global.InitializeSym())
{
return false;
}
//C28725: Use Watson instead of this SetUnhandledExceptionFilter.
#pragma prefast(suppress: 28725)
SetUnhandledExceptionFilter([](_In_ struct _EXCEPTION_POINTERS *ExceptionInfo)->LONG
{
return FaultInjectionExceptionFilter(ExceptionInfo);
});
vectoredExceptionHandler = AddVectoredExceptionHandler(0, [](_In_ struct _EXCEPTION_POINTERS *ExceptionInfo)->LONG
{
switch (ExceptionInfo->ExceptionRecord->ExceptionCode)
{
// selected fatal exceptions:
case STATUS_ACCESS_VIOLATION:
{
if (pfnHandleAV
&& pfnHandleAV(ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo) == EXCEPTION_CONTINUE_EXECUTION)
{
return EXCEPTION_CONTINUE_EXECUTION;
}
}
case STATUS_ASSERTION_FAILURE:
case STATUS_STACK_OVERFLOW:
FaultInjectionExceptionFilter(ExceptionInfo);
TerminateProcess(::GetCurrentProcess(), ExceptionInfo->ExceptionRecord->ExceptionCode);
default:
return EXCEPTION_CONTINUE_SEARCH;
}
});
return true;
}
return false;
}
void FaultInjection::RemoveExceptionFilters()
{
//C28725: Use Watson instead of this SetUnhandledExceptionFilter.
#pragma prefast(suppress: 28725)
SetUnhandledExceptionFilter(nullptr);
if (vectoredExceptionHandler != nullptr)
{
RemoveVectoredExceptionHandler(vectoredExceptionHandler);
exceptionFilterRemovalLastError = GetLastError(); // looks sometimes the removal fails
vectoredExceptionHandler = nullptr;
}
}
// Calculate stack hash by adding the addresses (only jscript9 frames)
UINT_PTR FaultInjection::CalculateStackHash(void* frames[], WORD frameCount, WORD framesToSkip)
{
UINT_PTR hash = 0;
for (int i = framesToSkip; i < frameCount; i++)
{
if (AutoSystemInfo::Data.IsJscriptModulePointer(frames[i]))
{
hash += (UINT_PTR)frames[i] - AutoSystemInfo::Data.dllLoadAddress;
}
}
return hash;
}
// save the stack data for dump debugging use
// to get list of fault injection points:
// !list -t jscript9test!Js::FaultInjection::InjectionRecord.next -e -x "dps @$extret @$extret+0x128" poi(@@c++(&jscript9test!Js::FaultInjection::Global.InjectionFirstRecord))
// to rebuild the stack (locals are available)
// .cxr @@C++(&jscript9test!Js::FaultInjection::Global.InjectionFirstRecord->Context)
__declspec(noinline) void FaultInjection::dumpCurrentStackData(LPCWSTR name /*= nullptr*/, size_t size /*= 0*/)
{
#if !defined(_M_ARM32_OR_ARM64)
static bool keepBreak = true; // for disabling following breakpoint by editing the value
if (keepBreak && IsDebuggerPresent())
{
DebugBreak();
}
InjectionRecord* record = (InjectionRecord*)malloc(sizeof(InjectionRecord));
if (record == nullptr) return;
ZeroMemory(record, sizeof(InjectionRecord));
auto _stackbasepointer = ((PNT_TIB)NtCurrentTeb())->StackBase;
// context
RtlCaptureContext(&record->Context);
#if _M_X64
auto& _stackpointer = record->Context.Rsp;
auto& _basepointer = record->Context.Rbp;
#elif _M_IX86
auto& _stackpointer = record->Context.Esp;
auto& _basepointer = record->Context.Ebp;
#endif
typedef decltype(_stackpointer) spType;
record->StackDataLength = (spType)_stackbasepointer - _stackpointer;
record->StackData = malloc(record->StackDataLength);
if (record->StackData)
{
memcpy(record->StackData, (void*)_stackpointer, record->StackDataLength);
_basepointer = _basepointer + (spType)record->StackData - _stackpointer;
_stackpointer = (spType)record->StackData; // for .cxr switching to this state
}
if (name)
{
wcscpy_s(record->name, name);
}
record->allocSize = size;
// stack frames
record->FrameCount = CaptureStack(0, MAX_FRAME_COUNT, record->StackFrames, 0);
// hash
record->hash = CalculateStackHash(record->StackFrames, record->FrameCount, 2);
fwprintf(stderr, L"***FI: Fault Injected, StackHash:%p\n", (void*)record->hash);
fflush(stderr);
*InjectionLastRecordRef = record;
InjectionLastRecordRef = &record->next;
InjectionRecordsCount++;
#endif // _M_ARM || _M_ARM64
}
bool FaultInjection::ShouldInjectFault(FaultType fType, LPCWSTR name, size_t size)
{
bool shouldInjectionFault = ShouldInjectFaultHelper(fType, name, size);
if (shouldInjectionFault && fType != FaultType::ScriptTerminationOnDispose)
{
dumpCurrentStackData(name, size);
}
return shouldInjectionFault;
}
bool FaultInjection::ShouldInjectFaultHelper(FaultType fType, LPCWSTR name, size_t size)
{
if (globalFlags.FaultInjection < 0)