forked from chakra-core/ChakraCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomHeap.cpp
More file actions
1222 lines (1053 loc) · 40.6 KB
/
Copy pathCustomHeap.cpp
File metadata and controls
1222 lines (1053 loc) · 40.6 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
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "CommonMemoryPch.h"
#if ENABLE_NATIVE_CODEGEN || DYNAMIC_INTERPRETER_THUNK
#include "Memory/XDataAllocator.h"
#if defined(_M_ARM) && defined(_WIN32)
#include <wchar.h>
#endif
#include "CustomHeap.h"
#if PDATA_ENABLED && defined(_WIN32)
#include "Core/DelayLoadLibrary.h"
#include <malloc.h>
#endif
namespace Memory
{
namespace CustomHeap
{
#pragma region "Constructor and Destructor"
template<typename TAlloc, typename TPreReservedAlloc>
Heap<TAlloc, TPreReservedAlloc>::Heap(ArenaAllocator * alloc, CodePageAllocators<TAlloc, TPreReservedAlloc> * codePageAllocators, HANDLE processHandle):
auxiliaryAllocator(alloc),
codePageAllocators(codePageAllocators),
lastSecondaryAllocStateChangedCount(0),
processHandle(processHandle)
#if DBG_DUMP
, freeObjectSize(0)
, totalAllocationSize(0)
, allocationsSinceLastCompact(0)
, freesSinceLastCompact(0)
#endif
#if DBG
, inDtor(false)
#endif
{
for (int i = 0; i < NumBuckets; i++)
{
this->buckets[i].Reset();
}
}
template<typename TAlloc, typename TPreReservedAlloc>
Heap<TAlloc, TPreReservedAlloc>::~Heap()
{
#if DBG
inDtor = true;
#endif
this->FreeAll();
}
#pragma endregion
#pragma region "Public routines"
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeAll()
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
FreeBuckets(false);
FreeLargeObjects();
FreeDecommittedBuckets();
FreeDecommittedLargeObjects();
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::Free(_In_ Allocation* object)
{
Assert(object != nullptr);
if (object == nullptr)
{
return;
}
BucketId bucket = (BucketId) GetBucketForSize(object->size);
if (bucket == BucketId::LargeObjectList)
{
#if PDATA_ENABLED
if(!object->xdata.IsFreed())
{
FreeXdata(&object->xdata, object->largeObjectAllocation.segment);
}
#endif
if (!object->largeObjectAllocation.isDecommitted)
{
FreeLargeObject(object);
}
return;
}
#if PDATA_ENABLED
if(!object->xdata.IsFreed())
{
FreeXdata(&object->xdata, object->page->segment);
}
#endif
if (!object->page->isDecommitted)
{
FreeAllocation(object);
}
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::DecommitAll()
{
// This function doesn't really touch the page allocator data structure.
// DecommitPages is merely a wrapper for VirtualFree
// So no need to take the critical section to synchronize
DListBase<Allocation>::EditingIterator i(&this->largeObjectAllocations);
while (i.Next())
{
Allocation& allocation = i.Data();
Assert(!allocation.largeObjectAllocation.isDecommitted);
this->codePageAllocators->DecommitPages(allocation.address, allocation.GetPageCount(), allocation.largeObjectAllocation.segment);
i.MoveCurrentTo(&this->decommittedLargeObjects);
allocation.largeObjectAllocation.isDecommitted = true;
}
for (int bucket = 0; bucket < BucketId::NumBuckets; bucket++)
{
FOREACH_DLISTBASE_ENTRY_EDITING(Page, page, &(this->fullPages[bucket]), bucketIter1)
{
Assert(page.inFullList);
this->codePageAllocators->DecommitPages(page.address, 1 /* pageCount */, page.segment);
bucketIter1.MoveCurrentTo(&(this->decommittedPages));
page.isDecommitted = true;
}
NEXT_DLISTBASE_ENTRY_EDITING;
FOREACH_DLISTBASE_ENTRY_EDITING(Page, page, &(this->buckets[bucket]), bucketIter2)
{
Assert(!page.inFullList);
this->codePageAllocators->DecommitPages(page.address, 1 /* pageCount */, page.segment);
bucketIter2.MoveCurrentTo(&(this->decommittedPages));
page.isDecommitted = true;
}
NEXT_DLISTBASE_ENTRY_EDITING;
}
}
template<typename TAlloc, typename TPreReservedAlloc>
bool Heap<TAlloc, TPreReservedAlloc>::IsInHeap(DListBase<Page> const& bucket, _In_ void * address)
{
DListBase<Page>::Iterator i(&bucket);
while (i.Next())
{
Page& page = i.Data();
if (page.address <= address && address < page.address + AutoSystemInfo::PageSize)
{
return true;
}
}
return false;
}
template<typename TAlloc, typename TPreReservedAlloc>
bool Heap<TAlloc, TPreReservedAlloc>::IsInHeap(DListBase<Page> const buckets[NumBuckets], _In_ void * address)
{
for (uint i = 0; i < NumBuckets; i++)
{
if (this->IsInHeap(buckets[i], address))
{
return true;
}
}
return false;
}
template<typename TAlloc, typename TPreReservedAlloc>
bool Heap<TAlloc, TPreReservedAlloc>::IsInHeap(DListBase<Allocation> const& allocations, _In_ void *address)
{
DListBase<Allocation>::Iterator i(&allocations);
while (i.Next())
{
Allocation& allocation = i.Data();
if (allocation.address <= address && address < allocation.address + allocation.size)
{
return true;
}
}
return false;
}
template<typename TAlloc, typename TPreReservedAlloc>
bool Heap<TAlloc, TPreReservedAlloc>::IsInHeap(_In_ void* address)
{
return IsInHeap(buckets, address) || IsInHeap(fullPages, address) || IsInHeap(largeObjectAllocations, address);
}
template<typename TAlloc, typename TPreReservedAlloc>
Page * Heap<TAlloc, TPreReservedAlloc>::GetExistingPage(BucketId bucket, bool canAllocInPreReservedHeapPageSegment)
{
// TODO: this can get a non-prereserved page even if you want one
if (!this->buckets[bucket].Empty())
{
Assert(!this->buckets[bucket].Head().inFullList);
return &this->buckets[bucket].Head();
}
return FindPageToSplit(bucket, canAllocInPreReservedHeapPageSegment);
}
/*
* Algorithm:
* - Find bucket
* - Check bucket pages - if it has enough free space, allocate that chunk
* - Check pages in bigger buckets - if that has enough space, split that page and allocate from that chunk
* - Allocate new page
*/
template<typename TAlloc, typename TPreReservedAlloc>
Allocation* Heap<TAlloc, TPreReservedAlloc>::Alloc(size_t bytes, ushort pdataCount, ushort xdataSize, bool canAllocInPreReservedHeapPageSegment, bool isAnyJittedCode, _Inout_ bool* isAllJITCodeInPreReservedRegion)
{
Assert(bytes > 0);
Assert((codePageAllocators->AllocXdata() || pdataCount == 0) && (!codePageAllocators->AllocXdata() || pdataCount > 0));
Assert(pdataCount > 0 || (pdataCount == 0 && xdataSize == 0));
// Round up to power of two to allocate, and figure out which bucket to allocate in
int _;
size_t bytesToAllocate = PowerOf2Policy::GetSize(bytes, &_ /* modFunctionIndex */);
BucketId bucket = (BucketId) GetBucketForSize(bytesToAllocate);
if (bucket == BucketId::LargeObjectList)
{
return AllocLargeObject(bytes, pdataCount, xdataSize, canAllocInPreReservedHeapPageSegment, isAnyJittedCode, isAllJITCodeInPreReservedRegion);
}
VerboseHeapTrace(_u("Bucket is %d\n"), bucket);
VerboseHeapTrace(_u("Requested: %d bytes. Allocated: %d bytes\n"), bytes, bytesToAllocate);
do
{
Page* page = GetExistingPage(bucket, canAllocInPreReservedHeapPageSegment);
if (page == nullptr && UpdateFullPages())
{
page = GetExistingPage(bucket, canAllocInPreReservedHeapPageSegment);
}
if (page == nullptr)
{
page = AllocNewPage(bucket, canAllocInPreReservedHeapPageSegment, isAnyJittedCode, isAllJITCodeInPreReservedRegion);
}
else if (!canAllocInPreReservedHeapPageSegment && isAnyJittedCode)
{
*isAllJITCodeInPreReservedRegion = false;
}
// Out of memory
if (page == nullptr)
{
return nullptr;
}
#if defined(DBG)
MEMORY_BASIC_INFORMATION memBasicInfo;
size_t resultBytes = VirtualQueryEx(this->processHandle, page->address, &memBasicInfo, sizeof(memBasicInfo));
if (resultBytes == 0)
{
MemoryOperationLastError::RecordLastError();
}
else
{
Assert(memBasicInfo.Protect == PAGE_EXECUTE_READ);
}
#endif
Allocation* allocation = nullptr;
if (AllocInPage(page, bytesToAllocate, pdataCount, xdataSize, &allocation))
{
return allocation;
}
} while (true);
}
template<typename TAlloc, typename TPreReservedAlloc>
BOOL Heap<TAlloc, TPreReservedAlloc>::ProtectAllocationWithExecuteReadWrite(Allocation *allocation, __in_opt char* addressInPage)
{
DWORD protectFlags = 0;
if (GlobalSecurityPolicy::IsCFGEnabled())
{
protectFlags = PAGE_EXECUTE_RW_TARGETS_NO_UPDATE;
}
else
{
#if defined(__APPLE__) && defined(_M_ARM64)
protectFlags = PAGE_READWRITE; // PAGE_EXECUTE_READWRITE banned on Apple Silicon
#else
protectFlags = PAGE_EXECUTE_READWRITE;
#endif
}
return this->ProtectAllocation(allocation, protectFlags, PAGE_EXECUTE_READ, addressInPage);
}
template<typename TAlloc, typename TPreReservedAlloc>
BOOL Heap<TAlloc, TPreReservedAlloc>::ProtectAllocationWithExecuteReadOnly(_In_ Allocation *allocation, __in_opt char* addressInPage)
{
DWORD protectFlags = 0;
if (GlobalSecurityPolicy::IsCFGEnabled())
{
protectFlags = PAGE_EXECUTE_RO_TARGETS_NO_UPDATE;
}
else
{
protectFlags = PAGE_EXECUTE_READ;
}
#if defined(__APPLE__) && defined(_M_ARM64)
return this->ProtectAllocation(allocation, protectFlags, PAGE_READWRITE, addressInPage); // PAGE_EXECUTE_READWRITE banned on Apple Silicon
#else
return this->ProtectAllocation(allocation, protectFlags, PAGE_EXECUTE_READWRITE, addressInPage);
#endif
}
template<typename TAlloc, typename TPreReservedAlloc>
BOOL Heap<TAlloc, TPreReservedAlloc>::ProtectAllocation(_In_ Allocation* allocation, DWORD dwVirtualProtectFlags, DWORD desiredOldProtectFlag, __in_opt char* addressInPage)
{
// Allocate at the page level so that our protections don't
// transcend allocation page boundaries. Here, allocation->address is page
// aligned if the object is a large object allocation. If it isn't, in the else
// branch of the following if statement, we set it to the allocation's page's
// address. This ensures that the address being protected is always page aligned
Assert(allocation != nullptr);
Assert(allocation->isAllocationUsed);
Assert(addressInPage == nullptr || (addressInPage >= allocation->address && addressInPage < (allocation->address + allocation->size)));
char* address = allocation->address;
size_t pageCount;
void * segment;
if (allocation->IsLargeAllocation())
{
#if DBG_DUMP || defined(RECYCLER_TRACE)
if (Js::Configuration::Global.flags.IsEnabled(Js::TraceProtectPagesFlag))
{
Output::Print(_u("Protecting large allocation\n"));
}
#endif
segment = allocation->largeObjectAllocation.segment;
if (addressInPage != nullptr)
{
if (addressInPage >= allocation->address + AutoSystemInfo::PageSize)
{
size_t page = (addressInPage - allocation->address) / AutoSystemInfo::PageSize;
address = allocation->address + (page * AutoSystemInfo::PageSize);
}
pageCount = 1;
}
else
{
pageCount = allocation->GetPageCount();
}
VerboseHeapTrace(_u("Protecting 0x%p with 0x%x\n"), address, dwVirtualProtectFlags);
return this->codePageAllocators->ProtectPages(address, pageCount, segment, dwVirtualProtectFlags, desiredOldProtectFlag);
}
else
{
#if DBG_DUMP || defined(RECYCLER_TRACE)
if (Js::Configuration::Global.flags.IsEnabled(Js::TraceProtectPagesFlag))
{
Output::Print(_u("Protecting small allocation\n"));
}
#endif
segment = allocation->page->segment;
address = allocation->page->address;
pageCount = 1;
VerboseHeapTrace(_u("Protecting 0x%p with 0x%x\n"), address, dwVirtualProtectFlags);
return this->codePageAllocators->ProtectPages(address, pageCount, segment, dwVirtualProtectFlags, desiredOldProtectFlag);
}
}
#pragma endregion
#pragma region "Large object methods"
template<typename TAlloc, typename TPreReservedAlloc>
Allocation* Heap<TAlloc, TPreReservedAlloc>::AllocLargeObject(size_t bytes, ushort pdataCount, ushort xdataSize, bool canAllocInPreReservedHeapPageSegment, bool isAnyJittedCode, _Inout_ bool* isAllJITCodeInPreReservedRegion)
{
size_t pages = GetNumPagesForSize(bytes);
if (pages == 0)
{
return nullptr;
}
void * segment = nullptr;
char* address = nullptr;
#if PDATA_ENABLED
XDataAllocation xdata;
#endif
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
address = this->codePageAllocators->Alloc(&pages, &segment, canAllocInPreReservedHeapPageSegment, isAnyJittedCode, isAllJITCodeInPreReservedRegion);
// Out of memory
if (address == nullptr)
{
return nullptr;
}
char* localAddr = this->codePageAllocators->AllocLocal(address, pages*AutoSystemInfo::PageSize, segment);
if (!localAddr)
{
return nullptr;
}
FillDebugBreak((BYTE*)localAddr, pages*AutoSystemInfo::PageSize);
this->codePageAllocators->FreeLocal(localAddr, segment);
if (this->processHandle == GetCurrentProcess())
{
DWORD protectFlags = 0;
if (GlobalSecurityPolicy::IsCFGEnabled())
{
protectFlags = PAGE_EXECUTE_RO_TARGETS_NO_UPDATE;
}
else
{
protectFlags = PAGE_EXECUTE_READ;
}
this->codePageAllocators->ProtectPages(address, pages, segment, protectFlags /*dwVirtualProtectFlags*/, PAGE_READWRITE /*desiredOldProtectFlags*/);
}
#if PDATA_ENABLED
if(pdataCount > 0)
{
if (!this->codePageAllocators->AllocSecondary(segment, (ULONG_PTR) address, bytes, pdataCount, xdataSize, &xdata))
{
this->codePageAllocators->Release(address, pages, segment);
return nullptr;
}
}
#endif
}
#if defined(DBG)
MEMORY_BASIC_INFORMATION memBasicInfo;
size_t resultBytes = VirtualQueryEx(this->processHandle, address, &memBasicInfo, sizeof(memBasicInfo));
if (resultBytes == 0)
{
MemoryOperationLastError::RecordLastError();
}
else
{
Assert(memBasicInfo.Protect == PAGE_EXECUTE_READ);
}
#endif
Allocation* allocation = this->largeObjectAllocations.PrependNode(this->auxiliaryAllocator);
if (allocation == nullptr)
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
this->codePageAllocators->Release(address, pages, segment);
#if PDATA_ENABLED
if(pdataCount > 0)
{
this->codePageAllocators->ReleaseSecondary(xdata, segment);
}
#endif
return nullptr;
}
allocation->address = address;
allocation->largeObjectAllocation.segment = segment;
allocation->largeObjectAllocation.isDecommitted = false;
allocation->size = pages * AutoSystemInfo::PageSize;
allocation->thunkAddress = 0;
#if PDATA_ENABLED
allocation->xdata = xdata;
#endif
return allocation;
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeDecommittedLargeObjects()
{
// CodePageAllocators is locked in FreeAll
Assert(inDtor);
FOREACH_DLISTBASE_ENTRY_EDITING(Allocation, allocation, &this->decommittedLargeObjects, largeObjectIter)
{
VerboseHeapTrace(_u("Decommitting large object at address 0x%p of size %u\n"), allocation.address, allocation.size);
this->codePageAllocators->ReleaseDecommitted(allocation.address, allocation.GetPageCount(), allocation.largeObjectAllocation.segment);
largeObjectIter.RemoveCurrent(this->auxiliaryAllocator);
}
NEXT_DLISTBASE_ENTRY_EDITING;
}
//Called during Free (while shutting down)
template<typename TAlloc, typename TPreReservedAlloc>
DWORD Heap<TAlloc, TPreReservedAlloc>::EnsurePageWriteable(Page* page)
{
return EnsurePageReadWrite<PAGE_READWRITE>(page);
}
// this get called when freeing the whole page
template<typename TAlloc, typename TPreReservedAlloc>
DWORD Heap<TAlloc, TPreReservedAlloc>::EnsureAllocationWriteable(Allocation* allocation)
{
return EnsureAllocationReadWrite<PAGE_READWRITE>(allocation);
}
// this get called when only freeing a part in the page
template<typename TAlloc, typename TPreReservedAlloc>
DWORD Heap<TAlloc, TPreReservedAlloc>::EnsureAllocationExecuteWriteable(Allocation* allocation)
{
if (GlobalSecurityPolicy::IsCFGEnabled())
{
return EnsureAllocationReadWrite<PAGE_EXECUTE_RW_TARGETS_NO_UPDATE>(allocation);
}
else
{
return EnsureAllocationReadWrite<PAGE_EXECUTE_READWRITE>(allocation);
}
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeLargeObjects()
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
FOREACH_DLISTBASE_ENTRY_EDITING(Allocation, allocation, &this->largeObjectAllocations, largeObjectIter)
{
EnsureAllocationWriteable(&allocation);
#if PDATA_ENABLED
Assert(allocation.xdata.IsFreed());
#endif
this->codePageAllocators->Release(allocation.address, allocation.GetPageCount(), allocation.largeObjectAllocation.segment);
largeObjectIter.RemoveCurrent(this->auxiliaryAllocator);
}
NEXT_DLISTBASE_ENTRY_EDITING;
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeLargeObject(Allocation* allocation)
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
EnsureAllocationWriteable(allocation);
#if PDATA_ENABLED
Assert(allocation->xdata.IsFreed());
#endif
this->codePageAllocators->Release(allocation->address, allocation->GetPageCount(), allocation->largeObjectAllocation.segment);
this->largeObjectAllocations.RemoveElement(this->auxiliaryAllocator, allocation);
}
#pragma endregion
#pragma region "Page methods"
template<typename TAlloc, typename TPreReservedAlloc>
bool Heap<TAlloc, TPreReservedAlloc>::AllocInPage(Page* page, size_t bytes, ushort pdataCount, ushort xdataSize, Allocation ** allocationOut)
{
Allocation * allocation = AnewNoThrowStruct(this->auxiliaryAllocator, Allocation);
if (allocation == nullptr)
{
return true;
}
Assert(Math::IsPow2((int32)bytes));
uint length = GetChunkSizeForBytes(bytes);
BVIndex index = GetFreeIndexForPage(page, bytes);
if (index == BVInvalidIndex)
{
CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
return false;
}
char* address = page->address + Page::Alignment * index;
#if PDATA_ENABLED
XDataAllocation xdata;
if(pdataCount > 0)
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
if (this->ShouldBeInFullList(page))
{
Adelete(this->auxiliaryAllocator, allocation);
// If we run out of XData space with the segment, move the page to the full page list, and return false to try the next page.
BucketId bucket = page->currentBucket;
VerboseHeapTrace(_u("Moving page from bucket %d to full list\n"), bucket);
Assert(!page->inFullList);
this->buckets[bucket].MoveElementTo(page, &this->fullPages[bucket]);
page->inFullList = true;
return false;
}
if (!this->codePageAllocators->AllocSecondary(page->segment, (ULONG_PTR)address, bytes, pdataCount, xdataSize, &xdata))
{
Adelete(this->auxiliaryAllocator, allocation);
return true;
}
}
#endif
#if DBG
allocation->isAllocationUsed = false;
allocation->isNotExecutableBecauseOOM = false;
#endif
allocation->page = page;
allocation->size = bytes;
allocation->address = address;
allocation->thunkAddress = 0;
#if DBG_DUMP
this->allocationsSinceLastCompact += bytes;
this->freeObjectSize -= bytes;
#endif
//Section of the Page should already be freed.
if (!page->freeBitVector.TestRange(index, length))
{
CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
return false;
}
//Section of the Page should already be freed.
if (!page->freeBitVector.TestRange(index, length))
{
CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
return false;
}
page->freeBitVector.ClearRange(index, length);
VerboseHeapTrace(_u("ChunkSize: %d, Index: %d, Free bit vector in page: "), length, index);
#if VERBOSE_HEAP
page->freeBitVector.DumpWord();
#endif
VerboseHeapTrace(_u("\n"));
if (this->ShouldBeInFullList(page))
{
BucketId bucket = page->currentBucket;
VerboseHeapTrace(_u("Moving page from bucket %d to full list\n"), bucket);
Assert(!page->inFullList);
this->buckets[bucket].MoveElementTo(page, &this->fullPages[bucket]);
page->inFullList = true;
}
#if PDATA_ENABLED
allocation->xdata = xdata;
#endif
*allocationOut = allocation;
return true;
}
template<typename TAlloc, typename TPreReservedAlloc>
Page* Heap<TAlloc, TPreReservedAlloc>::AllocNewPage(BucketId bucket, bool canAllocInPreReservedHeapPageSegment, bool isAnyJittedCode, _Inout_ bool* isAllJITCodeInPreReservedRegion)
{
void* pageSegment = nullptr;
char* address = nullptr;
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
address = this->codePageAllocators->AllocPages(1, &pageSegment, canAllocInPreReservedHeapPageSegment, isAnyJittedCode, isAllJITCodeInPreReservedRegion);
if (address == nullptr)
{
return nullptr;
}
}
char* localAddr = this->codePageAllocators->AllocLocal(address, AutoSystemInfo::PageSize, pageSegment);
if (!localAddr)
{
return nullptr;
}
FillDebugBreak((BYTE*)localAddr, AutoSystemInfo::PageSize);
this->codePageAllocators->FreeLocal(localAddr, pageSegment);
DWORD protectFlags = 0;
if (GlobalSecurityPolicy::IsCFGEnabled())
{
protectFlags = PAGE_EXECUTE_RO_TARGETS_NO_UPDATE;
}
else
{
protectFlags = PAGE_EXECUTE_READ;
}
//Change the protection of the page to Read-Only Execute, before adding it to the bucket list.
this->codePageAllocators->ProtectPages(address, 1, pageSegment, protectFlags, PAGE_READWRITE);
// Switch to allocating on a list of pages so we can do leak tracking later
VerboseHeapTrace(_u("Allocing new page in bucket %d\n"), bucket);
Page* page = this->buckets[bucket].PrependNode(this->auxiliaryAllocator, address, pageSegment, bucket);
if (page == nullptr)
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
this->codePageAllocators->ReleasePages(address, 1, pageSegment);
return nullptr;
}
#if DBG_DUMP
this->totalAllocationSize += AutoSystemInfo::PageSize;
this->freeObjectSize += AutoSystemInfo::PageSize;
#endif
return page;
}
template<typename TAlloc, typename TPreReservedAlloc>
Page* Heap<TAlloc, TPreReservedAlloc>::AddPageToBucket(Page* page, BucketId bucket, bool wasFull)
{
Assert(bucket > BucketId::InvalidBucket && bucket < BucketId::NumBuckets);
BucketId oldBucket = page->currentBucket;
page->currentBucket = bucket;
if (wasFull)
{
#pragma prefast(suppress: __WARNING_UNCHECKED_LOWER_BOUND_FOR_ENUMINDEX, "targetBucket is always in range >= SmallObjectList, but an __in_range doesn't fix the warning.");
Assert(page->inFullList);
this->fullPages[oldBucket].MoveElementTo(page, &this->buckets[bucket]);
page->inFullList = false;
}
else
{
Assert(!page->inFullList);
#pragma prefast(suppress: __WARNING_UNCHECKED_LOWER_BOUND_FOR_ENUMINDEX, "targetBucket is always in range >= SmallObjectList, but an __in_range doesn't fix the warning.");
this->buckets[oldBucket].MoveElementTo(page, &this->buckets[bucket]);
}
return page;
}
/*
* This method goes through the buckets greater than the target bucket
* and if the higher bucket has a page with enough free space to allocate
* something in the smaller bucket, then we bring the page to the smaller
* bucket.
* Note that if we allocate something from a page in the given bucket,
* and then that page is split into a lower bucket, freeing is still not
* a problem since the larger allocation is a multiple of the smaller one.
* This gets more complicated if we can coalesce buckets. In that case,
* we need to make sure that if a page was coalesced, and an allocation
* pre-coalescing was freed, the page would need to get split upon free
* to ensure correctness. For now, we've skipped implementing coalescing.
* findPreReservedHeapPages - true, if we need to find pages only belonging to PreReservedHeapSegment
*/
template<typename TAlloc, typename TPreReservedAlloc>
Page* Heap<TAlloc, TPreReservedAlloc>::FindPageToSplit(BucketId targetBucket, bool findPreReservedHeapPages)
{
for (BucketId b = (BucketId)(targetBucket + 1); b < BucketId::NumBuckets; b = (BucketId) (b + 1))
{
#pragma prefast(suppress: __WARNING_UNCHECKED_LOWER_BOUND_FOR_ENUMINDEX, "targetBucket is always in range >= SmallObjectList, but an __in_range doesn't fix the warning.");
FOREACH_DLISTBASE_ENTRY_EDITING(Page, pageInBucket, &this->buckets[b], bucketIter)
{
Assert(!pageInBucket.inFullList);
if (findPreReservedHeapPages && !this->codePageAllocators->IsPreReservedSegment(pageInBucket.segment))
{
//Find only pages that are pre-reserved using preReservedHeapPageAllocator
continue;
}
if (pageInBucket.CanAllocate(targetBucket))
{
Page* page = &pageInBucket;
if (findPreReservedHeapPages)
{
VerboseHeapTrace(_u("PRE-RESERVE: Found page for splitting in Pre Reserved Segment\n"));
}
VerboseHeapTrace(_u("Found page to split. Moving from bucket %d to %d\n"), b, targetBucket);
return AddPageToBucket(page, targetBucket);
}
}
NEXT_DLISTBASE_ENTRY_EDITING;
}
return nullptr;
}
template<typename TAlloc, typename TPreReservedAlloc>
BVIndex Heap<TAlloc, TPreReservedAlloc>::GetIndexInPage(_In_ Page* page, _In_ char* address)
{
Assert(page->address <= address && address < page->address + AutoSystemInfo::PageSize);
return (BVIndex) ((address - page->address) / Page::Alignment);
}
#pragma endregion
/**
* Free List methods
*/
#pragma region "Freeing methods"
template<typename TAlloc, typename TPreReservedAlloc>
bool Heap<TAlloc, TPreReservedAlloc>::FreeAllocation(Allocation* object)
{
Page* page = object->page;
void* segment = page->segment;
size_t pageSize = AutoSystemInfo::PageSize;
unsigned int length = GetChunkSizeForBytes(object->size);
BVIndex index = GetIndexInPage(page, object->address);
uint freeBitsCount = page->freeBitVector.Count();
// Make sure that the section under interest or the whole page has not already been freed
if (page->IsEmpty() || page->freeBitVector.TestAnyInRange(index, length))
{
CustomHeap_BadPageState_unrecoverable_error((ULONG_PTR)this);
return false;
}
if (page->inFullList)
{
VerboseHeapTrace(_u("Recycling page 0x%p because address 0x%p of size %d was freed\n"), page->address, object->address, object->size);
// If the object being freed is equal to the page size, we're
// going to remove it anyway so don't add it to a bucket
if (object->size != pageSize)
{
AddPageToBucket(page, page->currentBucket, true);
}
else
{
EnsureAllocationWriteable(object);
// Fill the old buffer with debug breaks
char* localAddr = this->codePageAllocators->AllocLocal(object->address, object->size, page->segment);
if (!localAddr)
{
MemoryOperationLastError::RecordError(JSERR_FatalMemoryExhaustion);
return false;
}
FillDebugBreak((BYTE*)localAddr, object->size);
this->codePageAllocators->FreeLocal(localAddr, page->segment);
void* pageAddress = page->address;
this->fullPages[page->currentBucket].RemoveElement(this->auxiliaryAllocator, page);
// The page is not in any bucket- just update the stats, free the allocation
// and dump the page- we don't need to update free object size since the object
// size is equal to the page size so they cancel each other out
#if DBG_DUMP
this->totalAllocationSize -= pageSize;
#endif
this->auxiliaryAllocator->Free(object, sizeof(Allocation));
{
AutoCriticalSection autoLock(&this->codePageAllocators->cs);
this->codePageAllocators->ReleasePages(pageAddress, 1, segment);
}
VerboseHeapTrace(_u("FastPath: freeing page-sized object directly\n"));
return true;
}
}
// If the page is about to become empty then we should not need
// to set it to executable and we don't expect to restore the
// previous protection settings.
if (freeBitsCount == BVUnit::BitsPerWord - length)
{
EnsureAllocationWriteable(object);
FreeAllocationHelper(object, index, length);
Assert(page->IsEmpty());
this->buckets[page->currentBucket].RemoveElement(this->auxiliaryAllocator, page);
return false;
}
else
{
EnsureAllocationExecuteWriteable(object);
FreeAllocationHelper(object, index, length);
// after freeing part of the page, the page should be in PAGE_EXECUTE_READWRITE protection, and turning to PAGE_EXECUTE_READ (always with TARGETS_NO_UPDATE state)
DWORD protectFlags = 0;
if (GlobalSecurityPolicy::IsCFGEnabled())
{
protectFlags = PAGE_EXECUTE_RO_TARGETS_NO_UPDATE;
}
else
{
protectFlags = PAGE_EXECUTE_READ;
}
this->codePageAllocators->ProtectPages(page->address, 1, segment, protectFlags, PAGE_EXECUTE_READWRITE);
return true;
}
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeAllocationHelper(Allocation* object, BVIndex index, uint length)
{
Page* page = object->page;
// Fill the old buffer with debug breaks
char* localAddr = this->codePageAllocators->AllocLocal(object->address, object->size, page->segment);
if (localAddr)
{
FillDebugBreak((BYTE*)localAddr, object->size);
this->codePageAllocators->FreeLocal(localAddr, page->segment);
}
else
{
MemoryOperationLastError::RecordError(JSERR_FatalMemoryExhaustion);
return;
}
VerboseHeapTrace(_u("Setting %d bits starting at bit %d, Free bit vector in page was "), length, index);
#if VERBOSE_HEAP
page->freeBitVector.DumpWord();
#endif
VerboseHeapTrace(_u("\n"));
page->freeBitVector.SetRange(index, length);
VerboseHeapTrace(_u("Free bit vector in page: "), length, index);
#if VERBOSE_HEAP
page->freeBitVector.DumpWord();
#endif
VerboseHeapTrace(_u("\n"));
#if DBG_DUMP
this->freeObjectSize += object->size;
this->freesSinceLastCompact += object->size;
#endif
this->auxiliaryAllocator->Free(object, sizeof(Allocation));
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeDecommittedBuckets()
{
// CodePageAllocators is locked in FreeAll
Assert(inDtor);
FOREACH_DLISTBASE_ENTRY_EDITING(Page, page, &this->decommittedPages, iter)
{
this->codePageAllocators->TrackDecommittedPages(page.address, 1, page.segment);
iter.RemoveCurrent(this->auxiliaryAllocator);
}
NEXT_DLISTBASE_ENTRY_EDITING;
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreePage(Page* page)
{
// CodePageAllocators is locked in FreeAll
Assert(inDtor);
DWORD pageSize = AutoSystemInfo::PageSize;
EnsurePageWriteable(page);
size_t freeSpace = page->freeBitVector.Count() * Page::Alignment;
VerboseHeapTrace(_u("Removing page in bucket %d, freeSpace: %d\n"), page->currentBucket, freeSpace);
this->codePageAllocators->ReleasePages(page->address, 1, page->segment);
#if DBG_DUMP
this->freeObjectSize -= freeSpace;
this->totalAllocationSize -= pageSize;
#endif
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeBucket(DListBase<Page>* bucket, bool freeOnlyEmptyPages)
{
// CodePageAllocators is locked in FreeAll
Assert(inDtor);
FOREACH_DLISTBASE_ENTRY_EDITING(Page, page, bucket, pageIter)
{
// Templatize this to remove branches/make code more compact?
if (!freeOnlyEmptyPages || page.IsEmpty())
{
FreePage(&page);
pageIter.RemoveCurrent(this->auxiliaryAllocator);
}
}
NEXT_DLISTBASE_ENTRY_EDITING;
}
template<typename TAlloc, typename TPreReservedAlloc>
void Heap<TAlloc, TPreReservedAlloc>::FreeBuckets(bool freeOnlyEmptyPages)