-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathdacdbiimpl.cpp
7880 lines (6614 loc) · 281 KB
/
dacdbiimpl.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// File: DacDbiImpl.cpp
//
//
// Implement DAC/DBI interface
//
//*****************************************************************************
#include "stdafx.h"
#include "dacdbiinterface.h"
#include "typestring.h"
#include "holder.h"
#include "debuginfostore.h"
#include "peimagelayout.inl"
#include "encee.h"
#include "switches.h"
#include "generics.h"
#include "stackwalk.h"
#include "virtualcallstub.h"
#include "dacdbiimpl.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "comcallablewrapper.h"
#endif // FEATURE_COMINTEROP
#include "request_common.h"
//-----------------------------------------------------------------------------
// Have standard enter and leave macros at the DacDbi boundary to enforce
// standard behavior.
// 1. catch exceptions and convert them at the boundary.
// 2. provide a space to hook logging and transitions.
// 3. provide a hook to verify return values.
//
// Usage notes:
// - use this at the DacDbi boundary; but not at internal functions
// - it's ok to Return from the middle.
//
// Expected usage is:
// Foo()
// {
// DD_ENTER_MAY_THROW
// ...
// if (...) { ThrowHr(E_SOME_FAILURE); }
// ...
// if (...) { return; } // early success case
// ...
// }
//-----------------------------------------------------------------------------
// Global allocator for DD. Access is protected under the g_dacCritSec lock.
IDacDbiInterface::IAllocator * g_pAllocator = NULL;
//---------------------------------------------------------------------------------------
//
// Extra sugar for wrapping IAllocator under friendly New/Delete operators.
//
// Sample usage:
// void Foo(TestClass ** ppOut)
// {
// *ppOut = NULL;
// TestClass * p = new (forDbi) TestClass();
// ...
// if (ok)
// {
// *ppOut = p;
// return; // DBI will then free this memory.
// }
// ...
// DeleteDbiMemory(p); // DeleteDbiMemory(p, len); if it was an array allocation.
// }
//
// Be very careful when using this on classes since Dbi and DAC may be in
// separate dlls. This is best used when operating on blittable data-structures.
// (no ctor/dtor, plain data fields) to guarantee the proper DLL isolation.
// You don't want to call the ctor in DAC's context and the dtor in DBI's context
// unless you really know what you're doing and that it's safe.
//
// Need a class to serve as a tag that we can use to overload New/Delete.
forDbiWorker forDbi;
void * operator new(size_t lenBytes, const forDbiWorker &)
{
_ASSERTE(g_pAllocator != NULL);
void *result = g_pAllocator->Alloc(lenBytes);
if (result == NULL)
{
ThrowOutOfMemory();
}
return result;
}
void * operator new[](size_t lenBytes, const forDbiWorker &)
{
_ASSERTE(g_pAllocator != NULL);
void *result = g_pAllocator->Alloc(lenBytes);
if (result == NULL)
{
ThrowOutOfMemory();
}
return result;
}
// Note: there is no C++ syntax for manually invoking this, but if a constructor throws an exception I understand that
// this delete operator will be invoked automatically to destroy the object.
void operator delete(void *p, const forDbiWorker &)
{
if (p == NULL)
{
return;
}
_ASSERTE(g_pAllocator != NULL);
g_pAllocator->Free((BYTE*) p);
}
// Note: there is no C++ syntax for manually invoking this, but if a constructor throws an exception I understand that
// this delete operator will be invoked automatically to destroy the object.
void operator delete[](void *p, const forDbiWorker &)
{
if (p == NULL)
{
return;
}
_ASSERTE(g_pAllocator != NULL);
g_pAllocator->Free((BYTE*) p);
}
// @dbgtodo dac support: determine how to handle an array of class instances to ensure the dtors get
// called correctly or document that they won't
// Delete memory and invoke dtor for memory allocated with 'operator (forDbi) new'
template<class T> void DeleteDbiMemory(T *p)
{
if (p == NULL)
{
return;
}
p->~T();
_ASSERTE(g_pAllocator != NULL);
g_pAllocator->Free((BYTE*) p);
}
void* AllocDbiMemory(size_t size)
{
void *result;
if (g_pAllocator != nullptr)
{
result = g_pAllocator->Alloc(size);
}
else
{
result = new (nothrow) BYTE[size];
}
if (result == NULL)
{
ThrowOutOfMemory();
}
return result;
}
void DeleteDbiMemory(void* p)
{
if (p == NULL)
{
return;
}
if (g_pAllocator != nullptr)
{
g_pAllocator->Free((BYTE*)p);
}
else
{
::delete (BYTE*)p;
}
}
// Delete memory and invoke dtor for memory allocated with 'operator (forDbi) new[]'
// There's an inherent risk here - where each element's destructor will get called within
// the context of the DAC. If the destructor tries to use the CRT allocator logic expecting
// to hit the DBI's, we could be in trouble. Those objects need to use an export allocator like this.
template<class T> void DeleteDbiArrayMemory(T *p, int count)
{
if (p == NULL)
{
return;
}
for (T *cur = p; cur < p + count; cur++)
{
cur->~T();
}
_ASSERTE(g_pAllocator != NULL);
g_pAllocator->Free((BYTE*) p);
}
//---------------------------------------------------------------------------------------
// Creates the DacDbiInterface object, used by Dbi.
//
// Arguments:
// pTarget - pointer to a Data-Target
// baseAddress - non-zero base address of mscorwks in target to debug.
// pAllocator - pointer to client allocator object. This lets DD allocate objects and
// pass them out back to the client, which can then delete them.
// DD takes a weak ref to this, so client must keep it alive until it
// calls Destroy.
// pMetadataLookup - callback interface to do internal metadata lookup. This is because
// metadata is not dac-ized.
// ppInterface - mandatory out-parameter
//
// Return Value:
// S_OK on success.
//
//
// Notes:
// On Windows, this is public function that can be retrieved by GetProcAddress.
// On Mac, this is used internally by DacDbiMarshalStubInstance below
// This will yield an IDacDbiInterface to provide structured access to the
// data-target.
//
// Must call Destroy to on interface to free its resources.
//
//---------------------------------------------------------------------------------------
STDAPI
DLLEXPORT
DacDbiInterfaceInstance(
ICorDebugDataTarget * pTarget,
CORDB_ADDRESS baseAddress,
IDacDbiInterface::IAllocator * pAllocator,
IDacDbiInterface::IMetaDataLookup * pMetaDataLookup,
IDacDbiInterface ** ppInterface)
{
// No marshalling is done by the instantiationf function - we just need to setup the infrastructure.
// We don't want to warn if this involves creating and accessing undacized data structures,
// because it's for the infrastructure, not DACized code itself.
SUPPORTS_DAC_HOST_ONLY;
// Since this is public, verify it.
if ((ppInterface == NULL) || (pTarget == NULL) || (baseAddress == 0))
{
return E_INVALIDARG;
}
*ppInterface = NULL;
//
// Actually allocate the real object and initialize it.
//
DacDbiInterfaceImpl * pDac = new (nothrow) DacDbiInterfaceImpl(pTarget, baseAddress, pAllocator, pMetaDataLookup);
if (!pDac)
{
return E_OUTOFMEMORY;
}
HRESULT hrStatus = pDac->Initialize();
if (SUCCEEDED(hrStatus))
{
*ppInterface = pDac;
}
else
{
delete pDac;
}
return hrStatus;
}
//---------------------------------------------------------------------------------------
// Constructor. Instantiates a DAC/DBI interface around a DataTarget.
//
// Arguments:
// pTarget - pointer to a Data-Target
// baseAddress - non-zero base address of mscorwks in target to debug.
// pAllocator - pointer to client allocator object. This lets DD allocate objects and
// pass them out back to the client, which can then delete them.
// DD takes a weak ref to this, so client must keep it alive until it
// calls Destroy.
// pMetadataLookup - callback interface to do internal metadata lookup. This is because
// metadata is not dac-ized.
//
// Notes:
// pAllocator is a weak reference.
//---------------------------------------------------------------------------------------
DacDbiInterfaceImpl::DacDbiInterfaceImpl(
ICorDebugDataTarget* pTarget,
CORDB_ADDRESS baseAddress,
IAllocator * pAllocator,
IMetaDataLookup * pMetaDataLookup
) : ClrDataAccess(pTarget),
m_pAllocator(pAllocator),
m_pMetaDataLookup(pMetaDataLookup),
m_pCachedPEAssembly(VMPTR_PEAssembly::NullPtr()),
m_pCachedImporter(NULL),
m_isCachedHijackFunctionValid(FALSE)
{
_ASSERTE(baseAddress != NULL);
m_globalBase = CORDB_ADDRESS_TO_TADDR(baseAddress);
_ASSERTE(pMetaDataLookup != NULL);
_ASSERTE(pAllocator != NULL);
_ASSERTE(pTarget != NULL);
#ifdef _DEBUG
// Enable verification asserts in ICorDebug scenarios. ICorDebug never guesses at the DAC path, so any
// mismatch should be fatal, and so always of interest to the user.
// This overrides the assignment in the base class ctor (which runs first).
m_fEnableDllVerificationAsserts = true;
#endif
}
//-----------------------------------------------------------------------------
// Destructor.
//
// Notes:
// This gets invoked after Destroy().
//-----------------------------------------------------------------------------
DacDbiInterfaceImpl::~DacDbiInterfaceImpl()
{
SUPPORTS_DAC_HOST_ONLY;
// This will automatically chain to the base class dtor
}
//-----------------------------------------------------------------------------
// Called from DAC-ized code to get a IMDInternalImport
//
// Arguments:
// pPEAssembly - PE file for which to get importer for
// fThrowEx - if true, throw instead of returning NULL.
//
// Returns:
// an Internal importer object for this file.
// May return NULL or throw (depending on fThrowEx).
// May throw in exceptional circumstances (eg, corrupt debuggee).
//
// Assumptions:
// This is called from DAC-ized code within the VM, which
// was in turn called from some DD primitive. The returned importer will
// be used by the DAC-ized code in the callstack, but it won't be cached.
//
// Notes:
// This is an Internal importer, not a public Metadata importer.
//
interface IMDInternalImport* DacDbiInterfaceImpl::GetMDImport(
const PEAssembly* pPEAssembly,
const ReflectionModule * pReflectionModule,
bool fThrowEx)
{
// Since this is called from an existing DAC-primitive, we already hold the g_dacCritSec lock.
// The lock conveniently protects our cache.
SUPPORTS_DAC;
IDacDbiInterface::IMetaDataLookup * pLookup = m_pMetaDataLookup;
_ASSERTE(pLookup != NULL);
VMPTR_PEAssembly vmPEAssembly = VMPTR_PEAssembly::NullPtr();
if (pPEAssembly != NULL)
{
vmPEAssembly.SetHostPtr(pPEAssembly);
}
else if (pReflectionModule != NULL)
{
// SOS and ClrDataAccess rely on special logic to find the metadata for methods in dynamic modules.
// We don't need to. The RS has already taken care of the special logic for us.
// So here we just grab the PEAssembly off of the ReflectionModule and continue down the normal
// code path. See code:ClrDataAccess::GetMDImport for comparison.
vmPEAssembly.SetHostPtr(pReflectionModule->GetPEAssembly());
}
// Optimize for the case where the VM queries the same Importer many times in a row.
if (m_pCachedPEAssembly == vmPEAssembly)
{
return m_pCachedImporter;
}
// Go to DBI to find the metadata.
IMDInternalImport * pInternal = NULL;
bool isILMetaDataForNI = false;
EX_TRY
{
// If test needs it in the future, prop isILMetaDataForNI back up to
// ClrDataAccess.m_mdImports.Add() call.
// example in code:ClrDataAccess::GetMDImport
// CordbModule::GetMetaDataInterface also looks up MetaData and would need attention.
// This is the new codepath that uses ICorDebugMetaDataLookup.
// To get the old codepath that uses the v2 metadata lookup methods,
// you'd have to load DAC only and then you'll get ClrDataAccess's implementation
// of this function.
pInternal = pLookup->LookupMetaData(vmPEAssembly, isILMetaDataForNI);
}
EX_CATCH
{
// Any expected error we should ignore.
if ((GET_EXCEPTION()->GetHR() != HRESULT_FROM_WIN32(ERROR_PARTIAL_COPY)) &&
(GET_EXCEPTION()->GetHR() != CORDBG_E_READVIRTUAL_FAILURE) &&
(GET_EXCEPTION()->GetHR() != CORDBG_E_SYMBOLS_NOT_AVAILABLE) &&
(GET_EXCEPTION()->GetHR() != CORDBG_E_MODULE_LOADED_FROM_DISK))
{
EX_RETHROW;
}
}
EX_END_CATCH(SwallowAllExceptions)
if (pInternal == NULL)
{
SIMPLIFYING_ASSUMPTION(!"MD lookup failed");
if (fThrowEx)
{
ThrowHR(E_FAIL);
}
return NULL;
}
else
{
// Cache it such that it we look for the exact same Importer again, we'll return it.
m_pCachedPEAssembly = vmPEAssembly;
m_pCachedImporter = pInternal;
}
return pInternal;
}
//-----------------------------------------------------------------------------
// Implementation of IDacDbiInterface
// See DacDbiInterface.h for full descriptions of all of these functions
//-----------------------------------------------------------------------------
// Destroy the connection, freeing up any resources.
void DacDbiInterfaceImpl::Destroy()
{
m_pAllocator = NULL;
this->Release();
// Memory is deleted, don't access this object any more
}
// Check whether the version of the DBI matches the version of the runtime.
// See code:CordbProcess::CordbProcess#DBIVersionChecking for more information regarding version checking.
HRESULT DacDbiInterfaceImpl::CheckDbiVersion(const DbiVersion * pVersion)
{
DD_ENTER_MAY_THROW;
if (pVersion->m_dwFormat != kCurrentDbiVersionFormat)
{
return CORDBG_E_INCOMPATIBLE_PROTOCOL;
}
if ((pVersion->m_dwProtocolBreakingChangeCounter != kCurrentDacDbiProtocolBreakingChangeCounter) ||
(pVersion->m_dwReservedMustBeZero1 != 0))
{
return CORDBG_E_INCOMPATIBLE_PROTOCOL;
}
return S_OK;
}
// Flush the DAC cache. This should be called when target memory changes.
HRESULT DacDbiInterfaceImpl::FlushCache()
{
// Non-reentrant. We don't want to flush cached instances from a callback.
// That would remove host DAC instances while they're being used.
DD_NON_REENTRANT_MAY_THROW;
m_pCachedPEAssembly = VMPTR_PEAssembly::NullPtr();
m_pCachedImporter = NULL;
m_isCachedHijackFunctionValid = FALSE;
HRESULT hr = ClrDataAccess::Flush();
// Current impl of Flush() should always succeed. If it ever fails, we want to know.
_ASSERTE(SUCCEEDED(hr));
return hr;
}
// enable or disable DAC target consistency checks
void DacDbiInterfaceImpl::DacSetTargetConsistencyChecks(bool fEnableAsserts)
{
// forward on to our ClrDataAccess base class
ClrDataAccess::SetTargetConsistencyChecks(fEnableAsserts);
}
// Query if Left-side is started up?
BOOL DacDbiInterfaceImpl::IsLeftSideInitialized()
{
DD_ENTER_MAY_THROW;
if (g_pDebugger != NULL)
{
// This check is "safe".
// The initialize order in the left-side is:
// 1) g_pDebugger is an RVA based global initialized to NULL when the module is loaded.
// 2) Allocate a "Debugger" object.
// 3) run the ctor, which will set m_fLeftSideInitialized = FALSE.
// 4) assign the object to g_pDebugger.
// 5) later, LS initialization code will assign g_pDebugger->m_fLeftSideInitialized = TRUE.
//
// The memory write in #5 is atomic. There is no window where we're reading unitialized data.
return (g_pDebugger->m_fLeftSideInitialized != 0);
}
return FALSE;
}
// Determines if a given address is a CLR stub.
BOOL DacDbiInterfaceImpl::IsTransitionStub(CORDB_ADDRESS address)
{
DD_ENTER_MAY_THROW;
BOOL fIsStub = FALSE;
#if defined(TARGET_UNIX)
// Currently IsIPInModule() is not implemented in the PAL. Rather than skipping the check, we should
// either E_NOTIMPL this API or implement IsIPInModule() in the PAL. Since ICDProcess::IsTransitionStub()
// is only called by VS in mixed-mode debugging scenarios, and mixed-mode debugging is not supported on
// POSIX systems, there is really no incentive to implement this API at this point.
ThrowHR(E_NOTIMPL);
#else // !TARGET_UNIX
TADDR ip = (TADDR)address;
if (ip == NULL)
{
fIsStub = FALSE;
}
else
{
fIsStub = StubManager::IsStub(ip);
}
// If it's in Mscorwks, count that as a stub too.
if (fIsStub == FALSE)
{
fIsStub = IsIPInModule(m_globalBase, ip);
}
#endif // TARGET_UNIX
return fIsStub;
}
// Gets the type of 'address'.
IDacDbiInterface::AddressType DacDbiInterfaceImpl::GetAddressType(CORDB_ADDRESS address)
{
DD_ENTER_MAY_THROW;
TADDR taAddr = CORDB_ADDRESS_TO_TADDR(address);
if (IsPossibleCodeAddress(taAddr) == S_OK)
{
if (ExecutionManager::IsManagedCode(taAddr))
{
return kAddressManagedMethod;
}
if (StubManager::IsStub(taAddr))
{
return kAddressRuntimeUnmanagedStub;
}
}
return kAddressUnrecognized;
}
// Get a VM appdomain pointer that matches the appdomain ID
VMPTR_AppDomain DacDbiInterfaceImpl::GetAppDomainFromId(ULONG appdomainId)
{
DD_ENTER_MAY_THROW;
VMPTR_AppDomain vmAppDomain;
// @dbgtodo dac support - We would like to wean ourselves off the IXClrData interfaces.
IXCLRDataProcess * pDAC = this;
ReleaseHolder<IXCLRDataAppDomain> pDacAppDomain;
HRESULT hrStatus = pDAC->GetAppDomainByUniqueID(appdomainId, &pDacAppDomain);
IfFailThrow(hrStatus);
IXCLRDataAppDomain * pIAppDomain = pDacAppDomain;
AppDomain * pAppDomain = (static_cast<ClrDataAppDomain *> (pIAppDomain))->GetAppDomain();
SIMPLIFYING_ASSUMPTION(pAppDomain != NULL);
if (pAppDomain == NULL)
{
ThrowHR(E_FAIL); // corrupted left-side?
}
TADDR addrAppDomain = PTR_HOST_TO_TADDR(pAppDomain);
vmAppDomain.SetDacTargetPtr(addrAppDomain);
return vmAppDomain;
}
// Get the AppDomain ID for an AppDomain.
ULONG DacDbiInterfaceImpl::GetAppDomainId(VMPTR_AppDomain vmAppDomain)
{
DD_ENTER_MAY_THROW;
if (vmAppDomain.IsNull())
{
return 0;
}
else
{
AppDomain * pAppDomain = vmAppDomain.GetDacPtr();
return DefaultADID;
}
}
// Get the managed AppDomain object for an AppDomain.
VMPTR_OBJECTHANDLE DacDbiInterfaceImpl::GetAppDomainObject(VMPTR_AppDomain vmAppDomain)
{
DD_ENTER_MAY_THROW;
AppDomain* pAppDomain = vmAppDomain.GetDacPtr();
OBJECTHANDLE hAppDomainManagedObject = pAppDomain->GetRawExposedObjectHandleForDebugger();
VMPTR_OBJECTHANDLE vmObj = VMPTR_OBJECTHANDLE::NullPtr();
vmObj.SetDacTargetPtr(hAppDomainManagedObject);
return vmObj;
}
// Get the full AD friendly name for the given EE AppDomain.
void DacDbiInterfaceImpl::GetAppDomainFullName(
VMPTR_AppDomain vmAppDomain,
IStringHolder * pStrName )
{
DD_ENTER_MAY_THROW;
AppDomain * pAppDomain = vmAppDomain.GetDacPtr();
// Get the AppDomain name from the VM without changing anything
// We might be able to simplify this, eg. by returning an SString.
bool fIsUtf8;
PVOID pRawName = pAppDomain->GetFriendlyNameNoSet(&fIsUtf8);
if (!pRawName)
{
ThrowHR(E_NOINTERFACE);
}
HRESULT hrStatus = S_OK;
if (fIsUtf8)
{
// we have to allocate a temporary string
// we could avoid this by adding a version of IStringHolder::AssignCopy that takes a UTF8 string
// We should also probably check to see when fIsUtf8 is ever true (it looks like it should normally be false).
ULONG32 dwNameLen = 0;
hrStatus = ConvertUtf8((LPCUTF8)pRawName, 0, &dwNameLen, NULL);
if (SUCCEEDED( hrStatus ))
{
NewArrayHolder<WCHAR> pwszName(new WCHAR[dwNameLen]);
hrStatus = ConvertUtf8((LPCUTF8)pRawName, dwNameLen, &dwNameLen, pwszName );
IfFailThrow(hrStatus);
hrStatus = pStrName->AssignCopy(pwszName);
}
}
else
{
hrStatus = pStrName->AssignCopy(static_cast<PCWSTR>(pRawName));
}
// Very important that this either sets pStrName or Throws.
// Don't set it and then then throw.
IfFailThrow(hrStatus);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// JIT Compiler Flags
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Get the values of the JIT Optimization and EnC flags.
void DacDbiInterfaceImpl::GetCompilerFlags (
VMPTR_DomainAssembly vmDomainAssembly,
BOOL *pfAllowJITOpts,
BOOL *pfEnableEnC)
{
DD_ENTER_MAY_THROW;
DomainAssembly * pDomainAssembly = vmDomainAssembly.GetDacPtr();
if (pDomainAssembly == NULL)
{
ThrowHR(E_FAIL);
}
// Get the underlying module - none of this is AppDomain specific
Module * pModule = pDomainAssembly->GetModule();
DWORD dwBits = pModule->GetDebuggerInfoBits();
*pfAllowJITOpts = !CORDisableJITOptimizations(dwBits);
*pfEnableEnC = pModule->IsEditAndContinueEnabled();
} //GetCompilerFlags
//-----------------------------------------------------------------------------
// Helper function for SetCompilerFlags to set EnC status.
// Arguments:
// Input:
// pModule - The runtime module for which flags are being set.
//
// Return value:
// true if the Enc bits can be set on this module
//-----------------------------------------------------------------------------
bool DacDbiInterfaceImpl::CanSetEnCBits(Module * pModule)
{
_ASSERTE(pModule != NULL);
#ifdef EnC_SUPPORTED
// If we're using explicit sequence points (from the PDB), then we can't do EnC
// because EnC won't get updated pdbs and so the sequence points will be wrong.
bool fIgnorePdbs = ((pModule->GetDebuggerInfoBits() & DACF_IGNORE_PDBS) != 0);
bool fAllowEnc = pModule->IsEditAndContinueCapable() &&
#ifdef PROFILING_SUPPORTED_DATA
!CORProfilerPresent() && // this queries target
#endif
fIgnorePdbs;
#else // ! EnC_SUPPORTED
// Enc not supported on any other platforms.
bool fAllowEnc = false;
#endif
return fAllowEnc;
} // DacDbiInterfaceImpl::SetEnCBits
// Set the values of the JIT optimization and EnC flags.
HRESULT DacDbiInterfaceImpl::SetCompilerFlags(VMPTR_DomainAssembly vmDomainAssembly,
BOOL fAllowJitOpts,
BOOL fEnableEnC)
{
DD_ENTER_MAY_THROW;
DWORD dwBits = 0;
DomainAssembly * pDomainAssembly = vmDomainAssembly.GetDacPtr();
Module * pModule = pDomainAssembly->GetModule();
HRESULT hr = S_OK;
_ASSERTE(pModule != NULL);
// Initialize dwBits.
dwBits = (pModule->GetDebuggerInfoBits() & ~(DACF_ALLOW_JIT_OPTS | DACF_ENC_ENABLED));
dwBits &= DACF_CONTROL_FLAGS_MASK;
if (fAllowJitOpts)
{
dwBits |= DACF_ALLOW_JIT_OPTS;
}
if (fEnableEnC)
{
if (CanSetEnCBits(pModule))
{
dwBits |= DACF_ENC_ENABLED;
}
else
{
hr = CORDBG_S_NOT_ALL_BITS_SET;
}
}
// Settings from the debugger take precedence over all other settings.
dwBits |= DACF_USER_OVERRIDE;
// set flags. This will write back to the target
pModule->SetDebuggerInfoBits((DebuggerAssemblyControlFlags)dwBits);
LOG((LF_CORDB, LL_INFO100, "D::HIPCE, Changed Jit-Debug-Info: fOpt=%d, fEnableEnC=%d, new bits=0x%08x\n",
(dwBits & DACF_ALLOW_JIT_OPTS) != 0,
(dwBits & DACF_ENC_ENABLED) != 0,
dwBits));
_ASSERTE(SUCCEEDED(hr));
return hr;
} // DacDbiInterfaceImpl::SetCompilerFlags
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// sequence points and var info
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Initialize the native/IL sequence points and native var info for a function.
void DacDbiInterfaceImpl::GetNativeCodeSequencePointsAndVarInfo(VMPTR_MethodDesc vmMethodDesc,
CORDB_ADDRESS startAddr,
BOOL fCodeAvailable,
NativeVarData * pNativeVarData,
SequencePoints * pSequencePoints)
{
DD_ENTER_MAY_THROW;
_ASSERTE(!vmMethodDesc.IsNull());
MethodDesc * pMD = vmMethodDesc.GetDacPtr();
_ASSERTE(fCodeAvailable != 0);
// get information about the locations of arguments and local variables
GetNativeVarData(pMD, startAddr, GetArgCount(pMD), pNativeVarData);
// get the sequence points
GetSequencePoints(pMD, startAddr, pSequencePoints);
} // GetNativeCodeSequencePointsAndVarInfo
//-----------------------------------------------------------------------------
// Get the number of fixed arguments to a function, i.e., the explicit args and the "this" pointer.
// This does not include other implicit arguments or varargs. This is used to compute a variable ID
// (see comment in CordbJITILFrame::ILVariableToNative for more detail)
// Arguments:
// input: pMD pointer to the method desc for the function
// output: none
// Return value:
// the number of fixed arguments to the function
//-----------------------------------------------------------------------------
SIZE_T DacDbiInterfaceImpl::GetArgCount(MethodDesc * pMD)
{
// Create a MetaSig for the given method's sig. (Easier than
// picking the sig apart ourselves.)
PCCOR_SIGNATURE pCallSig;
DWORD cbCallSigSize;
pMD->GetSig(&pCallSig, &cbCallSigSize);
if (pCallSig == NULL)
{
// Sig should only be null if the image is corrupted. (Even for lightweight-codegen)
// We expect the jit+verifier to catch this, so that we never land here.
// But just in case ...
CONSISTENCY_CHECK_MSGF(false, ("Corrupted image, null sig.(%s::%s)",
pMD->m_pszDebugClassName, pMD->m_pszDebugMethodName));
return 0;
}
MetaSig msig(pCallSig, cbCallSigSize, pMD->GetModule(), NULL, MetaSig::sigMember);
// Get the arg count.
UINT32 NumArguments = msig.NumFixedArgs();
// Account for the 'this' argument.
if (!pMD->IsStatic())
{
NumArguments++;
}
/*
SigParser sigParser(pCallSig, cbCallSigSize);
sigParser.SkipMethodHeaderSignature(&m_allArgsCount);
*/
return NumArguments;
} //GetArgCount
// Allocator to pass to the debug-info-stores...
BYTE* InfoStoreNew(void * pData, size_t cBytes)
{
return new BYTE[cBytes];
}
//-----------------------------------------------------------------------------
// Get locations and code offsets for local variables and arguments in a function
// This information is used to find the location of a value at a given IP.
// Arguments:
// input:
// pMethodDesc pointer to the method desc for the function
// startAddr starting address of the function--used to differentiate
// EnC versions
// fixedArgCount number of fixed arguments to the function
// output:
// pVarInfo data structure containing a list of variable and
// argument locations by range of IP offsets
// Note: this function may throw
//-----------------------------------------------------------------------------
void DacDbiInterfaceImpl::GetNativeVarData(MethodDesc * pMethodDesc,
CORDB_ADDRESS startAddr,
SIZE_T fixedArgCount,
NativeVarData * pVarInfo)
{
// make sure we haven't done this already
if (pVarInfo->IsInitialized())
{
return;
}
NewArrayHolder<ICorDebugInfo::NativeVarInfo> nativeVars(NULL);
DebugInfoRequest request;
request.InitFromStartingAddr(pMethodDesc, CORDB_ADDRESS_TO_TADDR(startAddr));
ULONG32 entryCount;
BOOL success = DebugInfoManager::GetBoundariesAndVars(request,
InfoStoreNew, NULL, // allocator
NULL, NULL,
&entryCount, &nativeVars);
if (!success)
ThrowHR(E_FAIL);
// set key fields of pVarInfo
pVarInfo->InitVarDataList(nativeVars, (int)fixedArgCount, (int)entryCount);
} // GetNativeVarData
//-----------------------------------------------------------------------------
// Given a instrumented IL map from the profiler that maps:
// Original offset IL_A -> Instrumentend offset IL_B
// And a native mapping from the JIT that maps:
// Instrumented offset IL_B -> native offset Native_C
// This function merges the two maps and stores the result back into the nativeMap.
// The nativeMap now maps:
// Original offset IL_A -> native offset Native_C
// pEntryCount is the number of valid entries in nativeMap, and it may be adjusted downwards
// as part of the composition.
//-----------------------------------------------------------------------------
void DacDbiInterfaceImpl::ComposeMapping(const InstrumentedILOffsetMapping * pProfilerILMap, ICorDebugInfo::OffsetMapping nativeMap[], ULONG32* pEntryCount)
{
// Translate the IL offset if the profiler has provided us with a mapping.
// The ICD public API should always expose the original IL offsets, but GetBoundaries()
// directly accesses the debug info, which stores the instrumented IL offsets.
ULONG32 entryCount = *pEntryCount;
// The map pointer could be NULL or there could be no entries in the map, in either case no work to do
if (pProfilerILMap && !pProfilerILMap->IsNull())
{
// If we did instrument, then we can't have any sequence points that
// are "in-between" the old-->new map that the profiler gave us.
// Ex, if map is:
// (6 old -> 36 new)
// (8 old -> 50 new)
// And the jit gives us an entry for 44 new, that will map back to 6 old.
// Since the map can only have one entry for 6 old, we remove 44 new.
// First Pass: invalidate all the duplicate entries by setting their IL offset to MAX_ILNUM
ULONG32 cDuplicate = 0;
ULONG32 prevILOffset = (ULONG32)(ICorDebugInfo::MAX_ILNUM);
for (ULONG32 i = 0; i < entryCount; i++)
{
ULONG32 origILOffset = TranslateInstrumentedILOffsetToOriginal(nativeMap[i].ilOffset, pProfilerILMap);
if (origILOffset == prevILOffset)
{
// mark this sequence point as invalid; refer to the comment above
nativeMap[i].ilOffset = (ULONG32)(ICorDebugInfo::MAX_ILNUM);
cDuplicate += 1;
}
else
{
// overwrite the instrumented IL offset with the original IL offset
nativeMap[i].ilOffset = origILOffset;
prevILOffset = origILOffset;
}
}
// Second Pass: move all the valid entries up front
ULONG32 realIndex = 0;
for (ULONG32 curIndex = 0; curIndex < entryCount; curIndex++)
{
if (nativeMap[curIndex].ilOffset != (ULONG32)(ICorDebugInfo::MAX_ILNUM))
{
// This is a valid entry. Move it up front.
nativeMap[realIndex] = nativeMap[curIndex];
realIndex += 1;
}
}
// make sure we have done the bookkeeping correctly
_ASSERTE((realIndex + cDuplicate) == entryCount);
// Final Pass: derecement entryCount
entryCount -= cDuplicate;
*pEntryCount = entryCount;
}
}
//-----------------------------------------------------------------------------
// Get the native/IL sequence points for a function
// Arguments:
// input: