-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
loaderheap.cpp
2260 lines (1828 loc) · 68.8 KB
/
loaderheap.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 "stdafx.h" // Precompiled header key.
#include "loaderheap.h"
#include "ex.h"
#include "pedecoder.h"
#define DONOT_DEFINE_ETW_CALLBACK
#include "eventtracebase.h"
#define LHF_EXECUTABLE 0x1
#ifndef DACCESS_COMPILE
INDEBUG(DWORD UnlockedLoaderHeap::s_dwNumInstancesOfLoaderHeaps = 0;)
#ifdef RANDOMIZE_ALLOC
#include <time.h>
static class Random
{
public:
Random() { seed = (unsigned int)time(NULL); }
unsigned int Next()
{
return ((seed = seed * 214013L + 2531011L) >> 16) & 0x7fff;
}
private:
unsigned int seed;
} s_random;
#endif
namespace
{
#if !defined(SELF_NO_HOST) // ETW available only in the runtime
inline void EtwAllocRequest(UnlockedLoaderHeap * const pHeap, void* ptr, size_t dwSize)
{
FireEtwAllocRequest(pHeap, ptr, static_cast<unsigned int>(dwSize), 0, 0, GetClrInstanceId());
}
#else
#define EtwAllocRequest(pHeap, ptr, dwSize) ((void)0)
#endif // SELF_NO_HOST
}
//
// RangeLists are constructed so they can be searched from multiple
// threads without locking. They do require locking in order to
// be safely modified, though.
//
RangeList::RangeList()
{
WRAPPER_NO_CONTRACT;
InitBlock(&m_starterBlock);
m_firstEmptyBlock = &m_starterBlock;
m_firstEmptyRange = 0;
}
RangeList::~RangeList()
{
LIMITED_METHOD_CONTRACT;
RangeListBlock *b = m_starterBlock.next;
while (b != NULL)
{
RangeListBlock *bNext = b->next;
delete b;
b = bNext;
}
}
void RangeList::InitBlock(RangeListBlock *b)
{
LIMITED_METHOD_CONTRACT;
Range *r = b->ranges;
Range *rEnd = r + RANGE_COUNT;
while (r < rEnd)
r++->id = NULL;
b->next = NULL;
}
BOOL RangeList::AddRangeWorker(const BYTE *start, const BYTE *end, void *id)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
INJECT_FAULT(return FALSE;);
}
CONTRACTL_END
_ASSERTE(id != NULL);
RangeListBlock *b = m_firstEmptyBlock;
Range *r = b->ranges + m_firstEmptyRange;
Range *rEnd = b->ranges + RANGE_COUNT;
while (TRUE)
{
while (r < rEnd)
{
if (r->id == NULL)
{
r->start = (TADDR)start;
r->end = (TADDR)end;
r->id = (TADDR)id;
r++;
m_firstEmptyBlock = b;
m_firstEmptyRange = r - b->ranges;
return TRUE;
}
r++;
}
//
// If there are no more blocks, allocate a
// new one.
//
if (b->next == NULL)
{
RangeListBlock *newBlock = new (nothrow) RangeListBlock;
if (newBlock == NULL)
{
m_firstEmptyBlock = b;
m_firstEmptyRange = r - b->ranges;
return FALSE;
}
InitBlock(newBlock);
newBlock->next = NULL;
b->next = newBlock;
}
//
// Next block
//
b = b->next;
r = b->ranges;
rEnd = r + RANGE_COUNT;
}
}
void RangeList::RemoveRangesWorker(void *id, const BYTE* start, const BYTE* end)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
GC_NOTRIGGER;
FORBID_FAULT;
}
CONTRACTL_END
RangeListBlock *b = &m_starterBlock;
Range *r = b->ranges;
Range *rEnd = r + RANGE_COUNT;
//
// Find the first free element, & mark it.
//
while (TRUE)
{
//
// Clear entries in this block.
//
while (r < rEnd)
{
if (r->id != NULL)
{
if (start != NULL)
{
_ASSERTE(end != NULL);
if (r->start >= (TADDR)start && r->start < (TADDR)end)
{
CONSISTENCY_CHECK_MSGF(r->end >= (TADDR)start &&
r->end <= (TADDR)end,
("r: %p start: %p end: %p", r, start, end));
r->id = NULL;
}
}
else if (r->id == (TADDR)id)
{
r->id = NULL;
}
}
r++;
}
//
// If there are no more blocks, we're done.
//
if (b->next == NULL)
{
m_firstEmptyRange = 0;
m_firstEmptyBlock = &m_starterBlock;
return;
}
//
// Next block.
//
b = b->next;
r = b->ranges;
rEnd = r + RANGE_COUNT;
}
}
#endif // #ifndef DACCESS_COMPILE
BOOL RangeList::IsInRangeWorker(TADDR address, TADDR *pID /* = NULL */)
{
CONTRACTL
{
INSTANCE_CHECK;
NOTHROW;
FORBID_FAULT;
GC_NOTRIGGER;
}
CONTRACTL_END
SUPPORTS_DAC;
RangeListBlock* b = &m_starterBlock;
Range* r = b->ranges;
Range* rEnd = r + RANGE_COUNT;
//
// Look for a matching element
//
while (TRUE)
{
while (r < rEnd)
{
if (r->id != NULL &&
address >= r->start
&& address < r->end)
{
if (pID != NULL)
{
*pID = r->id;
}
return TRUE;
}
r++;
}
//
// If there are no more blocks, we're done.
//
if (b->next == NULL)
return FALSE;
//
// Next block.
//
b = b->next;
r = b->ranges;
rEnd = r + RANGE_COUNT;
}
}
#ifdef DACCESS_COMPILE
void
RangeList::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
WRAPPER_NO_CONTRACT;
// This class is almost always contained in something
// else so there's no enumeration of 'this'.
RangeListBlock* block = &m_starterBlock;
block->EnumMemoryRegions(flags);
while (block->next.IsValid())
{
block->next.EnumMem();
block = block->next;
block->EnumMemoryRegions(flags);
}
}
void
RangeList::RangeListBlock::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
Range* range;
TADDR BADFOOD;
TSIZE_T size;
int i;
// The code below iterates each range stored in the RangeListBlock and
// dumps the memory region represented by each range.
// It is too much memory for a mini-dump, so we just bail out for mini-dumps.
if (flags == CLRDATA_ENUM_MEM_MINI || flags == CLRDATA_ENUM_MEM_TRIAGE)
{
return;
}
BIT64_ONLY( BADFOOD = 0xbaadf00dbaadf00d; );
NOT_BIT64( BADFOOD = 0xbaadf00d; );
for (i=0; i<RANGE_COUNT; i++)
{
range = &(this->ranges[i]);
if (range->id == NULL || range->start == NULL || range->end == NULL ||
// just looking at the lower 4bytes is good enough on WIN64
range->start == BADFOOD || range->end == BADFOOD)
{
break;
}
size = range->end - range->start;
_ASSERTE( size < UINT32_MAX ); // ranges should be less than 4gig!
// We can't be sure this entire range is mapped. For example, the code:StubLinkStubManager
// keeps track of all ranges in the code:BaseDomain::m_pStubHeap LoaderHeap, and
// code:LoaderHeap::UnlockedReservePages adds a range for the entire reserved region, instead
// of updating the RangeList when pages are committed. But in that case, the committed region of
// memory will be enumerated by the LoaderHeap anyway, so it's OK if this fails
DacEnumMemoryRegion(range->start, size, false);
}
}
#endif // #ifdef DACCESS_COMPILE
//=====================================================================================
// In DEBUG builds only, we tag live blocks with the requested size and the type of
// allocation (AllocMem, AllocAlignedMem, AllocateOntoReservedMem). This is strictly
// to validate that those who call Backout* are passing in the right values.
//
// For simplicity, we'll use one LoaderHeapValidationTag structure for all types even
// though not all fields are applicable to all types.
//=====================================================================================
#ifdef _DEBUG
enum AllocationType
{
kAllocMem = 1,
kFreedMem = 4,
};
struct LoaderHeapValidationTag
{
size_t m_dwRequestedSize; // What the caller requested (not what was actually allocated)
AllocationType m_allocationType; // Which api allocated this block.
const char * m_szFile; // Who allocated me
int m_lineNum; // Who allocated me
};
#endif //_DEBUG
//=====================================================================================
// These classes do detailed loaderheap sniffing to help in debugging heap crashes
//=====================================================================================
#ifdef _DEBUG
// This structure logs the results of an Alloc or Free call. They are stored in reverse time order
// with UnlockedLoaderHeap::m_pEventList pointing to the most recent event.
struct LoaderHeapEvent
{
LoaderHeapEvent *m_pNext;
AllocationType m_allocationType; //Which api was called
const char *m_szFile; //Caller Id
int m_lineNum; //Caller Id
const char *m_szAllocFile; //(BackoutEvents): Who allocated the block?
int m_allocLineNum; //(BackoutEvents): Who allocated the block?
void *m_pMem; //Starting address of block
size_t m_dwRequestedSize; //Requested size of block
size_t m_dwSize; //Actual size of block (including validation tags, padding, everything)
void Describe(SString *pSString)
{
CONTRACTL
{
INSTANCE_CHECK;
DISABLED(NOTHROW);
GC_NOTRIGGER;
}
CONTRACTL_END
pSString->AppendASCII("\n");
{
StackSString buf;
if (m_allocationType == kFreedMem)
{
buf.Printf(" Freed at: %s (line %d)\n", m_szFile, m_lineNum);
buf.Printf(" (block originally allocated at %s (line %d)\n", m_szAllocFile, m_allocLineNum);
}
else
{
buf.Printf(" Allocated at: %s (line %d)\n", m_szFile, m_lineNum);
}
pSString->Append(buf);
}
if (!QuietValidate())
{
pSString->AppendASCII(" *** THIS BLOCK HAS BEEN CORRUPTED ***\n");
}
{
StackSString buf;
buf.Printf(" Type: ");
switch (m_allocationType)
{
case kAllocMem:
buf.AppendASCII("AllocMem()\n");
break;
case kFreedMem:
buf.AppendASCII("Free\n");
break;
default:
break;
}
pSString->Append(buf);
}
{
StackSString buf;
buf.Printf(" Start of block: 0x%p\n", m_pMem);
pSString->Append(buf);
}
{
StackSString buf;
buf.Printf(" End of block: 0x%p\n", ((BYTE*)m_pMem) + m_dwSize - 1);
pSString->Append(buf);
}
{
StackSString buf;
buf.Printf(" Requested size: %lu (0x%lx)\n", (ULONG)m_dwRequestedSize, (ULONG)m_dwRequestedSize);
pSString->Append(buf);
}
{
StackSString buf;
buf.Printf(" Actual size: %lu (0x%lx)\n", (ULONG)m_dwSize, (ULONG)m_dwSize);
pSString->Append(buf);
}
pSString->AppendASCII("\n");
}
BOOL QuietValidate();
};
class LoaderHeapSniffer
{
public:
static DWORD InitDebugFlags()
{
WRAPPER_NO_CONTRACT;
DWORD dwDebugFlags = 0;
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_LoaderHeapCallTracing))
{
dwDebugFlags |= UnlockedLoaderHeap::kCallTracing;
}
return dwDebugFlags;
}
static VOID RecordEvent(UnlockedLoaderHeap *pHeap,
AllocationType allocationType,
__in const char *szFile,
int lineNum,
__in const char *szAllocFile,
int allocLineNum,
void *pMem,
size_t dwRequestedSize,
size_t dwSize
);
static VOID ClearEvents(UnlockedLoaderHeap *pHeap)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_FORBID_FAULT;
LoaderHeapEvent *pEvent = pHeap->m_pEventList;
while (pEvent)
{
LoaderHeapEvent *pNext = pEvent->m_pNext;
delete pEvent;
pEvent = pNext;
}
pHeap->m_pEventList = NULL;
}
static VOID CompactEvents(UnlockedLoaderHeap *pHeap)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_FORBID_FAULT;
LoaderHeapEvent **ppEvent = &(pHeap->m_pEventList);
while (*ppEvent)
{
LoaderHeapEvent *pEvent = *ppEvent;
if (pEvent->m_allocationType != kFreedMem)
{
ppEvent = &(pEvent->m_pNext);
}
else
{
LoaderHeapEvent **ppWalk = &(pEvent->m_pNext);
BOOL fMatchFound = FALSE;
while (*ppWalk && !fMatchFound)
{
LoaderHeapEvent *pWalk = *ppWalk;
if (pWalk->m_allocationType != kFreedMem &&
pWalk->m_pMem == pEvent->m_pMem &&
pWalk->m_dwRequestedSize == pEvent->m_dwRequestedSize)
{
// Delete matched pairs
// Order is important here - updating *ppWalk may change pEvent->m_pNext, and we want
// to get the updated value when we unlink pEvent.
*ppWalk = pWalk->m_pNext;
*ppEvent = pEvent->m_pNext;
delete pEvent;
delete pWalk;
fMatchFound = TRUE;
}
else
{
ppWalk = &(pWalk->m_pNext);
}
}
if (!fMatchFound)
{
ppEvent = &(pEvent->m_pNext);
}
}
}
}
static VOID PrintEvents(UnlockedLoaderHeap *pHeap)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_FORBID_FAULT;
printf("\n------------- LoaderHeapEvents (in reverse time order!) --------------------");
LoaderHeapEvent *pEvent = pHeap->m_pEventList;
while (pEvent)
{
printf("\n");
switch (pEvent->m_allocationType)
{
case kAllocMem: printf("AllocMem "); break;
case kFreedMem: printf("BackoutMem "); break;
}
printf(" ptr = 0x%-8p", pEvent->m_pMem);
printf(" rqsize = 0x%-8x", (DWORD)pEvent->m_dwRequestedSize);
printf(" actsize = 0x%-8x", (DWORD)pEvent->m_dwSize);
printf(" (at %s@%d)", pEvent->m_szFile, pEvent->m_lineNum);
if (pEvent->m_allocationType == kFreedMem)
{
printf(" (original allocation at %s@%d)", pEvent->m_szAllocFile, pEvent->m_allocLineNum);
}
pEvent = pEvent->m_pNext;
}
printf("\n------------- End of LoaderHeapEvents --------------------------------------");
printf("\n");
}
static VOID PitchSniffer(SString *pSString)
{
WRAPPER_NO_CONTRACT;
pSString->AppendASCII("\n"
"\nBecause call-tracing wasn't turned on, we couldn't provide details about who last owned the affected memory block. To get more precise diagnostics,"
"\nset the following registry DWORD value:"
"\n"
"\n HKLM\\Software\\Microsoft\\.NETFramework\\LoaderHeapCallTracing = 1"
"\n"
"\nand rerun the scenario that crashed."
"\n"
"\n");
}
static LoaderHeapEvent *FindEvent(UnlockedLoaderHeap *pHeap, void *pAddr)
{
LIMITED_METHOD_CONTRACT;
LoaderHeapEvent *pEvent = pHeap->m_pEventList;
while (pEvent)
{
if (pAddr >= pEvent->m_pMem && pAddr <= ( ((BYTE*)pEvent->m_pMem) + pEvent->m_dwSize - 1))
{
return pEvent;
}
pEvent = pEvent->m_pNext;
}
return NULL;
}
static void ValidateFreeList(UnlockedLoaderHeap *pHeap);
static void WeGotAFaultNowWhat(UnlockedLoaderHeap *pHeap)
{
WRAPPER_NO_CONTRACT;
ValidateFreeList(pHeap);
//If none of the above popped up an assert, pop up a generic one.
_ASSERTE(!("Unexpected AV inside LoaderHeap. The usual reason is that someone overwrote the end of a block or wrote into a freed block.\n"));
}
};
#endif
#ifdef _DEBUG
#define LOADER_HEAP_BEGIN_TRAP_FAULT BOOL __faulted = FALSE; EX_TRY {
#define LOADER_HEAP_END_TRAP_FAULT } EX_CATCH {__faulted = TRUE; } EX_END_CATCH(SwallowAllExceptions) if (__faulted) LoaderHeapSniffer::WeGotAFaultNowWhat(pHeap);
#else
#define LOADER_HEAP_BEGIN_TRAP_FAULT
#define LOADER_HEAP_END_TRAP_FAULT
#endif
size_t AllocMem_TotalSize(size_t dwRequestedSize, UnlockedLoaderHeap *pHeap);
//=====================================================================================
// This freelist implementation is a first cut and probably needs to be tuned.
// It should be tuned with the following assumptions:
//
// - Freeing LoaderHeap memory is done primarily for OOM backout. LoaderHeaps
// weren't designed to be general purpose heaps and shouldn't be used that way.
//
// - And hence, when memory is freed, expect it to be freed in large clumps and in a
// LIFO order. Since the LoaderHeap normally hands out memory with sequentially
// increasing addresses, blocks will typically be freed with sequentially decreasing
// addresses.
//
// The first cut of the freelist is a single-linked list of free blocks using first-fit.
// Assuming the above alloc-free pattern holds, the list will end up mostly sorted
// in increasing address order. When a block is freed, we'll attempt to coalesce it
// with the first block in the list. We could also choose to be more aggressive about
// sorting and coalescing but this should probably catch most cases in practice.
//=====================================================================================
// When a block is freed, we place this structure on the first bytes of the freed block (Allocations
// are bumped in size if necessary to make sure there's room.)
struct LoaderHeapFreeBlock
{
public:
LoaderHeapFreeBlock *m_pNext; // Pointer to next block on free list
size_t m_dwSize; // Total size of this block (including this header)
//! Try not to grow the size of this structure. It places a minimum size on LoaderHeap allocations.
static void InsertFreeBlock(LoaderHeapFreeBlock **ppHead, void *pMem, size_t dwTotalSize, UnlockedLoaderHeap *pHeap)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
LOADER_HEAP_BEGIN_TRAP_FAULT
// It's illegal to insert a free block that's smaller than the minimum sized allocation -
// it may stay stranded on the freelist forever.
#ifdef _DEBUG
if (!(dwTotalSize >= AllocMem_TotalSize(1, pHeap)))
{
LoaderHeapSniffer::ValidateFreeList(pHeap);
_ASSERTE(dwTotalSize >= AllocMem_TotalSize(1, pHeap));
}
if (!(0 == (dwTotalSize & ALLOC_ALIGN_CONSTANT)))
{
LoaderHeapSniffer::ValidateFreeList(pHeap);
_ASSERTE(0 == (dwTotalSize & ALLOC_ALIGN_CONSTANT));
}
#endif
INDEBUG(memset(pMem, 0xcc, dwTotalSize);)
LoaderHeapFreeBlock *pNewBlock = (LoaderHeapFreeBlock*)pMem;
pNewBlock->m_pNext = *ppHead;
pNewBlock->m_dwSize = dwTotalSize;
*ppHead = pNewBlock;
MergeBlock(pNewBlock, pHeap);
LOADER_HEAP_END_TRAP_FAULT
}
static void *AllocFromFreeList(LoaderHeapFreeBlock **ppHead, size_t dwSize, BOOL fRemoveFromFreeList, UnlockedLoaderHeap *pHeap)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
INCONTRACT(_ASSERTE_IMPL(!ARE_FAULTS_FORBIDDEN()));
void *pResult = NULL;
LOADER_HEAP_BEGIN_TRAP_FAULT
LoaderHeapFreeBlock **ppWalk = ppHead;
while (*ppWalk)
{
LoaderHeapFreeBlock *pCur = *ppWalk;
size_t dwCurSize = pCur->m_dwSize;
if (dwCurSize == dwSize)
{
pResult = pCur;
// Exact match. Hooray!
if (fRemoveFromFreeList)
{
*ppWalk = pCur->m_pNext;
}
break;
}
else if (dwCurSize > dwSize && (dwCurSize - dwSize) >= AllocMem_TotalSize(1, pHeap))
{
// Partial match. Ok...
pResult = pCur;
if (fRemoveFromFreeList)
{
*ppWalk = pCur->m_pNext;
InsertFreeBlock(ppWalk, ((BYTE*)pCur) + dwSize, dwCurSize - dwSize, pHeap );
}
break;
}
// Either block is too small or splitting the block would leave a remainder that's smaller than
// the minimum block size. Onto next one.
ppWalk = &( pCur->m_pNext );
}
if (pResult && fRemoveFromFreeList)
{
// Callers of loaderheap assume allocated memory is zero-inited so we must preserve this invariant!
memset(pResult, 0, dwSize);
}
LOADER_HEAP_END_TRAP_FAULT
return pResult;
}
private:
// Try to merge pFreeBlock with its immediate successor. Return TRUE if a merge happened. FALSE if no merge happened.
static BOOL MergeBlock(LoaderHeapFreeBlock *pFreeBlock, UnlockedLoaderHeap *pHeap)
{
STATIC_CONTRACT_NOTHROW;
BOOL result = FALSE;
LOADER_HEAP_BEGIN_TRAP_FAULT
LoaderHeapFreeBlock *pNextBlock = pFreeBlock->m_pNext;
size_t dwSize = pFreeBlock->m_dwSize;
if (pNextBlock == NULL || ((BYTE*)pNextBlock) != (((BYTE*)pFreeBlock) + dwSize))
{
result = FALSE;
}
else
{
size_t dwCombinedSize = dwSize + pNextBlock->m_dwSize;
LoaderHeapFreeBlock *pNextNextBlock = pNextBlock->m_pNext;
INDEBUG(memset(pFreeBlock, 0xcc, dwCombinedSize);)
pFreeBlock->m_pNext = pNextNextBlock;
pFreeBlock->m_dwSize = dwCombinedSize;
result = TRUE;
}
LOADER_HEAP_END_TRAP_FAULT
return result;
}
};
//=====================================================================================
// These helpers encapsulate the actual layout of a block allocated by AllocMem
// and UnlockedAllocMem():
//
// ==> Starting address is always pointer-aligned.
//
// - x bytes of user bytes (where "x" is the actual dwSize passed into AllocMem)
//
// - y bytes of "EE" (DEBUG-ONLY) (where "y" == LOADER_HEAP_DEBUG_BOUNDARY (normally 0))
// - z bytes of pad (DEBUG-ONLY) (where "z" is just enough to pointer-align the following byte)
// - a bytes of tag (DEBUG-ONLY) (where "a" is sizeof(LoaderHeapValidationTag)
//
// - b bytes of pad (if total size after all this < sizeof(LoaderHeapFreeBlock), pad enough to make it the size of LoaderHeapFreeBlock)
// - c bytes of pad (where "c" is just enough to pointer-align the following byte)
//
// ==> Following address is always pointer-aligned
//=====================================================================================
// Convert the requested size into the total # of bytes we'll actually allocate (including padding)
inline size_t AllocMem_TotalSize(size_t dwRequestedSize, UnlockedLoaderHeap *pHeap)
{
LIMITED_METHOD_CONTRACT;
size_t dwSize = dwRequestedSize;
#ifdef _DEBUG
dwSize += LOADER_HEAP_DEBUG_BOUNDARY;
dwSize = ((dwSize + ALLOC_ALIGN_CONSTANT) & (~ALLOC_ALIGN_CONSTANT));
#endif
if (!pHeap->m_fExplicitControl)
{
#ifdef _DEBUG
dwSize += sizeof(LoaderHeapValidationTag);
#endif
if (dwSize < sizeof(LoaderHeapFreeBlock))
{
dwSize = sizeof(LoaderHeapFreeBlock);
}
}
dwSize = ((dwSize + ALLOC_ALIGN_CONSTANT) & (~ALLOC_ALIGN_CONSTANT));
return dwSize;
}
#ifdef _DEBUG
LoaderHeapValidationTag *AllocMem_GetTag(LPVOID pBlock, size_t dwRequestedSize)
{
LIMITED_METHOD_CONTRACT;
size_t dwSize = dwRequestedSize;
dwSize += LOADER_HEAP_DEBUG_BOUNDARY;
dwSize = ((dwSize + ALLOC_ALIGN_CONSTANT) & (~ALLOC_ALIGN_CONSTANT));
return (LoaderHeapValidationTag *)( ((BYTE*)pBlock) + dwSize );
}
#endif
//=====================================================================================
// UnlockedLoaderHeap methods
//=====================================================================================
#ifndef DACCESS_COMPILE
UnlockedLoaderHeap::UnlockedLoaderHeap(DWORD dwReserveBlockSize,
DWORD dwCommitBlockSize,
const BYTE* dwReservedRegionAddress,
SIZE_T dwReservedRegionSize,
RangeList *pRangeList,
BOOL fMakeExecutable)
{
CONTRACTL
{
CONSTRUCTOR_CHECK;
NOTHROW;
FORBID_FAULT;
}
CONTRACTL_END;
m_pFirstBlock = NULL;
m_dwReserveBlockSize = dwReserveBlockSize;
m_dwCommitBlockSize = dwCommitBlockSize;
m_pPtrToEndOfCommittedRegion = NULL;
m_pEndReservedRegion = NULL;
m_pAllocPtr = NULL;
m_pRangeList = pRangeList;
// Round to VIRTUAL_ALLOC_RESERVE_GRANULARITY
m_dwTotalAlloc = 0;
#ifdef _DEBUG
m_dwDebugWastedBytes = 0;
s_dwNumInstancesOfLoaderHeaps++;
m_pEventList = NULL;
m_dwDebugFlags = LoaderHeapSniffer::InitDebugFlags();
m_fPermitStubsWithUnwindInfo = FALSE;
m_fStubUnwindInfoUnregistered= FALSE;
#endif
m_Options = 0;
#ifndef CROSSGEN_COMPILE
if (fMakeExecutable)
m_Options |= LHF_EXECUTABLE;
#endif // CROSSGEN_COMPILE
m_pFirstFreeBlock = NULL;
if (dwReservedRegionAddress != NULL && dwReservedRegionSize > 0)
{
m_reservedBlock.Init((void *)dwReservedRegionAddress, dwReservedRegionSize, FALSE);
}
}
// ~LoaderHeap is not synchronised (obviously)
UnlockedLoaderHeap::~UnlockedLoaderHeap()
{
CONTRACTL
{
DESTRUCTOR_CHECK;
NOTHROW;
FORBID_FAULT;
}
CONTRACTL_END
_ASSERTE(!m_fPermitStubsWithUnwindInfo || m_fStubUnwindInfoUnregistered);
if (m_pRangeList != NULL)
m_pRangeList->RemoveRanges((void *) this);
LoaderHeapBlock *pSearch, *pNext;
for (pSearch = m_pFirstBlock; pSearch; pSearch = pNext)
{
void * pVirtualAddress;
BOOL fReleaseMemory;
pVirtualAddress = pSearch->pVirtualAddress;
fReleaseMemory = pSearch->m_fReleaseMemory;
pNext = pSearch->pNext;
if (fReleaseMemory)
{
BOOL fSuccess;
fSuccess = ClrVirtualFree(pVirtualAddress, 0, MEM_RELEASE);
_ASSERTE(fSuccess);
}
delete pSearch;
}
if (m_reservedBlock.m_fReleaseMemory)
{
BOOL fSuccess;
fSuccess = ClrVirtualFree(m_reservedBlock.pVirtualAddress, 0, MEM_RELEASE);
_ASSERTE(fSuccess);
}
INDEBUG(s_dwNumInstancesOfLoaderHeaps --;)
}
void UnlockedLoaderHeap::UnlockedSetReservedRegion(BYTE* dwReservedRegionAddress, SIZE_T dwReservedRegionSize, BOOL fReleaseMemory)
{
WRAPPER_NO_CONTRACT;