-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathNaglerInstrumentationMethod.cpp
1731 lines (1433 loc) · 60.2 KB
/
NaglerInstrumentationMethod.cpp
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 Corporation. All rights reserved.
// Licensed under the MIT License.
#include "stdafx.h"
#include "NaglerInstrumentationMethod.h"
#pragma warning(push)
#pragma warning(disable: 4995) // disable so that memcpy, wmemcpy can be used
#include <sstream>
#pragma warning(pop)
#include "Util.h"
#include "InstrumentationEngineString.h"
#include "InstrStr.h"
#include "SystemUtils.h"
#include <type_traits>
const WCHAR CInstrumentationMethod::TestOutputPathEnvName[] = _T("Nagler_TestOutputPath");
const WCHAR CInstrumentationMethod::TestScriptFileEnvName[] = _T("Nagler_TestScript");
const WCHAR CInstrumentationMethod::TestScriptFolder[] = _T("TestScripts");
const WCHAR CInstrumentationMethod::IsRejitEnvName[] = _T("Nagler_IsRejit");
void AssertLogFailure(_In_ const WCHAR* wszError, ...)
{
#ifdef PLATFORM_UNIX
// Attempting to interpret the var args is very difficult
// cross-plat without a PAL. We should see about removing
// the dependency on this in the Common.Lib
string str;
HRESULT hr = SystemString::Convert(wszError, str);
if (!SUCCEEDED(hr))
{
str = "Unable to convert wchar string to char string";
}
AssertFailed(str.c_str());
#else
// Since this is a test libary, we will print to standard error and fail
va_list argptr;
va_start(argptr, wszError);
vfwprintf(stderr, wszError, argptr);
#endif
throw "Assert failed";
}
// Convenience macro for defining strings.
#define InstrStr(_V) CInstrumentationEngineString _V(m_pStringManager)
ILOpcodeInfo ilOpcodeInfo[] =
{
#ifdef PLATFORM_UNIX
#define OPDEF(ord, code, name, opcodeLen, operandLen, type, alt, flags, pop, push) \
{ name, (DWORD)opcodeLen, (DWORD)operandLen, type, alt, flags, (DWORD)pop, (DWORD)push},
#else
#define OPDEF(ord, code, name, opcodeLen, operandLen, type, alt, flags, pop, push) \
{ name, (DWORD)opcodeLen, (DWORD)operandLen, ##type, alt, flags, (DWORD)pop, (DWORD)push},
#endif
#include "ILOpcodes.h"
#undef OPDEF
};
struct ComInitializer
{
#ifndef PLATFORM_UNIX
HRESULT _hr;
ComInitializer(DWORD mode = COINIT_APARTMENTTHREADED)
{
_hr = CoInitializeEx(NULL, mode);
}
~ComInitializer()
{
if (SUCCEEDED(_hr))
{
CoUninitialize();
}
}
#endif
};
HRESULT CInstrumentationMethod::Initialize(_In_ IProfilerManager* pProfilerManager)
{
HRESULT hr;
m_pProfilerManager = pProfilerManager;
IfFailRet(m_pProfilerManager->QueryInterface(&m_pStringManager));
#ifdef PLATFORM_UNIX
DWORD retVal = LoadInstrumentationMethodXml(this);
#else
// On Windows, xml reading is done in a single-threaded apartment using
// COM, so we need to spin up a new thread for it.
CHandle hConfigThread;
hConfigThread.Attach(CreateThread(NULL, 0, LoadInstrumentationMethodXml, this, 0, NULL));
DWORD retVal = WaitForSingleObject(hConfigThread, 15000);
#endif
if (m_bTestInstrumentationMethodLogging)
{
CComPtr<IProfilerManagerLogging> spGlobalLogger;
CComPtr<IProfilerManager4> pProfilerManager4;
IfFailRet(pProfilerManager->QueryInterface(&pProfilerManager4));
pProfilerManager4->GetGlobalLoggingInstance(&spGlobalLogger);
spGlobalLogger->LogDumpMessage(_T("<InstrumentationMethodLog>"));
CComPtr<IProfilerManagerLogging> spLogger;
pProfilerManager->GetLoggingInstance(&spLogger);
spGlobalLogger->LogDumpMessage(_T("<Message>"));
spLogger->LogMessage(_T("Message."));
spGlobalLogger->LogDumpMessage(_T("</Message>"));
spGlobalLogger->LogDumpMessage(_T("<Dump>"));
spLogger->LogDumpMessage(_T("Success!"));
spGlobalLogger->LogDumpMessage(_T("</Dump>"));
spGlobalLogger->LogDumpMessage(_T("<Error>"));
spLogger->LogError(_T("Error."));
spGlobalLogger->LogDumpMessage(_T("</Error>"));
}
else if (m_bExceptionTrackingEnabled)
{
CComPtr<ICorProfilerInfo> pCorProfilerInfo;
pProfilerManager->GetCorProfilerInfo((IUnknown**)&pCorProfilerInfo);
pCorProfilerInfo->SetEventMask(COR_PRF_MONITOR_EXCEPTIONS | COR_PRF_ENABLE_STACK_SNAPSHOT);
CComPtr<IProfilerManagerLogging> spLogger;
pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T("<ExceptionTrace>"));
}
return S_OK;
}
// The CLR doesn't initialize com before calling the profiler, and the profiler manager cannot do so itself
// as that would screw up the com state for the application's thread. Spin up a new thread to allow the instrumentation
// method to co create a free threaded version of msxml on a thread that it owns to avoid this.
DWORD WINAPI CInstrumentationMethod::LoadInstrumentationMethodXml(
_In_ LPVOID lpParameter
)
{
ComInitializer coInit;
CInstrumentationMethod* pThis = (CInstrumentationMethod*)lpParameter;
if (FAILED(pThis->LoadTestScript()))
{
return (DWORD)-1;
}
return 0;
}
HRESULT CInstrumentationMethod::LoadTestScript()
{
HRESULT hr = S_OK;
tstring testScript;
IfFailRet(NaglerSystemUtils::GetEnvVar(TestScriptFileEnvName, testScript));
IfFailRet(NaglerSystemUtils::GetEnvVar(TestOutputPathEnvName, m_strBinaryDir));
CComPtr<CXmlDocWrapper> pDocument;
pDocument.Attach(new CXmlDocWrapper());
hr = pDocument->LoadFile(testScript.c_str());
if (hr != S_OK)
{
AssertFailed("Failed to load test configuration");
return E_FAIL;
}
CComPtr<CXmlNode> pDocumentNode;
IfFailRet(pDocument->GetRootNode(&pDocumentNode));
tstring strDocumentNodeName;
IfFailRet(pDocumentNode->GetName(strDocumentNodeName));
if (wcscmp(strDocumentNodeName.c_str(), _T("InstrumentationTestScript")) != 0)
{
return E_FAIL;
}
CComPtr<CXmlNode> pChildNode;
IfFailRet(pDocumentNode->GetChildNode(&pChildNode));
while (pChildNode != nullptr)
{
tstring strCurrNodeName;
IfFailRet(pChildNode->GetName(strCurrNodeName));
if (wcscmp(strCurrNodeName.c_str(), _T("InstrumentMethod")) == 0)
{
IfFailRet(ProcessInstrumentMethodNode(pChildNode));
}
else if (wcscmp(strCurrNodeName.c_str(), _T("ExceptionTracking")) == 0)
{
m_bExceptionTrackingEnabled = true;
}
else if (wcscmp(strCurrNodeName.c_str(), _T("InjectAssembly")) == 0)
{
#ifndef PLATFORM_UNIX
shared_ptr<CInjectAssembly> spNewInjectAssembly(new CInjectAssembly());
ProcessInjectAssembly(pChildNode, spNewInjectAssembly);
m_spInjectAssembly = spNewInjectAssembly;
#else
AssertFailed("Inject Assembly tests are currently only supported on Windows platforms.");
#endif
}
else if (wcscmp(strCurrNodeName.c_str(), _T("MethodLogging")) == 0)
{
m_bTestInstrumentationMethodLogging = true;
}
else if (wcscmp(strCurrNodeName.c_str(), _T("#comment")) == 0)
{
// do nothing
}
else
{
std::string utf8NodeName;
SystemString::Convert(strCurrNodeName.c_str(), utf8NodeName);
AssertFailed("Invalid configuration. Element should be InstrumentationMethod");
AssertFailed(utf8NodeName.c_str());
return E_FAIL;
}
pChildNode = pChildNode->Next();
}
return 0;
}
HRESULT CInstrumentationMethod::ProcessInstrumentMethodNode(CXmlNode* pNode)
{
HRESULT hr = S_OK;
tstring isRejitEnvValue;
IfFailRet(NaglerSystemUtils::GetEnvVar(IsRejitEnvName, isRejitEnvValue));
bool rejitAllInstruMethods = (wcscmp(isRejitEnvValue.c_str(), _T("True")) == 0);
tstring moduleName;
tstring methodName;
BOOL bIsRejit = rejitAllInstruMethods;
vector<shared_ptr<CInstrumentInstruction>> instructions;
vector<CLocalType> locals;
vector<COR_IL_MAP> corIlMap;
BOOL isReplacement = FALSE;
BOOL isSingleRetFirst = FALSE;
BOOL isSingleRetLast = FALSE;
BOOL isAddExceptionHandler = FALSE;
shared_ptr<CInstrumentMethodPointTo> spPointTo(nullptr);
CComPtr<CXmlNode> pChildNode;
IfFailRet(pNode->GetChildNode(&pChildNode));
while (pChildNode != nullptr)
{
tstring strCurrNodeName;
IfFailRet(pChildNode->GetName(strCurrNodeName));
if (wcscmp(strCurrNodeName.c_str(), _T("ModuleName")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
IfFailRet(pChildValue->GetStringValue(moduleName));
}
else if (wcscmp(strCurrNodeName.c_str(), _T("MethodName")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
IfFailRet(pChildValue->GetStringValue(methodName));
}
else if (wcscmp(strCurrNodeName.c_str(), _T("Instructions")) == 0)
{
tstring baselineAttr;
pChildNode->GetAttribute(_T("Baseline"), baselineAttr);
isReplacement = !baselineAttr.empty();
ProcessInstructionNodes(pChildNode, instructions, isReplacement != 0);
}
else if (wcscmp(strCurrNodeName.c_str(), _T("IsRejit")) == 0)
{
CComPtr<CXmlNode> pChildValue;
tstring nodeValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
IfFailRet(pChildValue->GetStringValue(nodeValue));
bIsRejit = (wcscmp(nodeValue.c_str(), _T("True")) == 0);
}
else if (wcscmp(strCurrNodeName.c_str(), _T("AddExceptionHandler")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
tstring nodeValue;
IfFailRet(pChildValue->GetStringValue(nodeValue));
isAddExceptionHandler = (wcscmp(nodeValue.c_str(), _T("True")) == 0);
}
else if (wcscmp(strCurrNodeName.c_str(), _T("CorIlMap")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
tstring varNodeValue;
IfFailRet(pChildValue->GetStringValue(varNodeValue));
// This isn't a great way to do things because it is pretty slow, but there doesn't
// seem to be a good cross-platform way of converting strings to integers
// that matches the patterns that we are currently using.
// We may want to update the xml reader to support using whatever encoding
// is used on the system.
std::string utf8NodeValue;
SystemString::Convert(varNodeValue.c_str(), utf8NodeValue);
stringstream corIlMapString(utf8NodeValue);
DWORD oldOffset = 0;
DWORD newOffset = 0;
while ((bool)(corIlMapString >> oldOffset >> newOffset))
{
COR_IL_MAP map;
map.fAccurate = true;
map.oldOffset = oldOffset;
map.newOffset = newOffset;
corIlMap.push_back(map);
}
}
else if (wcscmp(strCurrNodeName.c_str(), _T("Locals")) == 0)
{
ProcessLocals(pChildNode, locals);
}
else if (wcscmp(strCurrNodeName.c_str(), _T("PointTo")) == 0)
{
std::shared_ptr<CInstrumentMethodPointTo> spPointer(new CInstrumentMethodPointTo());
spPointTo = spPointer;
ProcessPointTo(pChildNode, *spPointTo);
}
else if (wcscmp(strCurrNodeName.c_str(), _T("MakeSingleRet")) == 0)
{
// Allow the single return instrumentation to execute
// both before and after the instruction instrumentation.
if (instructions.empty())
{
isSingleRetFirst = true;
}
else
{
isSingleRetLast = true;
}
}
else if (wcscmp(strCurrNodeName.c_str(), _T("#comment")) == 0)
{
// do nothing. Get next node.
}
else
{
std::string utf8NodeName;
SystemString::Convert(strCurrNodeName.c_str(), utf8NodeName);
AssertFailed("Invalid configuration. Unknown Element");
AssertFailed(utf8NodeName.c_str());
return E_FAIL;
}
pChildNode = pChildNode->Next();
}
if ((moduleName.empty()) ||
(methodName.empty()))
{
AssertFailed("Invalid configuration. Missing child element");
return E_FAIL;
}
// if it is a replacement method, there will be no instructions
// do the single ret after the method is replaced.
if (isReplacement && isSingleRetFirst)
{
isSingleRetFirst = false;
isSingleRetLast = true;
}
shared_ptr<CInstrumentMethodEntry> pMethod = make_shared<CInstrumentMethodEntry>(moduleName, methodName, bIsRejit, isSingleRetFirst, isSingleRetLast, isAddExceptionHandler);
if (spPointTo != nullptr)
{
pMethod->SetPointTo(spPointTo);
}
pMethod->AddInstrumentInstructions(instructions);
if (corIlMap.size() > 0)
{
pMethod->AddCorILMap(corIlMap);
}
pMethod->SetReplacement(isReplacement);
m_instrumentMethodEntries.push_back(pMethod);
pMethod->AddLocals(locals);
return S_OK;
}
HRESULT CInstrumentationMethod::ProcessPointTo(CXmlNode* pNode, CInstrumentMethodPointTo& pointTo)
{
HRESULT hr = S_OK;
CComPtr<CXmlNode> pChildNode;
IfFailRet(pNode->GetChildNode(&pChildNode));
while (pChildNode != nullptr)
{
//<AssemblyName>InjectToMscorlibTest_Release</AssemblyName>
//<TypeName>InstruOperationsTests.Program</TypeName>
//<MethodName>MethodToCallInstead</MethodName>
tstring nodeName;
IfFailRet(pChildNode->GetName(nodeName));
if (wcscmp(nodeName.c_str(), _T("#comment")) == 0)
{
// do nothing, get next node.
}
else if (wcscmp(nodeName.c_str(), _T("AssemblyName")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
tstring varNodeValue;
IfFailRet(pChildValue->GetStringValue(pointTo.m_assemblyName));
}
else if (wcscmp(nodeName.c_str(), _T("TypeName")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
tstring varNodeValue;
IfFailRet(pChildValue->GetStringValue(pointTo.m_typeName));
}
else if (wcscmp(nodeName.c_str(), _T("MethodName")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
tstring varNodeValue;
IfFailRet(pChildValue->GetStringValue(pointTo.m_methodName));
}
pChildNode = pChildNode->Next();
}
return hr;
}
HRESULT CInstrumentationMethod::ProcessInjectAssembly(CXmlNode* pNode, shared_ptr<CInjectAssembly>& injectAssembly)
{
HRESULT hr = S_OK;
CComPtr<CXmlNode> pChildNode;
IfFailRet(pNode->GetChildNode(&pChildNode));
while (pChildNode != nullptr)
{
//<Source>C:\tfs\pioneer2\VSClient1\src\edev\diagnostics\intellitrace\InstrumentationEngine\Tests\InstrEngineTests\Binary\InjectToMscorlibTest_Debug.exe</Source>
//<Target>mscorlib</Target>
tstring nodeName;
IfFailRet(pChildNode->GetName(nodeName));
if (wcscmp(nodeName.c_str(), _T("#comment")) == 0)
{
// do nothing. Get next node.
}
else if (wcscmp(nodeName.c_str(), _T("Target")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
IfFailRet(pChildValue->GetStringValue(injectAssembly->m_targetAssemblyName));
}
else if (wcscmp(nodeName.c_str(), _T("Source")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pChildNode->GetChildNode(&pChildValue));
tstring varNodeValue;
IfFailRet(pChildValue->GetStringValue(injectAssembly->m_sourceAssemblyName));
}
pChildNode = pChildNode->Next();
}
return hr;
}
HRESULT CInstrumentationMethod::ProcessLocals(CXmlNode* pNode, vector<CLocalType>& locals)
{
HRESULT hr = S_OK;
CComPtr<CXmlNode> pChildNode;;
IfFailRet(pNode->GetChildNode(&pChildNode));
while (pChildNode != nullptr)
{
tstring nodeName;
IfFailRet(pChildNode->GetName(nodeName));
if (wcscmp(nodeName.c_str(), _T("#comment")) == 0)
{
// do nothing.
}
else
{
if (wcscmp(nodeName.c_str(), _T("Local")) != 0)
{
AssertFailed("Invalid element");
return E_UNEXPECTED;
}
tstring typeName;
IfFailRet(pChildNode->GetAttribute(_T("Type"), typeName));
locals.push_back(CLocalType(typeName));
}
pChildNode = pChildNode->Next();
}
return hr;
}
HRESULT CInstrumentationMethod::ProcessInstructionNodes(CXmlNode* pNode, vector<shared_ptr<CInstrumentInstruction>>& instructions, bool isBaseline)
{
HRESULT hr = S_OK;
CComPtr<CXmlNode> pChildNode;
IfFailRet(pNode->GetChildNode(&pChildNode));
while (pChildNode != nullptr)
{
tstring currNodeName;
IfFailRet(pChildNode->GetName(currNodeName));
if (wcscmp(currNodeName.c_str(), _T("#comment")) == 0)
{
// do nothing
}
else if (wcscmp(currNodeName.c_str(), _T("Instruction")) == 0)
{
CComPtr<CXmlNode> pInstructionChildNode;
IfFailRet(pChildNode->GetChildNode(&pInstructionChildNode));
bool bOpcodeSet = false;
bool bOffsetSet = false;
DWORD dwOffset = 0;
ILOrdinalOpcode opcode;
ILOpcodeInfo opcodeInfo;
InstrumentationType instrType = InsertBefore;
DWORD dwRepeatCount = 1;
// NOTE: only support integer operands for the time being.
INT64 operand = 0;
while (pInstructionChildNode != nullptr)
{
tstring currInstructionNodeName;
IfFailRet(pInstructionChildNode->GetName(currInstructionNodeName));
if (wcscmp(currInstructionNodeName.c_str(), _T("Opcode")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pInstructionChildNode->GetChildNode(&pChildValue));
tstring strOpcode;
IfFailRet(pChildValue->GetStringValue(strOpcode));
IfFailRet(ConvertOpcode(strOpcode.c_str(), &opcode, &opcodeInfo));
bOpcodeSet = true;
}
else if (wcscmp(currInstructionNodeName.c_str(), _T("Offset")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pInstructionChildNode->GetChildNode(&pChildValue));
tstring strOffset;
IfFailRet(pChildValue->GetStringValue(strOffset));
dwOffset = _wtoi(strOffset.c_str());
bOffsetSet = true;
}
else if (wcscmp(currInstructionNodeName.c_str(), _T("Operand")) == 0)
{
if (opcodeInfo.m_operandLength == 0)
{
AssertFailed("Invalid configuration. Opcode should not have an operand");
}
CComPtr<CXmlNode> pChildValue;
IfFailRet(pInstructionChildNode->GetChildNode(&pChildValue));
tstring strOperand;
IfFailRet(pChildValue->GetStringValue(strOperand));
operand = _wtoi64(strOperand.c_str());
// For now, only support integer operands
if (!(opcodeInfo.m_type == ILOperandType_None ||
opcodeInfo.m_type == ILOperandType_Byte ||
opcodeInfo.m_type == ILOperandType_Int ||
opcodeInfo.m_type == ILOperandType_UShort ||
opcodeInfo.m_type == ILOperandType_Long ||
opcodeInfo.m_type == ILOperandType_Token
))
{
AssertFailed("Unrecognized opcode");
}
}
else if (wcscmp(currInstructionNodeName.c_str(), _T("InstrumentationType")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pInstructionChildNode->GetChildNode(&pChildValue));
tstring strInstrType;
IfFailRet(pChildValue->GetStringValue(strInstrType));
if (wcscmp(strInstrType.c_str(), _T("InsertBefore")) == 0)
{
instrType = InsertBefore;
}
else if (wcscmp(strInstrType.c_str(), _T("InsertAfter")) == 0)
{
instrType = InsertAfter;
}
else if (wcscmp(strInstrType.c_str(), _T("Replace")) == 0)
{
instrType = Replace;
}
else if (wcscmp(strInstrType.c_str(), _T("Remove")) == 0)
{
instrType = Remove;
}
else if (wcscmp(strInstrType.c_str(), _T("RemoveAll")) == 0)
{
instrType = RemoveAll;
}
}
else if (wcscmp(currInstructionNodeName.c_str(), _T("RepeatCount")) == 0)
{
CComPtr<CXmlNode> pChildValue;
IfFailRet(pInstructionChildNode->GetChildNode(&pChildValue));
tstring strRepeatCount;
IfFailRet(pChildValue->GetStringValue(strRepeatCount));
dwRepeatCount = _wtoi(strRepeatCount.c_str());
}
else
{
AssertFailed("Invalid configuration. Unknown Element");
return E_FAIL;
}
pInstructionChildNode = pInstructionChildNode->Next();
}
if ( (!isBaseline) && (instrType != Remove) && (instrType != RemoveAll) && (!bOpcodeSet || !bOffsetSet))
{
AssertFailed("Invalid configuration. Instruction must have an offset");
return E_FAIL;
}
if (((instrType == Replace) || (instrType == Remove) || (instrType == RemoveAll)) && (dwRepeatCount != 1))
{
AssertFailed("Invalid configuration. Incorrect repeat count");
return E_FAIL;
}
shared_ptr<CInstrumentInstruction> pInstrumentInstruction = make_shared<CInstrumentInstruction>(dwOffset, opcode, opcodeInfo, operand, instrType, dwRepeatCount);
instructions.push_back(pInstrumentInstruction);
}
else
{
AssertFailed("Invalid configuration. Unknown Element");
return E_FAIL;
}
pChildNode = pChildNode->Next();
}
return S_OK;
}
HRESULT CInstrumentationMethod::ConvertOpcode(LPCWSTR zwOpcode, ILOrdinalOpcode* pOpcode, ILOpcodeInfo* pOpcodeInfo)
{
// Horribly slow solution to mapping opcode name to opcode.
// This should be okay though since the tests should only have a few instructions
const DWORD cOpcodes = 0x0124;
for (DWORD i = 0; i < 0x0124; i++)
{
if (wcscmp(ilOpcodeInfo[i].m_name, zwOpcode) == 0)
{
*pOpcode = (ILOrdinalOpcode)i;
*pOpcodeInfo = ilOpcodeInfo[i];
break;
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::OnAppDomainCreated(
_In_ IAppDomainInfo *pAppDomainInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnAppDomainShutdown(
_In_ IAppDomainInfo *pAppDomainInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnAssemblyLoaded(_In_ IAssemblyInfo* pAssemblyInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnAssemblyUnloaded(_In_ IAssemblyInfo* pAssemblyInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnModuleLoaded(_In_ IModuleInfo* pModuleInfo)
{
HRESULT hr = S_OK;
InstrStr(clrieStrModuleName);
IfFailRet(pModuleInfo->GetModuleName(&clrieStrModuleName.m_bstr));
// Skip importing modules on non-Windows platforms for now.
#ifndef PLATFORM_UNIX
if ((m_spInjectAssembly != nullptr) && (wcscmp(clrieStrModuleName, m_spInjectAssembly->m_targetAssemblyName.c_str()) == 0))
{
CComPtr<IMetaDataDispenserEx> pDisp;
ComInitializer coInit(COINIT_MULTITHREADED);
IfFailRet(CoCreateInstance(CLSID_CorMetaDataDispenser, NULL, CLSCTX_INPROC_SERVER,
IID_IMetaDataDispenserEx, (void **)&pDisp));
CComPtr<IMetaDataImport2> pSourceImport;
tstring path(m_strBinaryDir + _T("\\") + m_spInjectAssembly->m_sourceAssemblyName);
IfFailRet(pDisp->OpenScope(path.c_str(), 0, IID_IMetaDataImport2, (IUnknown **)&pSourceImport));
// Loads the image with section alignment, but doesn't do any of the other steps to ready an image to run
// This is sufficient to read IL code from the image without doing RVA -> file offset mapping
std::shared_ptr<HINSTANCE__> spSourceImage(LoadLibraryEx(path.c_str(), NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE), FreeLibrary);
if (spSourceImage == nullptr)
{
return HRESULT_FROM_WIN32(::GetLastError());
}
//Not sure if there is a better way to get the base address of a module loaded via LoadLibrary?
//We are cheating a bit knowing that module handles are actually base addresses with a few bits OR'ed in
LPCBYTE* pSourceImage = reinterpret_cast<LPCBYTE*>((ULONGLONG)spSourceImage.get() & (~2));
IfFailRet(pModuleInfo->ImportModule(pSourceImport, pSourceImage));
}
#endif
// get the moduleId and method token for instrument method entry
for (shared_ptr<CInstrumentMethodEntry> pInstrumentMethodEntry : m_instrumentMethodEntries)
{
const tstring& instrModuleName = pInstrumentMethodEntry->GetModuleName();
if (wcscmp(clrieStrModuleName, instrModuleName.c_str()) == 0)
{
// search for method name inside all the types of the matching module
const tstring& methodName = pInstrumentMethodEntry->GetMethodName();
CComPtr<IMetaDataImport2> pMetadataImport;
IfFailRet(pModuleInfo->GetMetaDataImport((IUnknown**)&pMetadataImport));
BOOL bIsRejit = pInstrumentMethodEntry->GetIsRejit();
// Only request ReJIT if the method will modify code on ReJIT. On .NET Core, the runtime will
// only callback into the profiler for the ReJIT of the method if ReJIT is requested whereas the
// appropriate callbacks are made for both JIT and ReJIT on .NET Framework.
if (bIsRejit)
{
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataImport2> spTypeDefEnum(pMetadataImport, nullptr);
mdTypeDef typeDef = mdTypeDefNil;
ULONG cTokens = 0;
while (S_OK == (hr = pMetadataImport->EnumTypeDefs(spTypeDefEnum.Get(), &typeDef, 1, &cTokens)))
{
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataImport2> spMethodEnum(pMetadataImport, nullptr);
mdToken methodDefs[16];
ULONG cMethod = 0;
pMetadataImport->EnumMethodsWithName(spMethodEnum.Get(), typeDef, methodName.c_str(), methodDefs, extent<decltype(methodDefs)>::value, &cMethod);
if (cMethod > 0)
{
pModuleInfo->RequestRejit(methodDefs[0]);
break;
}
}
}
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::OnModuleUnloaded(_In_ IModuleInfo* pModuleInfo)
{
return S_OK;
}
HRESULT CInstrumentationMethod::OnShutdown()
{
HRESULT hr = S_OK;
if (m_bExceptionTrackingEnabled)
{
CComPtr<IProfilerManagerLogging> spLogger;
m_pProfilerManager->GetLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T("</ExceptionTrace>"));
}
else if (m_bTestInstrumentationMethodLogging)
{
CComPtr<IProfilerManagerLogging> spLogger;
CComPtr<IProfilerManager4> pProfilerManager4;
IfFailRet(m_pProfilerManager->QueryInterface(&pProfilerManager4));
pProfilerManager4->GetGlobalLoggingInstance(&spLogger);
spLogger->LogDumpMessage(_T("</InstrumentationMethodLog>"));
}
return hr;
}
HRESULT CInstrumentationMethod::ShouldInstrumentMethod(_In_ IMethodInfo* pMethodInfo, _In_ BOOL isRejit, _Out_ BOOL* pbInstrument)
{
*pbInstrument = FALSE;
HRESULT hr;
CComPtr<IModuleInfo> pModuleInfo;
pMethodInfo->GetModuleInfo(&pModuleInfo);
InstrStr(clrieStrModule);
IfFailRet(pModuleInfo->GetModuleName(&clrieStrModule.m_bstr));
tstring moduleName = clrieStrModule.BStr();
for (shared_ptr<CInstrumentMethodEntry> pInstrumentMethodEntry : m_instrumentMethodEntries)
{
const tstring& enteryModuleName = pInstrumentMethodEntry->GetModuleName();
if (wcscmp(enteryModuleName.c_str(), clrieStrModule) == 0)
{
// TODO: Eventually, this will need to use the full name and not the partial name
InstrStr(clrieStrMethodName);
pMethodInfo->GetName(&clrieStrMethodName.m_bstr);
const tstring& entryMethodName= pInstrumentMethodEntry->GetMethodName();
if (wcscmp(entryMethodName.c_str(), clrieStrMethodName) == 0)
{
m_methodInfoToEntryMap[pMethodInfo] = pInstrumentMethodEntry;
BOOL bRequireRejit = pInstrumentMethodEntry->GetIsRejit();
*pbInstrument = (bRequireRejit == isRejit);
return S_OK;
}
}
}
return S_OK;
}
HRESULT CInstrumentationMethod::BeforeInstrumentMethod(_In_ IMethodInfo* pMethodInfo, _In_ BOOL isRejit)
{
HRESULT hr = S_OK;
shared_ptr<CInstrumentMethodEntry> pMethodEntry = m_methodInfoToEntryMap[pMethodInfo];
if (!pMethodEntry)
{
AssertFailed("CInstrumentationMethod::InstrumentMethod - why no method entry? It should have been set in ShouldInstrumentMethod");
return E_FAIL;
}
BOOL bRequireRejit = pMethodEntry->GetIsRejit();
if (bRequireRejit != isRejit)
{
return E_FAIL;
}
vector<shared_ptr<CInstrumentInstruction>> instructions = pMethodEntry->GetInstructions();
CComPtr<IInstructionGraph> pInstructionGraph;
IfFailRet(pMethodInfo->GetInstructions(&pInstructionGraph));
if (pMethodEntry->IsReplacement())
{
vector<BYTE> ilCode;
for (shared_ptr<CInstrumentInstruction> instruction : instructions)
{
IfFailRet(instruction->EmitIL(ilCode));
}
vector<COR_IL_MAP> corIlMap = pMethodEntry->GetCorILMap();
// TODO: (wiktor) add sequence points to test
vector<DWORD> baselineSequencePoints;
baselineSequencePoints.resize(corIlMap.size());
for (size_t i = 0; i < baselineSequencePoints.size(); i++)
{
baselineSequencePoints[i] = corIlMap[i].newOffset;
}
IfFailRet(pInstructionGraph->CreateBaseline(ilCode.data(), ilCode.data() + ilCode.size(), (DWORD)corIlMap.size(), corIlMap.data(), (DWORD)baselineSequencePoints.size(), baselineSequencePoints.data()));
}
return hr;
}
HRESULT CInstrumentationMethod::InstrumentMethod(_In_ IMethodInfo* pMethodInfo, _In_ BOOL isRejit)
{
HRESULT hr = S_OK;
shared_ptr<CInstrumentMethodEntry> pMethodEntry = m_methodInfoToEntryMap[pMethodInfo];
if (!pMethodEntry)
{
AssertFailed("CInstrumentationMethod::InstrumentMethod - why no method entry? It should have been set in ShouldInstrumentMethod");
return E_FAIL;
}
BOOL bRequireRejit = pMethodEntry->GetIsRejit();
if (bRequireRejit != isRejit)
{
return E_FAIL;
}
vector<shared_ptr<CInstrumentInstruction>> instructions = pMethodEntry->GetInstructions();
CComPtr<IInstructionGraph> pInstructionGraph;
IfFailRet(pMethodInfo->GetInstructions(&pInstructionGraph));
if (pMethodEntry->IsSingleRetFirst())
{
PerformSingleReturnInstrumentation(pMethodInfo, pInstructionGraph);
}
if (pMethodEntry->GetPointTo() != nullptr)
{
std::shared_ptr<CInstrumentMethodPointTo> spPointTo = pMethodEntry->GetPointTo();
BYTE pSignature[256] = {};
DWORD cbSignature = 0;
pMethodInfo->GetCorSignature(extent<decltype(pSignature)>::value, pSignature, &cbSignature);
mdToken tkMethodToken = mdTokenNil;
CComPtr<IModuleInfo> spModuleInfo;
IfFailRet(pMethodInfo->GetModuleInfo(&spModuleInfo));
mdToken tkMscorlibRef = mdTokenNil;
CComPtr<IMetaDataAssemblyImport> spIMetaDataAssemblyImport;
IfFailRet(spModuleInfo->GetMetaDataAssemblyImport(
reinterpret_cast<IUnknown**>(&spIMetaDataAssemblyImport)));
const auto MaxReferenceCount = 256;
std::vector<mdAssemblyRef> vecAssemblyRefs(MaxReferenceCount, mdAssemblyRefNil);
ULONG ulReceivedCount = 0;
MicrosoftInstrumentationEngine::CMetadataEnumCloser<IMetaDataAssemblyImport> spEnum(spIMetaDataAssemblyImport, nullptr);
IfFailRet(spIMetaDataAssemblyImport->EnumAssemblyRefs(
spEnum.Get(),
&vecAssemblyRefs[0],
static_cast<ULONG>(vecAssemblyRefs.size()),
&ulReceivedCount));
vecAssemblyRefs.resize(ulReceivedCount);
for (mdAssemblyRef tkAssemblyRef : vecAssemblyRefs)
{
LPCVOID pbPublicKey = nullptr;
ULONG cbPublicKey = 0;
LPCVOID pbHashValue = nullptr;
ULONG cbHashValue = 0;
ULONG chName = 0;
tstring strName(MAX_PATH, WCHAR());
DWORD dwAsemblyRefFlags = 0;
ASSEMBLYMETADATA asmMetadata = { 0 };
if (SUCCEEDED(spIMetaDataAssemblyImport->GetAssemblyRefProps(
tkAssemblyRef,
&pbPublicKey,
&cbPublicKey,
&strName[0],
static_cast<ULONG>(strName.size()),
&chName,
&asmMetadata,
&pbHashValue,
&cbHashValue,
&dwAsemblyRefFlags)))
{
strName.resize(0 == chName ? chName : chName - 1);
if (0 == strName.compare(spPointTo->m_assemblyName))
{
tkMscorlibRef = tkAssemblyRef;
break;
}
}
}
CComPtr<IMetaDataImport> spIMetaDataImport;
IfFailRet(spModuleInfo->GetMetaDataImport(
reinterpret_cast<IUnknown**>(&spIMetaDataImport)));
mdToken tkTypeToken;