-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
dynamicmethod.cpp
1571 lines (1279 loc) · 51.2 KB
/
dynamicmethod.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.
//
//
#include "common.h"
#include "dynamicmethod.h"
#include "object.h"
#include "method.hpp"
#include "comdelegate.h"
#include "field.h"
#include "contractimpl.h"
#include "nibblemapmacros.h"
#include "stringliteralmap.h"
#include "virtualcallstub.h"
#ifndef DACCESS_COMPILE
// get the method table for dynamic methods
DynamicMethodTable* DomainAssembly::GetDynamicMethodTable()
{
CONTRACT (DynamicMethodTable*)
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
POSTCONDITION(CheckPointer(m_pDynamicMethodTable));
}
CONTRACT_END;
if (!m_pDynamicMethodTable)
DynamicMethodTable::CreateDynamicMethodTable(&m_pDynamicMethodTable, GetModule(), GetAppDomain());
RETURN m_pDynamicMethodTable;
}
void ReleaseDynamicMethodTable(DynamicMethodTable *pDynMT)
{
WRAPPER_NO_CONTRACT;
if (pDynMT)
{
pDynMT->Destroy();
}
}
void DynamicMethodTable::CreateDynamicMethodTable(DynamicMethodTable **ppLocation, Module *pModule, AppDomain *pDomain)
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(ppLocation));
PRECONDITION(CheckPointer(pModule));
POSTCONDITION(CheckPointer(*ppLocation));
}
CONTRACT_END;
AllocMemTracker amt;
LoaderHeap* pHeap = pDomain->GetHighFrequencyHeap();
_ASSERTE(pHeap);
if (*ppLocation) RETURN;
DynamicMethodTable* pDynMT = (DynamicMethodTable*)
amt.Track(pHeap->AllocMem(S_SIZE_T(sizeof(DynamicMethodTable))));
// Note: Memory allocated on loader heap is zero filled
// memset((void*)pDynMT, 0, sizeof(DynamicMethodTable));
if (*ppLocation) RETURN;
LOG((LF_BCL, LL_INFO100, "Level2 - Creating DynamicMethodTable {0x%p}...\n", pDynMT));
Holder<DynamicMethodTable*, DoNothing, ReleaseDynamicMethodTable> dynMTHolder(pDynMT);
pDynMT->m_Crst.Init(CrstDynamicMT);
pDynMT->m_Module = pModule;
pDynMT->m_pDomain = pDomain;
pDynMT->MakeMethodTable(&amt);
if (*ppLocation) RETURN;
if (InterlockedCompareExchangeT(ppLocation, pDynMT, NULL) != NULL)
{
LOG((LF_BCL, LL_INFO100, "Level2 - Another thread got here first - deleting DynamicMethodTable {0x%p}...\n", pDynMT));
RETURN;
}
dynMTHolder.SuppressRelease();
amt.SuppressRelease();
LOG((LF_BCL, LL_INFO10, "Level1 - DynamicMethodTable created {0x%p}...\n", pDynMT));
RETURN;
}
void DynamicMethodTable::MakeMethodTable(AllocMemTracker *pamTracker)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
m_pMethodTable = CreateMinimalMethodTable(m_Module, m_pDomain->GetHighFrequencyHeap(), pamTracker);
}
void DynamicMethodTable::Destroy()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
#if _DEBUG
// This method should be called only for collectible types or for non-collectible ones
// at the construction time when there are no DynamicMethodDesc instances added to the
// DynamicMethodTable yet (from the DynamicMethodTable::CreateDynamicMethodTable in case
// there were two threads racing to construct the instance for the thread that lost
// the race)
if (m_pMethodTable != NULL && !m_pMethodTable->GetLoaderAllocator()->IsCollectible())
{
MethodTable::IntroducedMethodIterator it(m_pMethodTable);
_ASSERTE(!it.IsValid());
}
#endif
m_Crst.Destroy();
LOG((LF_BCL, LL_INFO10, "Level1 - DynamicMethodTable destroyed {0x%p}\n", this));
}
void DynamicMethodTable::AddMethodsToList()
{
CONTRACT_VOID
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACT_END;
AllocMemTracker amt;
LoaderHeap* pHeap = m_pMethodTable->GetLoaderAllocator()->GetHighFrequencyHeap();
_ASSERTE(pHeap);
//
// allocate as many chunks as needed to hold the methods
//
MethodDescChunk* pChunk = MethodDescChunk::CreateChunk(pHeap, 0 /* one chunk of maximum size */,
mcDynamic, TRUE /* fNonVtableSlot */, TRUE /* fNativeCodeSlot */, FALSE /* fComPlusCallInfo */, m_pMethodTable, &amt);
if (m_DynamicMethodList) RETURN;
int methodCount = pChunk->GetCount();
BYTE* pResolvers = (BYTE*)amt.Track(pHeap->AllocMem(S_SIZE_T(sizeof(LCGMethodResolver)) * S_SIZE_T(methodCount)));
if (m_DynamicMethodList) RETURN;
DynamicMethodDesc *pNewMD = (DynamicMethodDesc *)pChunk->GetFirstMethodDesc();
DynamicMethodDesc *pPrevMD = NULL;
// now go through all the methods in the chunk and link them
for(int i = 0; i < methodCount; i++)
{
_ASSERTE(pNewMD->GetClassification() == mcDynamic);
pNewMD->SetMemberDef(0);
pNewMD->SetSlot(MethodTable::NO_SLOT); // we can't ever use the slot for dynamic methods
pNewMD->SetStatic();
pNewMD->InitializeFlags(DynamicMethodDesc::FlagPublic
| DynamicMethodDesc::FlagStatic
| DynamicMethodDesc::FlagIsLCGMethod);
LCGMethodResolver* pResolver = new (pResolvers) LCGMethodResolver();
pResolver->m_pDynamicMethod = pNewMD;
pResolver->m_DynamicMethodTable = this;
pNewMD->m_pResolver = pResolver;
pNewMD->SetTemporaryEntryPoint(m_pDomain->GetLoaderAllocator(), &amt);
#ifdef _DEBUG
pNewMD->m_pDebugMethodTable = m_pMethodTable;
#endif
if (pPrevMD)
{
pPrevMD->GetLCGMethodResolver()->m_next = pNewMD;
}
pPrevMD = pNewMD;
pNewMD = (DynamicMethodDesc *)(dac_cast<TADDR>(pNewMD) + pNewMD->SizeOf());
pResolvers += sizeof(LCGMethodResolver);
}
if (m_DynamicMethodList) RETURN;
{
// publish method list and method table
LockHolder lh(this);
if (m_DynamicMethodList) RETURN;
// publish the new method descs on the method table
m_pMethodTable->GetClass()->AddChunk(pChunk);
m_DynamicMethodList = (DynamicMethodDesc*)pChunk->GetFirstMethodDesc();
}
amt.SuppressRelease();
}
DynamicMethodDesc* DynamicMethodTable::GetDynamicMethod(BYTE *psig, DWORD sigSize, PTR_CUTF8 name)
{
CONTRACT (DynamicMethodDesc*)
{
INSTANCE_CHECK;
THROWS;
GC_TRIGGERS;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(psig));
PRECONDITION(sigSize > 0);
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
LOG((LF_BCL, LL_INFO10000, "Level4 - Getting DynamicMethod\n"));
DynamicMethodDesc *pNewMD = NULL;
for (;;)
{
{
LockHolder lh(this);
pNewMD = m_DynamicMethodList;
if (pNewMD)
{
m_DynamicMethodList = pNewMD->GetLCGMethodResolver()->m_next;
#ifdef _DEBUG
m_Used++;
#endif
break;
}
}
LOG((LF_BCL, LL_INFO1000, "Level4 - DynamicMethod unavailable\n"));
// need to create more methoddescs
AddMethodsToList();
}
_ASSERTE(pNewMD != NULL);
// Reset the method desc into pristine state
// Note: Reset has THROWS contract since it may allocate jump stub. It will never throw here
// since it will always reuse the existing jump stub.
pNewMD->Reset();
LOG((LF_BCL, LL_INFO1000, "Level3 - DynamicMethod obtained {0x%p} (used %d)\n", pNewMD, m_Used));
// the store sig part of the method desc
pNewMD->SetStoredMethodSig((PCCOR_SIGNATURE)psig, sigSize);
// the dynamic part of the method desc
pNewMD->m_pszMethodName = name;
pNewMD->InitializeFlags(DynamicMethodDesc::FlagPublic
| DynamicMethodDesc::FlagStatic
| DynamicMethodDesc::FlagIsLCGMethod);
#ifdef _DEBUG
pNewMD->m_pszDebugMethodName = name;
pNewMD->m_pszDebugClassName = (LPUTF8)"dynamicclass";
pNewMD->m_pszDebugMethodSignature = "DynamicMethod Signature not available";
#endif // _DEBUG
#ifdef HAVE_GCCOVER
pNewMD->m_GcCover = NULL;
#endif
pNewMD->SetNotInline(TRUE);
pNewMD->GetLCGMethodResolver()->Reset();
RETURN pNewMD;
}
void DynamicMethodTable::LinkMethod(DynamicMethodDesc *pMethod)
{
CONTRACT_VOID
{
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
PRECONDITION(CheckPointer(pMethod));
}
CONTRACT_END;
LOG((LF_BCL, LL_INFO10000, "Level4 - Returning DynamicMethod to free list {0x%p} (used %d)\n", pMethod, m_Used));
{
LockHolder lh(this);
pMethod->GetLCGMethodResolver()->m_next = m_DynamicMethodList;
m_DynamicMethodList = pMethod;
#ifdef _DEBUG
m_Used--;
#endif
}
RETURN;
}
//
// CodeHeap implementation
//
HeapList* HostCodeHeap::CreateCodeHeap(CodeHeapRequestInfo *pInfo, EEJitManager *pJitManager)
{
CONTRACT (HeapList*)
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
POSTCONDITION((RETVAL != NULL) || !pInfo->getThrowOnOutOfMemoryWithinRange());
}
CONTRACT_END;
NewHolder<HostCodeHeap> pCodeHeap(new HostCodeHeap(pJitManager));
HeapList *pHp = pCodeHeap->InitializeHeapList(pInfo);
if (pHp == NULL)
{
_ASSERTE(!pInfo->getThrowOnOutOfMemoryWithinRange());
RETURN NULL;
}
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap creation {0x%p} - base addr 0x%p, size available 0x%p, nibble map ptr 0x%p\n",
(HostCodeHeap*)pCodeHeap, pCodeHeap->m_pBaseAddr, pCodeHeap->m_TotalBytesAvailable, pCodeHeap->m_pHeapList->pHdrMap));
pCodeHeap.SuppressRelease();
LOG((LF_BCL, LL_INFO10, "Level1 - CodeHeap created {0x%p}\n", (HostCodeHeap*)pCodeHeap));
RETURN pHp;
}
HostCodeHeap::HostCodeHeap(EEJitManager *pJitManager)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
INJECT_FAULT(COMPlusThrowOM());
}
CONTRACTL_END;
m_pBaseAddr = NULL;
m_pLastAvailableCommittedAddr = NULL;
m_TotalBytesAvailable = 0;
m_ApproximateLargestBlock = 0;
m_AllocationCount = 0;
m_pHeapList = NULL;
m_pJitManager = (PTR_EEJitManager)pJitManager;
m_pFreeList = NULL;
m_pAllocator = NULL;
m_pNextHeapToRelease = NULL;
}
HostCodeHeap::~HostCodeHeap()
{
LIMITED_METHOD_CONTRACT;
if (m_pHeapList != NULL && m_pHeapList->pHdrMap != NULL)
delete[] m_pHeapList->pHdrMap;
if (m_pBaseAddr)
ExecutableAllocator::Instance()->Release(m_pBaseAddr);
LOG((LF_BCL, LL_INFO10, "Level1 - CodeHeap destroyed {0x%p}\n", this));
}
HeapList* HostCodeHeap::InitializeHeapList(CodeHeapRequestInfo *pInfo)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
size_t ReserveBlockSize = pInfo->getRequestSize();
// Add TrackAllocation, HeapList and very conservative padding to make sure we have enough for the allocation
ReserveBlockSize += sizeof(TrackAllocation) + HOST_CODEHEAP_SIZE_ALIGN + 0x100;
#if defined(TARGET_AMD64) || defined(TARGET_ARM64)
ReserveBlockSize += JUMP_ALLOCATE_SIZE;
#endif
// reserve ReserveBlockSize rounded-up to VIRTUAL_ALLOC_RESERVE_GRANULARITY of memory
ReserveBlockSize = ALIGN_UP(ReserveBlockSize, VIRTUAL_ALLOC_RESERVE_GRANULARITY);
if (pInfo->m_loAddr != NULL || pInfo->m_hiAddr != NULL)
{
m_pBaseAddr = (BYTE*)ExecutableAllocator::Instance()->ReserveWithinRange(ReserveBlockSize, pInfo->m_loAddr, pInfo->m_hiAddr);
if (!m_pBaseAddr)
{
if (pInfo->getThrowOnOutOfMemoryWithinRange())
ThrowOutOfMemoryWithinRange();
return NULL;
}
}
else
{
// top up the ReserveBlockSize to suggested minimum
ReserveBlockSize = max(ReserveBlockSize, pInfo->getReserveSize());
m_pBaseAddr = (BYTE*)ExecutableAllocator::Instance()->Reserve(ReserveBlockSize);
if (!m_pBaseAddr)
ThrowOutOfMemory();
}
m_pLastAvailableCommittedAddr = m_pBaseAddr;
m_TotalBytesAvailable = ReserveBlockSize;
m_ApproximateLargestBlock = ReserveBlockSize;
m_pAllocator = pInfo->m_pAllocator;
HeapList* pHp = new HeapList;
TrackAllocation *pTracker = NULL;
#if defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64)
pTracker = AllocMemory_NoThrow(0, JUMP_ALLOCATE_SIZE, sizeof(void*), 0);
if (pTracker == NULL)
{
// This should only ever happen with fault injection
_ASSERTE(g_pConfig->ShouldInjectFault(INJECTFAULT_DYNAMICCODEHEAP));
delete pHp;
ThrowOutOfMemory();
}
pHp->CLRPersonalityRoutine = (BYTE *)(pTracker + 1);
#endif
pHp->hpNext = NULL;
pHp->pHeap = (PTR_CodeHeap)this;
// wire it back
m_pHeapList = (PTR_HeapList)pHp;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap creation {0x%p} - size available 0x%p, private data ptr [0x%p, 0x%p]\n",
(HostCodeHeap*)this, m_TotalBytesAvailable, pTracker, pTracker->size));
// It is important to exclude the CLRPersonalityRoutine from the tracked range
pHp->startAddress = dac_cast<TADDR>(m_pBaseAddr) + (pTracker ? pTracker->size : 0);
pHp->mapBase = ROUND_DOWN_TO_PAGE(pHp->startAddress); // round down to next lower page align
pHp->pHdrMap = NULL;
pHp->endAddress = pHp->startAddress;
pHp->maxCodeHeapSize = m_TotalBytesAvailable - (pTracker ? pTracker->size : 0);
pHp->reserveForJumpStubs = 0;
#ifdef HOST_64BIT
ExecutableWriterHolder<BYTE> personalityRoutineWriterHolder(pHp->CLRPersonalityRoutine, 12);
emitJump(pHp->CLRPersonalityRoutine, personalityRoutineWriterHolder.GetRW(), (void *)ProcessCLRException);
#endif
size_t nibbleMapSize = HEAP2MAPSIZE(ROUND_UP_TO_PAGE(pHp->maxCodeHeapSize));
pHp->pHdrMap = new DWORD[nibbleMapSize / sizeof(DWORD)];
ZeroMemory(pHp->pHdrMap, nibbleMapSize);
return pHp;
}
HostCodeHeap::TrackAllocation* HostCodeHeap::AllocFromFreeList(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
if (m_pFreeList)
{
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Alloc size corrected 0x%X for free list\n", this, size));
// walk the list looking for a block with enough capacity
TrackAllocation *pCurrent = m_pFreeList;
TrackAllocation *pPrevious = NULL;
while (pCurrent)
{
BYTE* pPointer = ALIGN_UP((BYTE*)(pCurrent + 1) + header, alignment);
size_t realSize = ALIGN_UP(pPointer + size, sizeof(void*)) - (BYTE*)pCurrent;
if (pCurrent->size >= realSize + reserveForJumpStubs)
{
// found a block
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Block found, size 0x%X\n", this, pCurrent->size));
ExecutableWriterHolderNoLog<TrackAllocation> previousWriterHolder;
if (pPrevious)
{
previousWriterHolder.AssignExecutableWriterHolder(pPrevious, sizeof(TrackAllocation));
}
ExecutableWriterHolder<TrackAllocation> currentWriterHolder(pCurrent, sizeof(TrackAllocation));
// The space left is not big enough for a new block, let's just
// update the TrackAllocation record for the current block
if (pCurrent->size - realSize < max(HOST_CODEHEAP_SIZE_ALIGN, sizeof(TrackAllocation)))
{
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Item removed %p, size 0x%X\n", this, pCurrent, pCurrent->size));
// remove current
if (pPrevious)
{
previousWriterHolder.GetRW()->pNext = pCurrent->pNext;
}
else
{
m_pFreeList = pCurrent->pNext;
}
}
else
{
// create a new TrackAllocation after the memory we just allocated and insert it into the free list
TrackAllocation *pNewCurrent = (TrackAllocation*)((BYTE*)pCurrent + realSize);
ExecutableWriterHolder<TrackAllocation> newCurrentWriterHolder(pNewCurrent, sizeof(TrackAllocation));
newCurrentWriterHolder.GetRW()->pNext = pCurrent->pNext;
newCurrentWriterHolder.GetRW()->size = pCurrent->size - realSize;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Item changed %p, new size 0x%X\n", this, pNewCurrent, pNewCurrent->size));
if (pPrevious)
{
previousWriterHolder.GetRW()->pNext = pNewCurrent;
}
else
{
m_pFreeList = pNewCurrent;
}
// We only need to update the size of the current block if we are creating a new block
currentWriterHolder.GetRW()->size = realSize;
}
currentWriterHolder.GetRW()->pHeap = this;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Allocation returned %p, size 0x%X - data -> %p\n", this, pCurrent, pCurrent->size, pPointer));
return pCurrent;
}
pPrevious = pCurrent;
pCurrent = pCurrent->pNext;
}
}
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - No block in free list for size 0x%X\n", this, size));
return NULL;
}
void HostCodeHeap::AddToFreeList(TrackAllocation *pBlockToInsert, TrackAllocation *pBlockToInsertRW)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Add to FreeList [%p, 0x%X]\n", this, pBlockToInsert, pBlockToInsert->size));
// append to the list in the proper position and coalesce if needed
if (m_pFreeList)
{
TrackAllocation *pCurrent = m_pFreeList;
TrackAllocation *pPrevious = NULL;
while (pCurrent)
{
if (pCurrent > pBlockToInsert)
{
// found the point of insertion
pBlockToInsertRW->pNext = pCurrent;
ExecutableWriterHolderNoLog<TrackAllocation> previousWriterHolder;
if (pPrevious)
{
previousWriterHolder.AssignExecutableWriterHolder(pPrevious, sizeof(TrackAllocation));
previousWriterHolder.GetRW()->pNext = pBlockToInsert;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Insert block [%p, 0x%X] -> [%p, 0x%X] -> [%p, 0x%X]\n", this,
pPrevious, pPrevious->size,
pBlockToInsert, pBlockToInsert->size,
pCurrent, pCurrent->size));
}
else
{
m_pFreeList = pBlockToInsert;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Insert block [%p, 0x%X] to head\n", this, pBlockToInsert, pBlockToInsert->size));
}
// check for coalescing
if ((BYTE*)pBlockToInsert + pBlockToInsert->size == (BYTE*)pCurrent)
{
// coalesce with next
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Coalesce block [%p, 0x%X] with [%p, 0x%X] - new size 0x%X\n", this,
pBlockToInsert, pBlockToInsert->size,
pCurrent, pCurrent->size,
pCurrent->size + pBlockToInsert->size));
pBlockToInsertRW->pNext = pCurrent->pNext;
pBlockToInsertRW->size += pCurrent->size;
}
if (pPrevious && (BYTE*)pPrevious + pPrevious->size == (BYTE*)pBlockToInsert)
{
// coalesce with previous
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Coalesce block [%p, 0x%X] with [%p, 0x%X] - new size 0x%X\n", this,
pPrevious, pPrevious->size,
pBlockToInsert, pBlockToInsert->size,
pPrevious->size + pBlockToInsert->size));
previousWriterHolder.GetRW()->pNext = pBlockToInsert->pNext;
previousWriterHolder.GetRW()->size += pBlockToInsert->size;
}
return;
}
pPrevious = pCurrent;
pCurrent = pCurrent->pNext;
}
_ASSERTE(pPrevious && pCurrent == NULL);
pBlockToInsertRW->pNext = NULL;
// last in the list
ExecutableWriterHolder<TrackAllocation> previousWriterHolder2(pPrevious, sizeof(TrackAllocation));
if ((BYTE*)pPrevious + pPrevious->size == (BYTE*)pBlockToInsert)
{
// coalesce with previous
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Coalesce block [%p, 0x%X] with [%p, 0x%X] - new size 0x%X\n", this,
pPrevious, pPrevious->size,
pBlockToInsert, pBlockToInsert->size,
pPrevious->size + pBlockToInsert->size));
previousWriterHolder2.GetRW()->size += pBlockToInsert->size;
}
else
{
previousWriterHolder2.GetRW()->pNext = pBlockToInsert;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Insert block [%p, 0x%X] to end after [%p, 0x%X]\n", this,
pBlockToInsert, pBlockToInsert->size,
pPrevious, pPrevious->size));
}
return;
}
// first in the list
pBlockToInsertRW->pNext = m_pFreeList;
m_pFreeList = pBlockToInsert;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Insert block [%p, 0x%X] to head\n", this,
m_pFreeList, m_pFreeList->size));
}
void* HostCodeHeap::AllocMemForCode_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(header == sizeof(CodeHeader));
_ASSERTE(alignment <= HOST_CODEHEAP_SIZE_ALIGN);
// The code allocator has to guarantee that there is only one entrypoint per nibble map entry.
// It is guaranteed because of HostCodeHeap allocator always aligns the size up to HOST_CODEHEAP_SIZE_ALIGN,
// and because the size of nibble map entries (BYTES_PER_BUCKET) is smaller than HOST_CODEHEAP_SIZE_ALIGN.
// Assert the later fact here.
_ASSERTE(HOST_CODEHEAP_SIZE_ALIGN >= BYTES_PER_BUCKET);
header += sizeof(TrackAllocation*);
TrackAllocation* pTracker = AllocMemory_NoThrow(header, size, alignment, reserveForJumpStubs);
if (pTracker == NULL)
return NULL;
BYTE * pCode = ALIGN_UP((BYTE*)(pTracker + 1) + header, alignment);
// Pointer to the TrackAllocation record is stored just before the code header
CodeHeader * pHdr = (CodeHeader *)pCode - 1;
ExecutableWriterHolder<TrackAllocation *> trackerWriterHolder((TrackAllocation **)(pHdr) - 1, sizeof(TrackAllocation *));
*trackerWriterHolder.GetRW() = pTracker;
_ASSERTE(pCode + size <= (BYTE*)pTracker + pTracker->size);
// ref count the whole heap
m_AllocationCount++;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - ref count %d\n", this, m_AllocationCount));
return pCode;
}
HostCodeHeap::TrackAllocation* HostCodeHeap::AllocMemory_NoThrow(size_t header, size_t size, DWORD alignment, size_t reserveForJumpStubs)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifdef _DEBUG
if (g_pConfig->ShouldInjectFault(INJECTFAULT_DYNAMICCODEHEAP))
{
char *a = new (nothrow) char;
if (a == NULL)
return NULL;
delete a;
}
#endif // _DEBUG
// Skip walking the free list if the cached size of the largest block is not enough
size_t totalRequiredSize = ALIGN_UP(sizeof(TrackAllocation) + header + size + (alignment - 1) + reserveForJumpStubs, sizeof(void*));
if (totalRequiredSize > m_ApproximateLargestBlock)
return NULL;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - Allocation requested 0x%X\n", this, size));
TrackAllocation* pTracker = AllocFromFreeList(header, size, alignment, reserveForJumpStubs);
if (!pTracker)
{
// walk free list to end to find available space
size_t availableInFreeList = 0;
TrackAllocation *pCurrentBlock = m_pFreeList;
TrackAllocation *pLastBlock = NULL;
while (pCurrentBlock)
{
pLastBlock = pCurrentBlock;
pCurrentBlock = pCurrentBlock->pNext;
}
if (pLastBlock && (BYTE*)pLastBlock + pLastBlock->size == m_pLastAvailableCommittedAddr)
{
availableInFreeList = pLastBlock->size;
}
_ASSERTE(totalRequiredSize > availableInFreeList);
size_t sizeToCommit = totalRequiredSize - availableInFreeList;
sizeToCommit = ROUND_UP_TO_PAGE(sizeToCommit);
if (m_pLastAvailableCommittedAddr + sizeToCommit <= m_pBaseAddr + m_TotalBytesAvailable)
{
if (NULL == ExecutableAllocator::Instance()->Commit(m_pLastAvailableCommittedAddr, sizeToCommit, true /* isExecutable */))
{
LOG((LF_BCL, LL_ERROR, "CodeHeap [0x%p] - VirtualAlloc failed\n", this));
return NULL;
}
TrackAllocation *pBlockToInsert = (TrackAllocation*)(void*)m_pLastAvailableCommittedAddr;
ExecutableWriterHolder<TrackAllocation> blockToInsertWriterHolder(pBlockToInsert, sizeof(TrackAllocation));
blockToInsertWriterHolder.GetRW()->pNext = NULL;
blockToInsertWriterHolder.GetRW()->size = sizeToCommit;
m_pLastAvailableCommittedAddr += sizeToCommit;
AddToFreeList(pBlockToInsert, blockToInsertWriterHolder.GetRW());
pTracker = AllocFromFreeList(header, size, alignment, reserveForJumpStubs);
_ASSERTE(pTracker != NULL);
}
else
{
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap [0x%p] - allocation failed:\n\tm_pLastAvailableCommittedAddr: 0x%X\n\tsizeToCommit: 0x%X\n\tm_pBaseAddr: 0x%X\n\tm_TotalBytesAvailable: 0x%X\n", this, m_pLastAvailableCommittedAddr, sizeToCommit, m_pBaseAddr, m_TotalBytesAvailable));
// Update largest available block size
m_ApproximateLargestBlock = totalRequiredSize - 1;
}
}
return pTracker;
}
#endif //!DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void HostCodeHeap::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
DAC_ENUM_DTHIS();
TADDR addr = dac_cast<TADDR>(m_pBaseAddr);
size_t size = dac_cast<TADDR>(m_pLastAvailableCommittedAddr) - addr;
#if (_DEBUG)
// Test hook: when testing on debug builds, we want an easy way to test that the while
// correctly terminates in the face of ridiculous stuff from the target.
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DumpGeneration_IntentionallyCorruptDataFromTarget) == 1)
{
// Pretend the object is very large.
size |= 0xf0000000;
}
#endif // (_DEBUG)
while (size)
{
ULONG32 enumSize;
if (size > 0x80000000)
{
enumSize = 0x80000000;
}
else
{
enumSize = (ULONG32)size;
}
// If we can't read the target memory, stop immediately so we don't work
// with broken data.
if (!DacEnumMemoryRegion(addr, enumSize))
break;
addr += enumSize;
size -= enumSize;
}
}
#endif // DACCESS_COMPILE
// static
struct HostCodeHeap::TrackAllocation * HostCodeHeap::GetTrackAllocation(TADDR codeStart)
{
LIMITED_METHOD_CONTRACT;
CodeHeader * pHdr = dac_cast<PTR_CodeHeader>(PCODEToPINSTR(codeStart)) - 1;
// Pointer to the TrackAllocation record is stored just before the code header
return *((TrackAllocation **)(pHdr) - 1);
}
HostCodeHeap* HostCodeHeap::GetCodeHeap(TADDR codeStart)
{
WRAPPER_NO_CONTRACT;
return HostCodeHeap::GetTrackAllocation(codeStart)->pHeap;
}
#ifndef DACCESS_COMPILE
void HostCodeHeap::FreeMemForCode(void * codeStart)
{
LIMITED_METHOD_CONTRACT;
TrackAllocation *pTracker = HostCodeHeap::GetTrackAllocation((TADDR)codeStart);
ExecutableWriterHolder<TrackAllocation> trackerWriterHolder(pTracker, sizeof(TrackAllocation));
AddToFreeList(pTracker, trackerWriterHolder.GetRW());
m_ApproximateLargestBlock += pTracker->size;
m_AllocationCount--;
LOG((LF_BCL, LL_INFO100, "Level2 - CodeHeap released [0x%p, vt(0x%x)] - ref count %d\n", this, *(size_t*)this, m_AllocationCount));
if (m_AllocationCount == 0)
{
m_pJitManager->AddToCleanupList(this);
}
}
//
// Implementation for DynamicMethodDesc declared in method.hpp
//
void DynamicMethodDesc::Destroy()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(IsDynamicMethod());
LoaderAllocator *pLoaderAllocator = GetLoaderAllocator();
LOG((LF_BCL, LL_INFO1000, "Level3 - Destroying DynamicMethod {0x%p}\n", this));
// The m_pSig and m_pszMethodName need to be destroyed after the GetLCGMethodResolver()->Destroy() call
// otherwise the EEJitManager::CodeHeapIterator could return DynamicMethodDesc with these members NULLed, but
// the nibble map for the corresponding code memory indicating that this DynamicMethodDesc is still alive.
PCODE pSig = m_pSig;
PTR_CUTF8 pszMethodName = m_pszMethodName;
GetLCGMethodResolver()->Destroy();
// The current DynamicMethodDesc storage is destroyed at this point
if (pszMethodName != NULL)
{
delete[] pszMethodName;
}
if (pSig != NULL)
{
delete[] (BYTE*)pSig;
}
if (pLoaderAllocator->IsCollectible())
{
if (pLoaderAllocator->Release())
{
GCX_PREEMP();
LoaderAllocator::GCLoaderAllocators(pLoaderAllocator);
}
}
}
//
// The resolver object is reused when the method is destroyed,
// this will reset its state for the next use.
//
void LCGMethodResolver::Reset()
{
m_DynamicStringLiterals = NULL;
m_recordCodePointer = NULL;
m_UsedIndCellList = NULL;
m_pJumpStubCache = NULL;
m_next = NULL;
m_Code = NULL;
}
//
// Recycle all the indcells in m_UsedIndCellList by adding them to the free list
//
void LCGMethodResolver::RecycleIndCells()
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
// Append the list of indirection cells used by this dynamic method to the free list
IndCellList * list = m_UsedIndCellList;
if (list)
{
BYTE * cellhead = list->indcell;
BYTE * cellprev = NULL;
BYTE * cellcurr = NULL;
// Build a linked list of indirection cells from m_UsedIndCellList.
// No need to lock newlist because this method is only called during the finalization of
// DynamicResolver.DestroyScout and at that time no one else should be modifying m_UsedIndCellList.
while (list)
{
cellcurr = list->indcell;
_ASSERTE(cellcurr != NULL);
if (cellprev)
*((BYTE**)cellprev) = cellcurr;
list = list->pNext;
cellprev = cellcurr;
}
// Insert the linked list to the free list of the VirtualCallStubManager of the current domain.
// We should use GetLoaderAllocator because that is where the ind cell was allocated.
LoaderAllocator *pLoaderAllocator = GetDynamicMethod()->GetLoaderAllocator();
VirtualCallStubManager *pMgr = pLoaderAllocator->GetVirtualCallStubManager();
pMgr->InsertIntoRecycledIndCellList_Locked(cellhead, cellcurr);
m_UsedIndCellList = NULL;
}
}
void LCGMethodResolver::Destroy()
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
MODE_ANY;
} CONTRACTL_END;
LOG((LF_BCL, LL_INFO100, "Level2 - Resolver - Destroying Resolver {0x%p}\n", this));
if (m_Code)
{
delete[] m_Code;
m_Code = NULL;
}
m_CodeSize = 0;
if (!m_LocalSig.IsNull())
{
delete[] m_LocalSig.GetPtr();
m_LocalSig = SigPointer();
}
// Get the global string literal interning map
GlobalStringLiteralMap* pStringLiteralMap = SystemDomain::GetGlobalStringLiteralMapNoCreate();
// release references to all the string literals used in this Dynamic Method
if (pStringLiteralMap != NULL)
{
// lock the global string literal interning map