forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapPage.cpp
1850 lines (1681 loc) · 67.3 KB
/
HeapPage.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
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "platform/heap/HeapPage.h"
#include "base/trace_event/process_memory_dump.h"
#include "platform/MemoryCoordinator.h"
#include "platform/ScriptForbiddenScope.h"
#include "platform/heap/BlinkGCMemoryDumpProvider.h"
#include "platform/heap/CallbackStack.h"
#include "platform/heap/HeapCompact.h"
#include "platform/heap/PageMemory.h"
#include "platform/heap/PagePool.h"
#include "platform/heap/SafePoint.h"
#include "platform/heap/ThreadState.h"
#include "platform/instrumentation/tracing/TraceEvent.h"
#include "platform/instrumentation/tracing/web_memory_allocator_dump.h"
#include "platform/instrumentation/tracing/web_process_memory_dump.h"
#include "platform/wtf/Assertions.h"
#include "platform/wtf/AutoReset.h"
#include "platform/wtf/ContainerAnnotations.h"
#include "platform/wtf/CurrentTime.h"
#include "platform/wtf/LeakAnnotations.h"
#include "platform/wtf/allocator/Partitions.h"
#include "public/platform/Platform.h"
#ifdef ANNOTATE_CONTIGUOUS_CONTAINER
// When finalizing a non-inlined vector backing store/container, remove
// its contiguous container annotation. Required as it will not be destructed
// from its Vector.
#define ASAN_RETIRE_CONTAINER_ANNOTATION(object, objectSize) \
do { \
BasePage* page = PageFromObject(object); \
DCHECK(page); \
bool is_container = \
ThreadState::IsVectorArenaIndex(page->Arena()->ArenaIndex()); \
if (!is_container && page->IsLargeObjectPage()) \
is_container = \
static_cast<LargeObjectPage*>(page)->IsVectorBackingPage(); \
if (is_container) \
ANNOTATE_DELETE_BUFFER(object, objectSize, 0); \
} while (0)
// A vector backing store represented by a large object is marked
// so that when it is finalized, its ASan annotation will be
// correctly retired.
#define ASAN_MARK_LARGE_VECTOR_CONTAINER(arena, large_object) \
if (ThreadState::IsVectorArenaIndex(arena->ArenaIndex())) { \
BasePage* large_page = PageFromObject(large_object); \
DCHECK(large_page->IsLargeObjectPage()); \
static_cast<LargeObjectPage*>(large_page)->SetIsVectorBackingPage(); \
}
#else
#define ASAN_RETIRE_CONTAINER_ANNOTATION(payload, payloadSize)
#define ASAN_MARK_LARGE_VECTOR_CONTAINER(arena, largeObject)
#endif
namespace blink {
#if DCHECK_IS_ON() && defined(ARCH_CPU_64_BITS)
NO_SANITIZE_ADDRESS
void HeapObjectHeader::ZapMagic() {
CheckHeader();
magic_ = kZappedMagic;
}
#endif
void HeapObjectHeader::Finalize(Address object, size_t object_size) {
HeapAllocHooks::FreeHookIfEnabled(object);
const GCInfo* gc_info = ThreadHeap::GcInfo(GcInfoIndex());
if (gc_info->HasFinalizer())
gc_info->finalize_(object);
ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size);
}
BaseArena::BaseArena(ThreadState* state, int index)
: first_page_(nullptr),
first_unswept_page_(nullptr),
thread_state_(state),
index_(index) {}
BaseArena::~BaseArena() {
DCHECK(!first_page_);
DCHECK(!first_unswept_page_);
}
void BaseArena::RemoveAllPages() {
ClearFreeLists();
DCHECK(!first_unswept_page_);
while (first_page_) {
BasePage* page = first_page_;
page->Unlink(&first_page_);
page->RemoveFromHeap();
}
}
void BaseArena::TakeSnapshot(const String& dump_base_name,
ThreadState::GCSnapshotInfo& info) {
// |dumpBaseName| at this point is "blink_gc/thread_X/heaps/HeapName"
base::trace_event::MemoryAllocatorDump* allocator_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(dump_base_name);
size_t page_count = 0;
BasePage::HeapSnapshotInfo heap_info;
for (BasePage* page = first_unswept_page_; page; page = page->Next()) {
String dump_name = dump_base_name +
String::Format("/pages/page_%lu",
static_cast<unsigned long>(page_count++));
base::trace_event::MemoryAllocatorDump* page_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(dump_name);
page->TakeSnapshot(page_dump, info, heap_info);
}
allocator_dump->AddScalar("blink_page_count", "objects", page_count);
// When taking a full dump (w/ freelist), both the /buckets and /pages
// report their free size but they are not meant to be added together.
// Therefore, here we override the free_size of the parent heap to be
// equal to the free_size of the sum of its heap pages.
allocator_dump->AddScalar("free_size", "bytes", heap_info.free_size);
allocator_dump->AddScalar("free_count", "objects", heap_info.free_count);
}
#if DCHECK_IS_ON()
BasePage* BaseArena::FindPageFromAddress(Address address) {
for (BasePage* page = first_page_; page; page = page->Next()) {
if (page->Contains(address))
return page;
}
for (BasePage* page = first_unswept_page_; page; page = page->Next()) {
if (page->Contains(address))
return page;
}
return nullptr;
}
#endif
void BaseArena::MakeConsistentForGC() {
ClearFreeLists();
#if DCHECK_IS_ON()
DCHECK(IsConsistentForGC());
#endif
for (BasePage* page = first_page_; page; page = page->Next()) {
page->MarkAsUnswept();
page->InvalidateObjectStartBitmap();
}
// We should not start a new GC until we finish sweeping in the current GC.
CHECK(!first_unswept_page_);
HeapCompact* heap_compactor = GetThreadState()->Heap().Compaction();
if (!heap_compactor->IsCompactingArena(ArenaIndex()))
return;
BasePage* next_page = first_page_;
while (next_page) {
if (!next_page->IsLargeObjectPage())
heap_compactor->AddCompactingPage(next_page);
next_page = next_page->Next();
}
}
void BaseArena::MakeConsistentForMutator() {
ClearFreeLists();
#if DCHECK_IS_ON()
DCHECK(IsConsistentForGC());
#endif
DCHECK(!first_page_);
// Drop marks from marked objects and rebuild free lists in preparation for
// resuming the executions of mutators.
BasePage* previous_page = nullptr;
for (BasePage *page = first_unswept_page_; page;
previous_page = page, page = page->Next()) {
page->MakeConsistentForMutator();
page->MarkAsSwept();
page->InvalidateObjectStartBitmap();
}
if (previous_page) {
DCHECK(first_unswept_page_);
previous_page->next_ = first_page_;
first_page_ = first_unswept_page_;
first_unswept_page_ = nullptr;
}
DCHECK(!first_unswept_page_);
}
size_t BaseArena::ObjectPayloadSizeForTesting() {
#if DCHECK_IS_ON()
DCHECK(IsConsistentForGC());
#endif
DCHECK(!first_unswept_page_);
size_t object_payload_size = 0;
for (BasePage* page = first_page_; page; page = page->Next())
object_payload_size += page->ObjectPayloadSizeForTesting();
return object_payload_size;
}
void BaseArena::PrepareForSweep() {
DCHECK(GetThreadState()->IsInGC());
DCHECK(!first_unswept_page_);
// Move all pages to a list of unswept pages.
first_unswept_page_ = first_page_;
first_page_ = nullptr;
}
#if defined(ADDRESS_SANITIZER)
void BaseArena::PoisonArena() {
for (BasePage* page = first_unswept_page_; page; page = page->Next())
page->PoisonUnmarkedObjects();
}
#endif
Address BaseArena::LazySweep(size_t allocation_size, size_t gc_info_index) {
// If there are no pages to be swept, return immediately.
if (!first_unswept_page_)
return nullptr;
CHECK(GetThreadState()->IsSweepingInProgress());
// lazySweepPages() can be called recursively if finalizers invoked in
// page->sweep() allocate memory and the allocation triggers
// lazySweepPages(). This check prevents the sweeping from being executed
// recursively.
if (GetThreadState()->SweepForbidden())
return nullptr;
TRACE_EVENT0("blink_gc", "BaseArena::lazySweepPages");
ThreadState::SweepForbiddenScope sweep_forbidden(GetThreadState());
ScriptForbiddenIfMainThreadScope script_forbidden;
double start_time = WTF::CurrentTimeMS();
Address result = LazySweepPages(allocation_size, gc_info_index);
GetThreadState()->AccumulateSweepingTime(WTF::CurrentTimeMS() - start_time);
ThreadHeap::ReportMemoryUsageForTracing();
return result;
}
void BaseArena::SweepUnsweptPage() {
BasePage* page = first_unswept_page_;
if (page->IsEmpty()) {
page->Unlink(&first_unswept_page_);
page->RemoveFromHeap();
} else {
// Sweep a page and move the page from m_firstUnsweptPages to
// m_firstPages.
page->Sweep();
page->Unlink(&first_unswept_page_);
page->Link(&first_page_);
page->MarkAsSwept();
}
}
bool BaseArena::LazySweepWithDeadline(double deadline_seconds) {
// It might be heavy to call
// Platform::current()->monotonicallyIncreasingTimeSeconds() per page (i.e.,
// 128 KB sweep or one LargeObject sweep), so we check the deadline per 10
// pages.
static const int kDeadlineCheckInterval = 10;
CHECK(GetThreadState()->IsSweepingInProgress());
DCHECK(GetThreadState()->SweepForbidden());
DCHECK(!GetThreadState()->IsMainThread() ||
ScriptForbiddenScope::IsScriptForbidden());
NormalPageArena* normal_arena = nullptr;
if (first_unswept_page_ && !first_unswept_page_->IsLargeObjectPage()) {
// Mark this NormalPageArena as being lazily swept.
NormalPage* normal_page =
reinterpret_cast<NormalPage*>(first_unswept_page_);
normal_arena = normal_page->ArenaForNormalPage();
normal_arena->SetIsLazySweeping(true);
}
int page_count = 1;
while (first_unswept_page_) {
SweepUnsweptPage();
if (page_count % kDeadlineCheckInterval == 0) {
if (deadline_seconds <= MonotonicallyIncreasingTime()) {
// Deadline has come.
ThreadHeap::ReportMemoryUsageForTracing();
if (normal_arena)
normal_arena->SetIsLazySweeping(false);
return !first_unswept_page_;
}
}
page_count++;
}
ThreadHeap::ReportMemoryUsageForTracing();
if (normal_arena)
normal_arena->SetIsLazySweeping(false);
return true;
}
void BaseArena::CompleteSweep() {
CHECK(GetThreadState()->IsSweepingInProgress());
DCHECK(GetThreadState()->SweepForbidden());
DCHECK(!GetThreadState()->IsMainThread() ||
ScriptForbiddenScope::IsScriptForbidden());
while (first_unswept_page_) {
SweepUnsweptPage();
}
ThreadHeap::ReportMemoryUsageForTracing();
}
Address BaseArena::AllocateLargeObject(size_t allocation_size,
size_t gc_info_index) {
// TODO(sof): should need arise, support eagerly finalized large objects.
CHECK(ArenaIndex() != BlinkGC::kEagerSweepArenaIndex);
LargeObjectArena* large_object_arena = static_cast<LargeObjectArena*>(
GetThreadState()->Arena(BlinkGC::kLargeObjectArenaIndex));
Address large_object = large_object_arena->AllocateLargeObjectPage(
allocation_size, gc_info_index);
ASAN_MARK_LARGE_VECTOR_CONTAINER(this, large_object);
return large_object;
}
bool BaseArena::WillObjectBeLazilySwept(BasePage* page,
void* object_pointer) const {
// If not on the current page being (potentially) lazily swept,
// |objectPointer| is an unmarked, sweepable object.
if (page != first_unswept_page_)
return true;
DCHECK(!page->IsLargeObjectPage());
// Check if the arena is currently being lazily swept.
NormalPage* normal_page = reinterpret_cast<NormalPage*>(page);
NormalPageArena* normal_arena = normal_page->ArenaForNormalPage();
if (!normal_arena->IsLazySweeping())
return true;
// Rare special case: unmarked object is on the page being lazily swept,
// and a finalizer for an object on that page calls
// ThreadHeap::willObjectBeLazilySwept().
//
// Need to determine if |objectPointer| represents a live (unmarked) object or
// an unmarked object that will be lazily swept later. As lazy page sweeping
// doesn't record a frontier pointer representing how far along it is, the
// page is scanned from the start, skipping past freed & unmarked regions.
//
// If no marked objects are encountered before |objectPointer|, we know that
// the finalizing object calling willObjectBeLazilySwept() comes later, and
// |objectPointer| has been deemed to be alive already (=> it won't be swept.)
//
// If a marked object is encountered before |objectPointer|, it will
// not have been lazily swept past already. Hence it represents an unmarked,
// sweepable object.
//
// As willObjectBeLazilySwept() is used rarely and it happening to be
// used while runnning a finalizer on the page being lazily swept is
// even rarer, the page scan is considered acceptable and something
// really wanted -- willObjectBeLazilySwept()'s result can be trusted.
Address page_end = normal_page->PayloadEnd();
for (Address header_address = normal_page->Payload();
header_address < page_end;) {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(header_address);
size_t size = header->size();
// Scan made it to |objectPointer| without encountering any marked objects.
// => lazy sweep will have processed this unmarked, but live, object.
// => |objectPointer| will not be lazily swept.
//
// Notice that |objectPointer| might be pointer to a GarbageCollectedMixin,
// hence using fromPayload() to derive the HeapObjectHeader isn't possible
// (and use its value to check if |headerAddress| is equal to it.)
if (header_address > object_pointer)
return false;
if (!header->IsFree() && header->IsMarked()) {
// There must be a marked object on this page and the one located must
// have room after it for the unmarked |objectPointer| object.
DCHECK(header_address + size < page_end);
return true;
}
header_address += size;
}
NOTREACHED();
return true;
}
NormalPageArena::NormalPageArena(ThreadState* state, int index)
: BaseArena(state, index),
current_allocation_point_(nullptr),
remaining_allocation_size_(0),
last_remaining_allocation_size_(0),
promptly_freed_size_(0),
is_lazy_sweeping_(false) {
ClearFreeLists();
}
void NormalPageArena::ClearFreeLists() {
SetAllocationPoint(nullptr, 0);
free_list_.Clear();
}
size_t NormalPageArena::ArenaSize() {
size_t size = 0;
BasePage* page = first_page_;
while (page) {
size += page->size();
page = page->Next();
}
LOG_HEAP_FREELIST_VERBOSE("Heap size: %zu (%d)\n", size, arenaIndex());
return size;
}
size_t NormalPageArena::FreeListSize() {
size_t free_size = free_list_.FreeListSize();
LOG_HEAP_FREELIST_VERBOSE("Free size: %zu (%d)\n", freeSize, arenaIndex());
return free_size;
}
void NormalPageArena::SweepAndCompact() {
ThreadHeap& heap = GetThreadState()->Heap();
if (!heap.Compaction()->IsCompactingArena(ArenaIndex()))
return;
if (!first_unswept_page_) {
heap.Compaction()->FinishedArenaCompaction(this, 0, 0);
return;
}
// Compaction is performed in-place, sliding objects down over unused
// holes for a smaller heap page footprint and improved locality.
// A "compaction pointer" is consequently kept, pointing to the next
// available address to move objects down to. It will belong to one
// of the already sweep-compacted pages for this arena, but as compaction
// proceeds, it will not belong to the same page as the one being
// currently compacted.
//
// The compaction pointer is represented by the
// |(currentPage, allocationPoint)| pair, with |allocationPoint|
// being the offset into |currentPage|, making up the next
// available location. When the compaction of an arena page causes the
// compaction pointer to exhaust the current page it is compacting into,
// page compaction will advance the current page of the compaction
// pointer, as well as the allocation point.
//
// By construction, the page compaction can be performed without having
// to allocate any new pages. So to arrange for the page compaction's
// supply of freed, available pages, we chain them together after each
// has been "compacted from". The page compaction will then reuse those
// as needed, and once finished, the chained, available pages can be
// released back to the OS.
//
// To ease the passing of the compaction state when iterating over an
// arena's pages, package it up into a |CompactionContext|.
NormalPage::CompactionContext context;
context.compacted_pages_ = &first_page_;
while (first_unswept_page_) {
BasePage* page = first_unswept_page_;
if (page->IsEmpty()) {
page->Unlink(&first_unswept_page_);
page->RemoveFromHeap();
continue;
}
// Large objects do not belong to this arena.
DCHECK(!page->IsLargeObjectPage());
NormalPage* normal_page = static_cast<NormalPage*>(page);
normal_page->Unlink(&first_unswept_page_);
normal_page->MarkAsSwept();
// If not the first page, add |normalPage| onto the available pages chain.
if (!context.current_page_)
context.current_page_ = normal_page;
else
normal_page->Link(&context.available_pages_);
normal_page->SweepAndCompact(context);
}
// All pages were empty; nothing to compact.
if (!context.current_page_) {
heap.Compaction()->FinishedArenaCompaction(this, 0, 0);
return;
}
size_t freed_size = 0;
size_t freed_page_count = 0;
// If the current page hasn't been allocated into, add it to the available
// list, for subsequent release below.
size_t allocation_point = context.allocation_point_;
if (!allocation_point) {
context.current_page_->Link(&context.available_pages_);
} else {
NormalPage* current_page = context.current_page_;
current_page->Link(&first_page_);
if (allocation_point != current_page->PayloadSize()) {
// Put the remainder of the page onto the free list.
freed_size = current_page->PayloadSize() - allocation_point;
Address payload = current_page->Payload();
SET_MEMORY_INACCESSIBLE(payload + allocation_point, freed_size);
current_page->ArenaForNormalPage()->AddToFreeList(
payload + allocation_point, freed_size);
}
}
// Return available pages to the free page pool, decommitting them from
// the pagefile.
BasePage* available_pages = context.available_pages_;
while (available_pages) {
size_t page_size = available_pages->size();
#if DEBUG_HEAP_COMPACTION
if (!freed_page_count)
LOG_HEAP_COMPACTION("Releasing:");
LOG_HEAP_COMPACTION(" [%p, %p]", available_pages,
available_pages + page_size);
#endif
freed_size += page_size;
freed_page_count++;
BasePage* next_page;
available_pages->Unlink(&next_page);
#if !(DCHECK_IS_ON() || defined(LEAK_SANITIZER) || \
defined(ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER))
// Clear out the page before adding it to the free page pool, which
// decommits it. Recommitting the page must find a zeroed page later.
// We cannot assume that the OS will hand back a zeroed page across
// its "decommit" operation.
//
// If in a debug setting, the unused page contents will have been
// zapped already; leave it in that state.
DCHECK(!available_pages->IsLargeObjectPage());
NormalPage* unused_page = reinterpret_cast<NormalPage*>(available_pages);
memset(unused_page->Payload(), 0, unused_page->PayloadSize());
#endif
available_pages->RemoveFromHeap();
available_pages = static_cast<NormalPage*>(next_page);
}
if (freed_page_count)
LOG_HEAP_COMPACTION("\n");
heap.Compaction()->FinishedArenaCompaction(this, freed_page_count,
freed_size);
}
#if DCHECK_IS_ON()
bool NormalPageArena::IsConsistentForGC() {
// A thread heap is consistent for sweeping if none of the pages to be swept
// contain a freelist block or the current allocation point.
for (size_t i = 0; i < kBlinkPageSizeLog2; ++i) {
for (FreeListEntry* free_list_entry = free_list_.free_lists_[i];
free_list_entry; free_list_entry = free_list_entry->Next()) {
if (PagesToBeSweptContains(free_list_entry->GetAddress()))
return false;
}
}
if (HasCurrentAllocationArea()) {
if (PagesToBeSweptContains(CurrentAllocationPoint()))
return false;
}
return true;
}
bool NormalPageArena::PagesToBeSweptContains(Address address) {
for (BasePage* page = first_unswept_page_; page; page = page->Next()) {
if (page->Contains(address))
return true;
}
return false;
}
#endif
void NormalPageArena::TakeFreelistSnapshot(const String& dump_name) {
if (free_list_.TakeSnapshot(dump_name)) {
base::trace_event::MemoryAllocatorDump* buckets_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(dump_name + "/buckets");
base::trace_event::MemoryAllocatorDump* pages_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(dump_name + "/pages");
BlinkGCMemoryDumpProvider::Instance()
->CurrentProcessMemoryDump()
->AddOwnershipEdge(pages_dump->guid(), buckets_dump->guid());
}
}
void NormalPageArena::AllocatePage() {
GetThreadState()->ShouldFlushHeapDoesNotContainCache();
PageMemory* page_memory =
GetThreadState()->Heap().GetFreePagePool()->Take(ArenaIndex());
if (!page_memory) {
// Allocate a memory region for blinkPagesPerRegion pages that
// will each have the following layout.
//
// [ guard os page | ... payload ... | guard os page ]
// ^---{ aligned to blink page size }
PageMemoryRegion* region = PageMemoryRegion::AllocateNormalPages(
GetThreadState()->Heap().GetRegionTree());
// Setup the PageMemory object for each of the pages in the region.
for (size_t i = 0; i < kBlinkPagesPerRegion; ++i) {
PageMemory* memory = PageMemory::SetupPageMemoryInRegion(
region, i * kBlinkPageSize, BlinkPagePayloadSize());
// Take the first possible page ensuring that this thread actually
// gets a page and add the rest to the page pool.
if (!page_memory) {
bool result = memory->Commit();
// If you hit the ASSERT, it will mean that you're hitting
// the limit of the number of mmapped regions OS can support
// (e.g., /proc/sys/vm/max_map_count in Linux).
CHECK(result);
page_memory = memory;
} else {
GetThreadState()->Heap().GetFreePagePool()->Add(ArenaIndex(), memory);
}
}
}
NormalPage* page =
new (page_memory->WritableStart()) NormalPage(page_memory, this);
page->Link(&first_page_);
GetThreadState()->Heap().HeapStats().IncreaseAllocatedSpace(page->size());
#if DCHECK_IS_ON() || defined(LEAK_SANITIZER) || defined(ADDRESS_SANITIZER)
// Allow the following addToFreeList() to add the newly allocated memory
// to the free list.
ASAN_UNPOISON_MEMORY_REGION(page->Payload(), page->PayloadSize());
Address address = page->Payload();
for (size_t i = 0; i < page->PayloadSize(); i++)
address[i] = kReuseAllowedZapValue;
ASAN_POISON_MEMORY_REGION(page->Payload(), page->PayloadSize());
#endif
AddToFreeList(page->Payload(), page->PayloadSize());
}
void NormalPageArena::FreePage(NormalPage* page) {
GetThreadState()->Heap().HeapStats().DecreaseAllocatedSpace(page->size());
PageMemory* memory = page->Storage();
page->~NormalPage();
GetThreadState()->Heap().GetFreePagePool()->Add(ArenaIndex(), memory);
}
bool NormalPageArena::Coalesce() {
// Don't coalesce arenas if there are not enough promptly freed entries
// to be coalesced.
//
// FIXME: This threshold is determined just to optimize blink_perf
// benchmarks. Coalescing is very sensitive to the threashold and
// we need further investigations on the coalescing scheme.
if (promptly_freed_size_ < 1024 * 1024)
return false;
if (GetThreadState()->SweepForbidden())
return false;
DCHECK(!HasCurrentAllocationArea());
TRACE_EVENT0("blink_gc", "BaseArena::coalesce");
// Rebuild free lists.
free_list_.Clear();
size_t freed_size = 0;
for (NormalPage* page = static_cast<NormalPage*>(first_page_); page;
page = static_cast<NormalPage*>(page->Next())) {
Address start_of_gap = page->Payload();
for (Address header_address = start_of_gap;
header_address < page->PayloadEnd();) {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(header_address);
size_t size = header->size();
DCHECK_GT(size, 0u);
DCHECK_LT(size, BlinkPagePayloadSize());
if (header->IsPromptlyFreed()) {
DCHECK_GE(size, sizeof(HeapObjectHeader));
// Zero the memory in the free list header to maintain the
// invariant that memory on the free list is zero filled.
// The rest of the memory is already on the free list and is
// therefore already zero filled.
SET_MEMORY_INACCESSIBLE(header_address, sizeof(HeapObjectHeader));
CHECK_MEMORY_INACCESSIBLE(header_address, size);
freed_size += size;
header_address += size;
continue;
}
if (header->IsFree()) {
// Zero the memory in the free list header to maintain the
// invariant that memory on the free list is zero filled.
// The rest of the memory is already on the free list and is
// therefore already zero filled.
SET_MEMORY_INACCESSIBLE(header_address, size < sizeof(FreeListEntry)
? size
: sizeof(FreeListEntry));
CHECK_MEMORY_INACCESSIBLE(header_address, size);
header_address += size;
continue;
}
if (start_of_gap != header_address)
AddToFreeList(start_of_gap, header_address - start_of_gap);
header_address += size;
start_of_gap = header_address;
}
if (start_of_gap != page->PayloadEnd())
AddToFreeList(start_of_gap, page->PayloadEnd() - start_of_gap);
}
GetThreadState()->DecreaseAllocatedObjectSize(freed_size);
DCHECK_EQ(promptly_freed_size_, freed_size);
promptly_freed_size_ = 0;
return true;
}
void NormalPageArena::PromptlyFreeObject(HeapObjectHeader* header) {
DCHECK(!GetThreadState()->SweepForbidden());
Address address = reinterpret_cast<Address>(header);
Address payload = header->Payload();
size_t size = header->size();
size_t payload_size = header->PayloadSize();
DCHECK_GT(size, 0u);
#if DCHECK_IS_ON()
DCHECK_EQ(PageFromObject(address), FindPageFromAddress(address));
#endif
{
ThreadState::SweepForbiddenScope forbidden_scope(GetThreadState());
header->Finalize(payload, payload_size);
if (address + size == current_allocation_point_) {
current_allocation_point_ = address;
SetRemainingAllocationSize(remaining_allocation_size_ + size);
SET_MEMORY_INACCESSIBLE(address, size);
return;
}
SET_MEMORY_INACCESSIBLE(payload, payload_size);
header->MarkPromptlyFreed();
}
promptly_freed_size_ += size;
}
bool NormalPageArena::ExpandObject(HeapObjectHeader* header, size_t new_size) {
// It's possible that Vector requests a smaller expanded size because
// Vector::shrinkCapacity can set a capacity smaller than the actual payload
// size.
if (header->PayloadSize() >= new_size)
return true;
size_t allocation_size = ThreadHeap::AllocationSizeFromSize(new_size);
DCHECK_GT(allocation_size, header->size());
size_t expand_size = allocation_size - header->size();
if (IsObjectAllocatedAtAllocationPoint(header) &&
expand_size <= remaining_allocation_size_) {
current_allocation_point_ += expand_size;
DCHECK_GE(remaining_allocation_size_, expand_size);
SetRemainingAllocationSize(remaining_allocation_size_ - expand_size);
// Unpoison the memory used for the object (payload).
SET_MEMORY_ACCESSIBLE(header->PayloadEnd(), expand_size);
header->SetSize(allocation_size);
#if DCHECK_IS_ON()
DCHECK(FindPageFromAddress(header->PayloadEnd() - 1));
#endif
return true;
}
return false;
}
bool NormalPageArena::ShrinkObject(HeapObjectHeader* header, size_t new_size) {
DCHECK_GT(header->PayloadSize(), new_size);
size_t allocation_size = ThreadHeap::AllocationSizeFromSize(new_size);
DCHECK_GT(header->size(), allocation_size);
size_t shrink_size = header->size() - allocation_size;
if (IsObjectAllocatedAtAllocationPoint(header)) {
current_allocation_point_ -= shrink_size;
SetRemainingAllocationSize(remaining_allocation_size_ + shrink_size);
SET_MEMORY_INACCESSIBLE(current_allocation_point_, shrink_size);
header->SetSize(allocation_size);
return true;
}
DCHECK_GE(shrink_size, sizeof(HeapObjectHeader));
DCHECK_GT(header->GcInfoIndex(), 0u);
Address shrink_address = header->PayloadEnd() - shrink_size;
HeapObjectHeader* freed_header = new (NotNull, shrink_address)
HeapObjectHeader(shrink_size, header->GcInfoIndex());
freed_header->MarkPromptlyFreed();
#if DCHECK_IS_ON()
DCHECK_EQ(PageFromObject(reinterpret_cast<Address>(header)),
FindPageFromAddress(reinterpret_cast<Address>(header)));
#endif
promptly_freed_size_ += shrink_size;
header->SetSize(allocation_size);
SET_MEMORY_INACCESSIBLE(shrink_address + sizeof(HeapObjectHeader),
shrink_size - sizeof(HeapObjectHeader));
return false;
}
Address NormalPageArena::LazySweepPages(size_t allocation_size,
size_t gc_info_index) {
DCHECK(!HasCurrentAllocationArea());
AutoReset<bool> is_lazy_sweeping(&is_lazy_sweeping_, true);
Address result = nullptr;
while (first_unswept_page_) {
BasePage* page = first_unswept_page_;
if (page->IsEmpty()) {
page->Unlink(&first_unswept_page_);
page->RemoveFromHeap();
} else {
// Sweep a page and move the page from m_firstUnsweptPages to
// m_firstPages.
page->Sweep();
page->Unlink(&first_unswept_page_);
page->Link(&first_page_);
page->MarkAsSwept();
// For NormalPage, stop lazy sweeping once we find a slot to
// allocate a new object.
result = AllocateFromFreeList(allocation_size, gc_info_index);
if (result)
break;
}
}
return result;
}
void NormalPageArena::SetRemainingAllocationSize(
size_t new_remaining_allocation_size) {
remaining_allocation_size_ = new_remaining_allocation_size;
// Sync recorded allocated-object size:
// - if previous alloc checkpoint is larger, allocation size has increased.
// - if smaller, a net reduction in size since last call to
// updateRemainingAllocationSize().
if (last_remaining_allocation_size_ > remaining_allocation_size_)
GetThreadState()->IncreaseAllocatedObjectSize(
last_remaining_allocation_size_ - remaining_allocation_size_);
else if (last_remaining_allocation_size_ != remaining_allocation_size_)
GetThreadState()->DecreaseAllocatedObjectSize(
remaining_allocation_size_ - last_remaining_allocation_size_);
last_remaining_allocation_size_ = remaining_allocation_size_;
}
void NormalPageArena::UpdateRemainingAllocationSize() {
if (last_remaining_allocation_size_ > RemainingAllocationSize()) {
GetThreadState()->IncreaseAllocatedObjectSize(
last_remaining_allocation_size_ - RemainingAllocationSize());
last_remaining_allocation_size_ = RemainingAllocationSize();
}
DCHECK_EQ(last_remaining_allocation_size_, RemainingAllocationSize());
}
void NormalPageArena::SetAllocationPoint(Address point, size_t size) {
#if DCHECK_IS_ON()
if (point) {
DCHECK(size);
BasePage* page = PageFromObject(point);
DCHECK(!page->IsLargeObjectPage());
DCHECK_LE(size, static_cast<NormalPage*>(page)->PayloadSize());
}
#endif
if (HasCurrentAllocationArea()) {
AddToFreeList(CurrentAllocationPoint(), RemainingAllocationSize());
}
UpdateRemainingAllocationSize();
current_allocation_point_ = point;
last_remaining_allocation_size_ = remaining_allocation_size_ = size;
}
Address NormalPageArena::OutOfLineAllocate(size_t allocation_size,
size_t gc_info_index) {
DCHECK_GT(allocation_size, RemainingAllocationSize());
DCHECK_GE(allocation_size, kAllocationGranularity);
// 1. If this allocation is big enough, allocate a large object.
if (allocation_size >= kLargeObjectSizeThreshold)
return AllocateLargeObject(allocation_size, gc_info_index);
// 2. Try to allocate from a free list.
UpdateRemainingAllocationSize();
Address result = AllocateFromFreeList(allocation_size, gc_info_index);
if (result)
return result;
// 3. Reset the allocation point.
SetAllocationPoint(nullptr, 0);
// 4. Lazily sweep pages of this heap until we find a freed area for
// this allocation or we finish sweeping all pages of this heap.
result = LazySweep(allocation_size, gc_info_index);
if (result)
return result;
// 5. Coalesce promptly freed areas and then try to allocate from a free
// list.
if (Coalesce()) {
result = AllocateFromFreeList(allocation_size, gc_info_index);
if (result)
return result;
}
// 6. Complete sweeping.
GetThreadState()->CompleteSweep();
// 7. Check if we should trigger a GC.
GetThreadState()->ScheduleGCIfNeeded();
// 8. Add a new page to this heap.
AllocatePage();
// 9. Try to allocate from a free list. This allocation must succeed.
result = AllocateFromFreeList(allocation_size, gc_info_index);
CHECK(result);
return result;
}
Address NormalPageArena::AllocateFromFreeList(size_t allocation_size,
size_t gc_info_index) {
// Try reusing a block from the largest bin. The underlying reasoning
// being that we want to amortize this slow allocation call by carving
// off as a large a free block as possible in one go; a block that will
// service this block and let following allocations be serviced quickly
// by bump allocation.
size_t bucket_size = static_cast<size_t>(1)
<< free_list_.biggest_free_list_index_;
int index = free_list_.biggest_free_list_index_;
for (; index > 0; --index, bucket_size >>= 1) {
FreeListEntry* entry = free_list_.free_lists_[index];
if (allocation_size > bucket_size) {
// Final bucket candidate; check initial entry if it is able
// to service this allocation. Do not perform a linear scan,
// as it is considered too costly.
if (!entry || entry->size() < allocation_size)
break;
}
if (entry) {
entry->Unlink(&free_list_.free_lists_[index]);
SetAllocationPoint(entry->GetAddress(), entry->size());
DCHECK(HasCurrentAllocationArea());
DCHECK_GE(RemainingAllocationSize(), allocation_size);
free_list_.biggest_free_list_index_ = index;
return AllocateObject(allocation_size, gc_info_index);
}
}
free_list_.biggest_free_list_index_ = index;
return nullptr;
}
LargeObjectArena::LargeObjectArena(ThreadState* state, int index)
: BaseArena(state, index) {}
Address LargeObjectArena::AllocateLargeObjectPage(size_t allocation_size,
size_t gc_info_index) {
// Caller already added space for object header and rounded up to allocation
// alignment
DCHECK(!(allocation_size & kAllocationMask));
// 1. Try to sweep large objects more than allocationSize bytes
// before allocating a new large object.
Address result = LazySweep(allocation_size, gc_info_index);
if (result)
return result;
// 2. If we have failed in sweeping allocationSize bytes,
// we complete sweeping before allocating this large object.
GetThreadState()->CompleteSweep();
// 3. Check if we should trigger a GC.
GetThreadState()->ScheduleGCIfNeeded();
return DoAllocateLargeObjectPage(allocation_size, gc_info_index);
}
Address LargeObjectArena::DoAllocateLargeObjectPage(size_t allocation_size,
size_t gc_info_index) {
size_t large_object_size =
LargeObjectPage::PageHeaderSize() + allocation_size;
// If ASan is supported we add allocationGranularity bytes to the allocated
// space and poison that to detect overflows
#if defined(ADDRESS_SANITIZER)
large_object_size += kAllocationGranularity;
#endif