-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathcodeman.cpp
More file actions
7117 lines (5874 loc) · 233 KB
/
codeman.cpp
File metadata and controls
7117 lines (5874 loc) · 233 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// codeman.cpp - a managment class for handling multiple code managers
//
#include "common.h"
#include "jitinterface.h"
#include "corjit.h"
#include "jithost.h"
#include "eetwain.h"
#include "eeconfig.h"
#include "excep.h"
#include "appdomain.hpp"
#include "codeman.h"
#include "nibblemapmacros.h"
#include "generics.h"
#include "dynamicmethod.h"
#include "eventtrace.h"
#include "threadsuspend.h"
#include "daccess.h"
#include "exceptionhandling.h"
#include "rtlfunctions.h"
#include "debuginfostore.h"
#include "strsafe.h"
#include "configuration.h"
#if !defined(DACCESS_COMPILE) && !defined(TARGET_WASM)
#include "../debug/ee/executioncontrol.h"
#endif // !DACCESS_COMPILE && !TARGET_WASM
#include <minipal/cpufeatures.h>
#include <minipal/cpuid.h>
#ifdef HOST_64BIT
#define CHECK_DUPLICATED_STRUCT_LAYOUTS
#include "../debug/daccess/fntableaccess.h"
#endif // HOST_64BIT
#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif
// Default number of jump stubs in a jump stub block
#define DEFAULT_JUMPSTUBS_PER_BLOCK 32
SPTR_IMPL(EECodeManager, ExecutionManager, m_pDefaultCodeMan);
SPTR_IMPL(EEJitManager, ExecutionManager, m_pEEJitManager);
#ifdef FEATURE_READYTORUN
SPTR_IMPL(ReadyToRunJitManager, ExecutionManager, m_pReadyToRunJitManager);
#endif
#ifdef FEATURE_INTERPRETER
SPTR_IMPL(InterpreterJitManager, ExecutionManager, m_pInterpreterJitManager);
SPTR_IMPL(InterpreterCodeManager, ExecutionManager, m_pInterpreterCodeMan);
#endif
SVAL_IMPL(RangeSectionMapData, ExecutionManager, g_codeRangeMap);
VOLATILE_SVAL_IMPL_INIT(LONG, ExecutionManager, m_dwReaderCount, 0);
VOLATILE_SVAL_IMPL_INIT(LONG, ExecutionManager, m_dwWriterLock, 0);
#ifndef DACCESS_COMPILE
CrstStatic ExecutionManager::m_JumpStubCrst;
unsigned ExecutionManager::m_normal_JumpStubLookup;
unsigned ExecutionManager::m_normal_JumpStubUnique;
unsigned ExecutionManager::m_normal_JumpStubBlockAllocCount;
unsigned ExecutionManager::m_normal_JumpStubBlockFullCount;
unsigned ExecutionManager::m_LCG_JumpStubLookup;
unsigned ExecutionManager::m_LCG_JumpStubUnique;
unsigned ExecutionManager::m_LCG_JumpStubBlockAllocCount;
unsigned ExecutionManager::m_LCG_JumpStubBlockFullCount;
#endif // DACCESS_COMPILE
#if defined(TARGET_AMD64) && defined(TARGET_WINDOWS) && !defined(DACCESS_COMPILE)
// Support for new style unwind information (to allow OS to stack crawl JIT compiled code).
typedef NTSTATUS (WINAPI* RtlAddGrowableFunctionTableFnPtr) (
PVOID *DynamicTable, PRUNTIME_FUNCTION FunctionTable, ULONG EntryCount,
ULONG MaximumEntryCount, ULONG_PTR rangeStart, ULONG_PTR rangeEnd);
typedef VOID (WINAPI* RtlGrowFunctionTableFnPtr) (PVOID DynamicTable, ULONG NewEntryCount);
typedef VOID (WINAPI* RtlDeleteGrowableFunctionTableFnPtr) (PVOID DynamicTable);
// OS entry points (only exist on Win8 and above)
static RtlAddGrowableFunctionTableFnPtr pRtlAddGrowableFunctionTable;
static RtlGrowFunctionTableFnPtr pRtlGrowFunctionTable;
static RtlDeleteGrowableFunctionTableFnPtr pRtlDeleteGrowableFunctionTable;
static bool s_publishingActive; // Publishing to ETW is turned on
static Crst* s_pUnwindInfoTablePublishLock; // Protects main table, OS registration, and lazy init
static Crst* s_pUnwindInfoTablePendingLock; // Protects pending buffer only
/****************************************************************************/
// initialize the entry points for new win8 unwind info publishing functions.
// return true if the initialize is successful (the functions exist)
bool InitUnwindFtns()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
HINSTANCE hNtdll = GetModuleHandle(W("ntdll.dll"));
if (hNtdll != NULL)
{
void* growFunctionTable = GetProcAddress(hNtdll, "RtlGrowFunctionTable");
void* deleteGrowableFunctionTable = GetProcAddress(hNtdll, "RtlDeleteGrowableFunctionTable");
void* addGrowableFunctionTable = GetProcAddress(hNtdll, "RtlAddGrowableFunctionTable");
// All or nothing AddGroableFunctionTable is last (marker)
if (growFunctionTable != NULL &&
deleteGrowableFunctionTable != NULL &&
addGrowableFunctionTable != NULL)
{
pRtlGrowFunctionTable = (RtlGrowFunctionTableFnPtr) growFunctionTable;
pRtlDeleteGrowableFunctionTable = (RtlDeleteGrowableFunctionTableFnPtr) deleteGrowableFunctionTable;
pRtlAddGrowableFunctionTable = (RtlAddGrowableFunctionTableFnPtr) addGrowableFunctionTable;
}
// Don't call FreeLibrary(hNtdll) because GetModuleHandle did *NOT* increment the reference count!
}
return (pRtlAddGrowableFunctionTable != NULL);
}
/****************************************************************************/
UnwindInfoTable::UnwindInfoTable(ULONG_PTR rangeStart, ULONG_PTR rangeEnd)
{
STANDARD_VM_CONTRACT;
_ASSERTE(s_pUnwindInfoTablePublishLock->OwnedByCurrentThread());
_ASSERTE((rangeEnd - rangeStart) <= 0x7FFFFFFF);
// We can choose the average method size estimate dynamically based on past experience
// 128 is the estimated size of an average method, so we can accurately predict
// how many RUNTIME_FUNCTION entries are in each chunk we allocate.
ULONG size = (ULONG) ((rangeEnd - rangeStart) / 128) + 1;
// To ensure we test the growing logic in debug builds, make the size much smaller.
INDEBUG(size = size / 4 + 1);
cTableCurCount = 0;
cTableMaxCount = size;
cDeletedEntries = 0;
iRangeStart = rangeStart;
iRangeEnd = rangeEnd;
hHandle = NULL;
pTable = new T_RUNTIME_FUNCTION[cTableMaxCount];
cPendingCount = 0;
}
/****************************************************************************/
UnwindInfoTable::~UnwindInfoTable()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
} CONTRACTL_END;
_ASSERTE(s_publishingActive);
// We do this lock free to because too many places still want no-trigger. It should be OK
// It would be cleaner if we could take the lock (we did not have to be GC_NOTRIGGER)
UnRegister();
delete[] pTable;
}
/*****************************************************************************/
void UnwindInfoTable::Register()
{
_ASSERTE(s_pUnwindInfoTablePublishLock->OwnedByCurrentThread());
NTSTATUS ret = pRtlAddGrowableFunctionTable(&hHandle, pTable, cTableCurCount, cTableMaxCount, iRangeStart, iRangeEnd);
if (ret != STATUS_SUCCESS)
{
_ASSERTE(!"Failed to publish UnwindInfo (ignorable)");
hHandle = NULL;
STRESS_LOG3(LF_JIT, LL_ERROR, "UnwindInfoTable::Register ERROR %x creating table [%p, %p]\n", ret, iRangeStart, iRangeEnd);
}
else
{
STRESS_LOG3(LF_JIT, LL_INFO100, "UnwindInfoTable::Register Handle: %p [%p, %p]\n", hHandle, iRangeStart, iRangeEnd);
}
}
/*****************************************************************************/
void UnwindInfoTable::UnRegister()
{
PVOID handle = hHandle;
hHandle = 0;
if (handle != 0)
{
STRESS_LOG3(LF_JIT, LL_INFO100, "UnwindInfoTable::UnRegister Handle: %p [%p, %p]\n", handle, iRangeStart, iRangeEnd);
pRtlDeleteGrowableFunctionTable(handle);
}
}
/*****************************************************************************/
// Add 'data' entries to the pending buffer for later publication to the OS.
// When the buffer is full, entries are flushed under s_pUnwindInfoTablePublishLock.
//
void UnwindInfoTable::AddToUnwindInfoTable(PT_RUNTIME_FUNCTION data, int count)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
_ASSERTE(s_publishingActive);
for (int i = 0; i < count; )
{
{
CrstHolder pendingLock(s_pUnwindInfoTablePendingLock);
while (i < count && cPendingCount < cPendingMaxCount)
{
_ASSERTE(data[i].BeginAddress <= RUNTIME_FUNCTION__EndAddress(&data[i], iRangeStart));
_ASSERTE(RUNTIME_FUNCTION__EndAddress(&data[i], iRangeStart) <= (iRangeEnd - iRangeStart));
pendingTable[cPendingCount++] = data[i];
STRESS_LOG5(LF_JIT, LL_INFO1000, "AddToUnwindTable Handle: %p [%p, %p] BUFFERED 0x%x, pending 0x%x\n",
hHandle, iRangeStart, iRangeEnd,
data[i].BeginAddress, cPendingCount);
i++;
}
}
// Flush any pending entries if we run out of space, or when we are at the end
// of the batch so the OS can unwind this method immediately.
FlushPendingEntries();
}
}
/*****************************************************************************/
void UnwindInfoTable::FlushPendingEntries()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
}
CONTRACTL_END;
// Free the old table outside the lock
NewArrayHolder<T_RUNTIME_FUNCTION> oldPTable;
CrstHolder publishLock(s_pUnwindInfoTablePublishLock);
if (hHandle == NULL)
{
// If hHandle is null, it means Register() failed. Skip flushing to avoid calling
// RtlGrowFunctionTable with a null handle.
CrstHolder pendingLock(s_pUnwindInfoTablePendingLock);
cPendingCount = 0;
return;
}
// Grab the pending entries under the pending lock, then release it so
// other threads can keep accumulating new entries while we publish.
T_RUNTIME_FUNCTION localPending[cPendingMaxCount];
ULONG localPendingCount;
{
CrstHolder pendingLock(s_pUnwindInfoTablePendingLock);
localPendingCount = cPendingCount;
memcpy(localPending, pendingTable, cPendingCount * sizeof(T_RUNTIME_FUNCTION));
cPendingCount = 0;
INDEBUG( memset(pendingTable, 0xcc, sizeof(pendingTable)); )
}
if (localPendingCount == 0)
return;
// Sort the pending entries by BeginAddress.
// Use a simple insertion sort since cPendingMaxCount is small (32).
static_assert(cPendingMaxCount == 32,
"cPendingMaxCount was updated and might be too large for insertion sort, consider using a better algorithm");
for (ULONG i = 1; i < localPendingCount; i++)
{
T_RUNTIME_FUNCTION key = localPending[i];
ULONG j = i;
while (j > 0 && localPending[j - 1].BeginAddress > key.BeginAddress)
{
localPending[j] = localPending[j - 1];
j--;
}
localPending[j] = key;
}
// Fast path: if all pending entries can be appended in order with room to spare,
// we can just append and call RtlGrowFunctionTable.
if (cTableCurCount + localPendingCount <= cTableMaxCount
&& (cTableCurCount == 0 || pTable[cTableCurCount - 1].BeginAddress < localPending[0].BeginAddress))
{
memcpy(&pTable[cTableCurCount], localPending, localPendingCount * sizeof(T_RUNTIME_FUNCTION));
cTableCurCount += localPendingCount;
pRtlGrowFunctionTable(hHandle, cTableCurCount);
STRESS_LOG5(LF_JIT, LL_INFO1000, "FlushPendingEntries Handle: %p [%p, %p] APPENDED 0x%x entries, now 0x%x\n",
hHandle, iRangeStart, iRangeEnd, localPendingCount, cTableCurCount);
return;
}
// Merge main table and pending entries.
// Calculate the new table size: live entries from main table + all pending entries
ULONG liveCount = cTableCurCount - cDeletedEntries;
ULONG newCount = liveCount + localPendingCount;
ULONG desiredSpace = newCount * 5 / 4 + 1; // Increase by 20%
STRESS_LOG7(LF_JIT, LL_INFO100, "FlushPendingEntries Handle: %p [%p, %p] Merging 0x%x live + 0x%x pending into 0x%x max, from 0x%x\n",
hHandle, iRangeStart, iRangeEnd, liveCount, localPendingCount, desiredSpace, cTableMaxCount);
NewArrayHolder<T_RUNTIME_FUNCTION> newPTable(new T_RUNTIME_FUNCTION[desiredSpace]);
// Merge-sort the main table and pending buffer into newPTable.
ULONG mainIdx = 0;
ULONG pendIdx = 0;
ULONG toIdx = 0;
while (mainIdx < cTableCurCount && pendIdx < localPendingCount)
{
// Skip deleted entries in main table
if (pTable[mainIdx].UnwindData == 0)
{
mainIdx++;
continue;
}
if (localPending[pendIdx].BeginAddress < pTable[mainIdx].BeginAddress)
{
newPTable[toIdx++] = localPending[pendIdx++];
}
else
{
newPTable[toIdx++] = pTable[mainIdx++];
}
}
while (mainIdx < cTableCurCount)
{
if (pTable[mainIdx].UnwindData != 0)
newPTable[toIdx++] = pTable[mainIdx];
mainIdx++;
}
while (pendIdx < localPendingCount)
{
newPTable[toIdx++] = localPending[pendIdx++];
}
_ASSERTE(toIdx == newCount);
_ASSERTE(toIdx <= desiredSpace);
oldPTable = pTable;
// The OS growable function table API (RtlGrowFunctionTable) only supports
// appending sorted entries, it cannot shrink, reorder, or remove entries.
// We have to tear down the old OS registration and create a new one
// combining the old and pending entries while skipping the deleted ones.
// We should keep the gap between UnRegister and Register as short as possible,
// as OS stack walks will have no unwind info for this range during that
// window. The new table is fully built before UnRegister to minimize this gap.
UnRegister();
pTable = newPTable.Extract();
cTableCurCount = toIdx;
cTableMaxCount = desiredSpace;
cDeletedEntries = 0;
Register();
}
/*****************************************************************************/
/* static */ void UnwindInfoTable::RemoveFromUnwindInfoTable(UnwindInfoTable** unwindInfoPtr, TADDR baseAddress, TADDR entryPoint)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(unwindInfoPtr != NULL);
if (!s_publishingActive)
return;
UnwindInfoTable* unwindInfo = VolatileLoad(unwindInfoPtr);
if (unwindInfo == NULL)
return;
DWORD relativeEntryPoint = (DWORD)(entryPoint - baseAddress);
STRESS_LOG3(LF_JIT, LL_INFO100, "RemoveFromUnwindInfoTable Removing %p BaseAddress %p rel %x\n",
entryPoint, baseAddress, relativeEntryPoint);
// Check the main (published) table under the publish lock.
// We don't need to check the pending buffer because the method should have already been published
// before it can be removed.
{
CrstHolder publishLock(s_pUnwindInfoTablePublishLock);
for (ULONG i = 0; i < unwindInfo->cTableCurCount; i++)
{
if (unwindInfo->pTable[i].BeginAddress <= relativeEntryPoint &&
relativeEntryPoint < RUNTIME_FUNCTION__EndAddress(&unwindInfo->pTable[i], unwindInfo->iRangeStart))
{
if (unwindInfo->pTable[i].UnwindData != 0)
unwindInfo->cDeletedEntries++;
unwindInfo->pTable[i].UnwindData = 0; // Mark the entry for deletion
STRESS_LOG1(LF_JIT, LL_INFO100, "RemoveFromUnwindInfoTable Removed entry 0x%x\n", i);
return;
}
}
}
STRESS_LOG2(LF_JIT, LL_WARNING, "RemoveFromUnwindInfoTable COULD NOT FIND %p BaseAddress %p\n",
entryPoint, baseAddress);
}
/****************************************************************************/
// Publish the stack unwind data 'data' which is relative 'baseAddress'
// to the operating system in a way ETW stack tracing can use.
/* static */ void UnwindInfoTable::PublishUnwindInfoForMethod(TADDR baseAddress, PT_RUNTIME_FUNCTION methodUnwindData, int methodUnwindDataCount)
{
STANDARD_VM_CONTRACT;
if (!s_publishingActive)
return;
TADDR entry = baseAddress + methodUnwindData->BeginAddress;
RangeSection * pRS = ExecutionManager::FindCodeRange(entry, ExecutionManager::GetScanFlags());
_ASSERTE(pRS != NULL);
UnwindInfoTable* unwindInfo = VolatileLoad(&pRS->_pUnwindInfoTable);
if (unwindInfo == NULL)
{
CrstHolder publishLock(s_pUnwindInfoTablePublishLock);
if (pRS->_pUnwindInfoTable == NULL)
{
unwindInfo = new UnwindInfoTable(pRS->_range.RangeStart(), pRS->_range.RangeEndOpen());
unwindInfo->Register();
VolatileStore(&pRS->_pUnwindInfoTable, unwindInfo);
}
else
{
unwindInfo = pRS->_pUnwindInfoTable;
}
}
unwindInfo->AddToUnwindInfoTable(methodUnwindData, methodUnwindDataCount);
}
/*****************************************************************************/
/* static */ void UnwindInfoTable::UnpublishUnwindInfoForMethod(TADDR entryPoint)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (!s_publishingActive)
return;
RangeSection * pRS = ExecutionManager::FindCodeRange(entryPoint, ExecutionManager::GetScanFlags());
_ASSERTE(pRS != NULL);
if (pRS != NULL)
{
_ASSERTE(pRS->_pjit->GetCodeType() == (miManaged | miIL) || pRS->_pjit->GetCodeType() == (miManaged | miIL | miOPTIL));
if (pRS->_pjit->GetCodeType() == (miManaged | miIL)) // Do this only for Jitted code, not for interpreted code
{
// This cast is justified because only EEJitManager's have the code type above.
EEJitManager* pJitMgr = (EEJitManager*)(pRS->_pjit);
CodeHeader * pHeader = pJitMgr->GetCodeHeaderFromStartAddress(entryPoint);
for(ULONG i = 0; i < pHeader->GetNumberOfUnwindInfos(); i++)
RemoveFromUnwindInfoTable(&pRS->_pUnwindInfoTable, pRS->_range.RangeStart(), pRS->_range.RangeStart() + pHeader->GetUnwindInfo(i)->BeginAddress);
}
}
}
/*****************************************************************************/
// We only do this on Windows x64 (other platforms use frame-based stack crawling),
// We want good stack traces so we need to publish unwind information so ETW can
// walk the stack.
/* static */ void UnwindInfoTable::Initialize()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(!s_publishingActive);
// If we don't have the APIs we need, give up
if (!InitUnwindFtns())
return;
// Create the locks
s_pUnwindInfoTablePublishLock = new Crst(CrstUnwindInfoTablePublishLock);
s_pUnwindInfoTablePendingLock = new Crst(CrstUnwindInfoTablePendingLock);
s_publishingActive = true;
}
#else
/* static */ void UnwindInfoTable::PublishUnwindInfoForMethod(TADDR baseAddress, T_RUNTIME_FUNCTION* methodUnwindData, int methodUnwindDataCount)
{
LIMITED_METHOD_CONTRACT;
}
/* static */ void UnwindInfoTable::UnpublishUnwindInfoForMethod(TADDR entryPoint)
{
LIMITED_METHOD_CONTRACT;
}
/* static */ void UnwindInfoTable::Initialize()
{
LIMITED_METHOD_CONTRACT;
}
#endif // defined(TARGET_AMD64) && defined(TARGET_WINDOWS) && !defined(DACCESS_COMPILE)
#if !defined(DACCESS_COMPILE)
CodeHeapIterator::CodeHeapIterator(EECodeGenManager* manager, HeapList* heapList, LoaderAllocator* pLoaderAllocatorFilter)
: m_manager(manager)
, m_Iterator{}
, m_Heaps{}
, m_HeapsIndexNext{ 0 }
, m_pLoaderAllocatorFilter{ pLoaderAllocatorFilter }
, m_pCurrent{ NULL }
, m_codeType(manager->GetCodeType())
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
PRECONDITION(manager != NULL);
}
CONTRACTL_END;
// Iterator through the heap list collecting the current state of the heaps.
HeapList* current = heapList;
while (current)
{
HeapListState* state = m_Heaps.AppendThrowing();
state->Heap = current;
state->MapBase = (void*)current->mapBase;
state->HdrMap = current->pHdrMap;
state->MaxCodeHeapSize = current->maxCodeHeapSize;
current = current->GetNext();
}
// Move to the first method section.
(void)NextMethodSectionIterator();
}
CodeHeapIterator::EECodeGenManagerReleaseIteratorHolder::EECodeGenManagerReleaseIteratorHolder(EECodeGenManager* manager) : m_manager(manager)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
manager->AddRefIterator();
}
CodeHeapIterator::EECodeGenManagerReleaseIteratorHolder::~EECodeGenManagerReleaseIteratorHolder()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_manager)
{
m_manager->ReleaseIterator();
m_manager = NULL;
}
}
CodeHeapIterator::EECodeGenManagerReleaseIteratorHolder& CodeHeapIterator::EECodeGenManagerReleaseIteratorHolder::operator=(EECodeGenManagerReleaseIteratorHolder&& other)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (this != &other)
{
if (m_manager)
{
m_manager->ReleaseIterator();
}
m_manager = other.m_manager;
other.m_manager = NULL;
}
return *this;
}
bool CodeHeapIterator::Next()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
while (true)
{
if (!m_Iterator.Next())
{
if (!NextMethodSectionIterator())
return false;
}
else
{
BYTE* code = m_Iterator.GetMethodCode();
#ifdef FEATURE_INTERPRETER
if (m_codeType == (miManaged | miIL | miOPTIL))
{
// Interpreter case
InterpreterCodeHeader* pHdr = (InterpreterCodeHeader*)(code - sizeof(InterpreterCodeHeader));
m_pCurrent = pHdr->GetMethodDesc();
}
else
#endif
{
CodeHeader* pHdr = (CodeHeader*)(code - sizeof(CodeHeader));
m_pCurrent = !pHdr->IsStubCodeBlock() ? pHdr->GetMethodDesc() : NULL;
}
// LoaderAllocator filter
if (m_pLoaderAllocatorFilter && m_pCurrent)
{
LoaderAllocator *pCurrentLoaderAllocator = m_pCurrent->GetLoaderAllocator();
if (pCurrentLoaderAllocator != m_pLoaderAllocatorFilter)
continue;
}
return true;
}
}
}
bool CodeHeapIterator::NextMethodSectionIterator()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_HeapsIndexNext >= m_Heaps.Count())
{
m_Iterator = {};
return false;
}
HeapListState& curr = m_Heaps.Table()[m_HeapsIndexNext++];
m_Iterator = MethodSectionIterator{
curr.MapBase,
(COUNT_T)curr.MaxCodeHeapSize,
curr.HdrMap,
(COUNT_T)HEAP2MAPSIZE(ROUND_UP_TO_PAGE(curr.MaxCodeHeapSize))};
return true;
}
#endif // !DACCESS_COMPILE
#ifndef DACCESS_COMPILE
//---------------------------------------------------------------------------------------
//
// ReaderLockHolder::ReaderLockHolder takes the reader lock, checks for the writer lock
// and either aborts if the writer lock is held, or yields until the writer lock is released,
// keeping the reader lock. This is normally called in the constructor for the
// ReaderLockHolder.
//
// The writer cannot be taken if there are any readers. The WriterLockHolder functions take the
// writer lock and check for any readers. If there are any, the WriterLockHolder functions
// release the writer and yield to wait for the readers to be done.
ExecutionManager::ReaderLockHolder::ReaderLockHolder()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
CAN_TAKE_LOCK;
} CONTRACTL_END;
IncCantAllocCount();
InterlockedIncrement(&m_dwReaderCount);
EE_LOCK_TAKEN(GetPtrForLockContract());
if (VolatileLoad(&m_dwWriterLock) != 0)
{
YIELD_WHILE ((VolatileLoad(&m_dwWriterLock) != 0));
}
}
//---------------------------------------------------------------------------------------
//
// See code:ExecutionManager::ReaderLockHolder::ReaderLockHolder. This just decrements the reader count.
ExecutionManager::ReaderLockHolder::~ReaderLockHolder()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
InterlockedDecrement(&m_dwReaderCount);
DecCantAllocCount();
EE_LOCK_RELEASED(GetPtrForLockContract());
}
//---------------------------------------------------------------------------------------
//
// Returns whether the reader lock is acquired
BOOL ExecutionManager::ReaderLockHolder::Acquired()
{
LIMITED_METHOD_CONTRACT;
return VolatileLoad(&m_dwWriterLock) == 0;
}
ExecutionManager::WriterLockHolder::WriterLockHolder()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
CAN_TAKE_LOCK;
} CONTRACTL_END;
_ASSERTE(m_dwWriterLock == 0);
// Signal to a debugger that this thread cannot stop now
IncCantStopCount();
IncCantAllocCount();
DWORD dwSwitchCount = 0;
while (TRUE)
{
// While this thread holds the writer lock, we must not try to suspend it
// or allow a profiler to walk its stack
Thread::IncForbidSuspendThread();
InterlockedIncrement(&m_dwWriterLock);
if (m_dwReaderCount == 0)
break;
InterlockedDecrement(&m_dwWriterLock);
// Before we loop and retry, it's safe to suspend or hijack and inspect
// this thread
Thread::DecForbidSuspendThread();
__SwitchToThread(0, ++dwSwitchCount);
}
EE_LOCK_TAKEN(GetPtrForLockContract());
}
ExecutionManager::WriterLockHolder::~WriterLockHolder()
{
LIMITED_METHOD_CONTRACT;
InterlockedDecrement(&m_dwWriterLock);
// Writer lock released, so it's safe again for this thread to be
// suspended or have its stack walked by a profiler
Thread::DecForbidSuspendThread();
DecCantAllocCount();
// Signal to a debugger that it's again safe to stop this thread
DecCantStopCount();
EE_LOCK_RELEASED(GetPtrForLockContract());
}
#else
// For DAC builds, we only care whether the writer lock is held.
// If it is, we will assume the locked data is in an inconsistent
// state and throw. We never actually take the lock.
// Note: Throws
ExecutionManager::ReaderLockHolder::ReaderLockHolder()
{
SUPPORTS_DAC;
if (m_dwWriterLock != 0)
{
ThrowHR(CORDBG_E_PROCESS_NOT_SYNCHRONIZED);
}
}
ExecutionManager::ReaderLockHolder::~ReaderLockHolder()
{
}
#endif // DACCESS_COMPILE
/*-----------------------------------------------------------------------------
This is a listing of which methods uses which synchronization mechanism
in the ExecutionManager
//-----------------------------------------------------------------------------
==============================================================================
ExecutionManger::ReaderLockHolder and ExecutionManger::WriterLockHolder
Protects the callers of ExecutionManager::GetRangeSection from heap deletions
while walking RangeSections. You need to take a reader lock before reading the
values: m_CodeRangeList and hold it while walking the lists
Uses ReaderLockHolder (allows multiple reeaders with no writers)
-----------------------------------------
ExecutionManager::FindCodeRange
ExecutionManager::FindReadyToRunModule
ExecutionManager::EnumMemoryRegions
AND
ExecutionManager::IsManagedCode
ExecutionManager::IsManagedCodeWithLock
The IsManagedCode checks are notable as they protect not just access to the RangeSection walking,
but the actual RangeSection while determining if a given ip IsManagedCode.
Uses WriterLockHolder (allows single writer and no readers)
-----------------------------------------
ExecutionManager::DeleteRange
*/
//-----------------------------------------------------------------------------
#if defined(TARGET_ARM) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
#define EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
#endif
#if defined(EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS)
// The function fragments can be used in Hot/Cold splitting, expressing Large Functions or in 'ShrinkWrapping', which is
// delaying saving and restoring some callee-saved registers later inside the body of the method.
// (It's assumed that JIT will not emit any ShrinkWrapping-style methods)
// For these cases multiple RUNTIME_FUNCTION entries (a.k.a function fragments) are used to define
// all the regions of the function or funclet. And one of these function fragments cover the beginning of the function/funclet,
// including the prolog section and is referred as the 'Host Record'.
// This function returns TRUE if the inspected RUNTIME_FUNCTION entry is NOT a host record
BOOL IsFunctionFragment(TADDR baseAddress, PTR_RUNTIME_FUNCTION pFunctionEntry)
{
LIMITED_METHOD_DAC_CONTRACT;
_ASSERTE((pFunctionEntry->UnwindData & 3) == 0); // The unwind data must be an RVA; we don't support packed unwind format
DWORD unwindHeader = *(PTR_DWORD)(baseAddress + pFunctionEntry->UnwindData);
_ASSERTE((0 == ((unwindHeader >> 18) & 3)) || !"unknown unwind data format, version != 0");
#if defined(TARGET_ARM)
// On ARM, It's assumed that the prolog is always at the beginning of the function and cannot be split.
// Given that, there are 4 possible ways to fragment a function:
// 1. Prolog only:
// 2. Prolog and some epilogs:
// 3. Epilogs only:
// 4. No Prolog or epilog
//
// Function fragments describing 1 & 2 are host records, 3 & 4 are not.
// for 3 & 4, the .xdata record's F bit is set to 1, marking clearly what is NOT a host record
_ASSERTE((pFunctionEntry->BeginAddress & THUMB_CODE) == THUMB_CODE); // Sanity check: it's a thumb address
DWORD Fbit = (unwindHeader >> 22) & 0x1; // F "fragment" bit
return (Fbit == 1);
#elif defined(TARGET_ARM64)
// ARM64 is a little bit more flexible, in the sense that it supports partial prologs. However only one of the
// prolog regions are allowed to alter SP and that's the Host Record. Partial prologs are used in ShrinkWrapping
// scenarios which is not supported, hence we don't need to worry about them. discarding partial prologs
// simplifies identifying a host record a lot.
//
// 1. Prolog only: The host record. Epilog Count and E bit are all 0.
// 2. Prolog and some epilogs: The host record with accompanying epilog-only records
// 3. Epilogs only: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
// 4. No prologs or epilogs: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
//
int EpilogCount = (int)(unwindHeader >> 22) & 0x1F;
int CodeWords = unwindHeader >> 27;
PTR_DWORD pUnwindCodes = (PTR_DWORD)(baseAddress + pFunctionEntry->UnwindData);
// Skip header.
pUnwindCodes++;
// Skip extended header.
if ((CodeWords == 0) && (EpilogCount == 0))
{
EpilogCount = (*pUnwindCodes) & 0xFFFF;
pUnwindCodes++;
}
// Skip epilog scopes.
BOOL Ebit = (unwindHeader >> 21) & 0x1;
if (!Ebit && (EpilogCount != 0))
{
// EpilogCount is the number of exception scopes defined right after the unwindHeader
pUnwindCodes += EpilogCount;
}
return ((*pUnwindCodes & 0xFF) == 0xE5);
#elif defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
// LOONGARCH64 is a little bit more flexible, in the sense that it supports partial prologs. However only one of the
// prolog regions are allowed to alter SP and that's the Host Record. Partial prologs are used in ShrinkWrapping
// scenarios which is not supported, hence we don't need to worry about them. discarding partial prologs
// simplifies identifying a host record a lot.
//
// 1. Prolog only: The host record. Epilog Count and E bit are all 0.
// 2. Prolog and some epilogs: The host record with accompanying epilog-only records
// 3. Epilogs only: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
// 4. No prologs or epilogs: First unwind code is Phantom prolog (Starting with an end_c, indicating an empty prolog)
//
int EpilogCount = (int)(unwindHeader >> 22) & 0x1F;
int CodeWords = unwindHeader >> 27;
PTR_DWORD pUnwindCodes = (PTR_DWORD)(baseAddress + pFunctionEntry->UnwindData);
// Skip header.
pUnwindCodes++;
// Skip extended header.
if ((CodeWords == 0) && (EpilogCount == 0))
{
EpilogCount = (*pUnwindCodes) & 0xFFFF;
pUnwindCodes++;
}
// Skip epilog scopes.
BOOL Ebit = (unwindHeader >> 21) & 0x1;
if (!Ebit && (EpilogCount != 0))
{
// EpilogCount is the number of exception scopes defined right after the unwindHeader
pUnwindCodes += EpilogCount;
}
return ((*pUnwindCodes & 0xFF) == 0xE5);
#else
PORTABILITY_ASSERT("IsFunctionFragnent - NYI on this platform");
#endif
}
#endif // EXCEPTION_DATA_SUPPORTS_FUNCTION_FRAGMENTS
#ifndef DACCESS_COMPILE
//**********************************************************************************
// IJitManager
//**********************************************************************************
IJitManager::IJitManager()
{
LIMITED_METHOD_CONTRACT;
m_runtimeSupport = ExecutionManager::GetDefaultCodeManager();
}
#endif // #ifndef DACCESS_COMPILE
// When we unload an appdomain, we need to make sure that any threads that are crawling through
// our heap or rangelist are out. For cooperative-mode threads, we know that they will have
// been stopped when we suspend the EE so they won't be touching an element that is about to be deleted.
// However for pre-emptive mode threads, they could be stalled right on top of the element we want
// to delete, so we need to apply the reader lock to them and wait for them to drain.
ExecutionManager::ScanFlag ExecutionManager::GetScanFlags(Thread *pThread)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
} CONTRACTL_END;
#if !defined(DACCESS_COMPILE)
if (!pThread)
{