This repository has been archived by the owner on Apr 22, 2023. It is now read-only.
/
spaces.cc
2635 lines (2155 loc) · 81.8 KB
/
spaces.cc
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 2006-2008 the V8 project authors. 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 "v8.h"
#include "macro-assembler.h"
#include "mark-compact.h"
#include "platform.h"
namespace v8 {
namespace internal {
// For contiguous spaces, top should be in the space (or at the end) and limit
// should be the end of the space.
#define ASSERT_SEMISPACE_ALLOCATION_INFO(info, space) \
ASSERT((space).low() <= (info).top \
&& (info).top <= (space).high() \
&& (info).limit == (space).high())
// ----------------------------------------------------------------------------
// HeapObjectIterator
HeapObjectIterator::HeapObjectIterator(PagedSpace* space) {
Initialize(space->bottom(), space->top(), NULL);
}
HeapObjectIterator::HeapObjectIterator(PagedSpace* space,
HeapObjectCallback size_func) {
Initialize(space->bottom(), space->top(), size_func);
}
HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start) {
Initialize(start, space->top(), NULL);
}
HeapObjectIterator::HeapObjectIterator(PagedSpace* space, Address start,
HeapObjectCallback size_func) {
Initialize(start, space->top(), size_func);
}
void HeapObjectIterator::Initialize(Address cur, Address end,
HeapObjectCallback size_f) {
cur_addr_ = cur;
end_addr_ = end;
end_page_ = Page::FromAllocationTop(end);
size_func_ = size_f;
Page* p = Page::FromAllocationTop(cur_addr_);
cur_limit_ = (p == end_page_) ? end_addr_ : p->AllocationTop();
#ifdef DEBUG
Verify();
#endif
}
bool HeapObjectIterator::HasNextInNextPage() {
if (cur_addr_ == end_addr_) return false;
Page* cur_page = Page::FromAllocationTop(cur_addr_);
cur_page = cur_page->next_page();
ASSERT(cur_page->is_valid());
cur_addr_ = cur_page->ObjectAreaStart();
cur_limit_ = (cur_page == end_page_) ? end_addr_ : cur_page->AllocationTop();
ASSERT(cur_addr_ < cur_limit_);
#ifdef DEBUG
Verify();
#endif
return true;
}
#ifdef DEBUG
void HeapObjectIterator::Verify() {
Page* p = Page::FromAllocationTop(cur_addr_);
ASSERT(p == Page::FromAllocationTop(cur_limit_));
ASSERT(p->Offset(cur_addr_) <= p->Offset(cur_limit_));
}
#endif
// -----------------------------------------------------------------------------
// PageIterator
PageIterator::PageIterator(PagedSpace* space, Mode mode) : space_(space) {
prev_page_ = NULL;
switch (mode) {
case PAGES_IN_USE:
stop_page_ = space->AllocationTopPage();
break;
case PAGES_USED_BY_MC:
stop_page_ = space->MCRelocationTopPage();
break;
case ALL_PAGES:
#ifdef DEBUG
// Verify that the cached last page in the space is actually the
// last page.
for (Page* p = space->first_page_; p->is_valid(); p = p->next_page()) {
if (!p->next_page()->is_valid()) {
ASSERT(space->last_page_ == p);
}
}
#endif
stop_page_ = space->last_page_;
break;
}
}
// -----------------------------------------------------------------------------
// Page
#ifdef DEBUG
Page::RSetState Page::rset_state_ = Page::IN_USE;
#endif
// -----------------------------------------------------------------------------
// MemoryAllocator
//
int MemoryAllocator::capacity_ = 0;
int MemoryAllocator::size_ = 0;
VirtualMemory* MemoryAllocator::initial_chunk_ = NULL;
// 270 is an estimate based on the static default heap size of a pair of 256K
// semispaces and a 64M old generation.
const int kEstimatedNumberOfChunks = 270;
List<MemoryAllocator::ChunkInfo> MemoryAllocator::chunks_(
kEstimatedNumberOfChunks);
List<int> MemoryAllocator::free_chunk_ids_(kEstimatedNumberOfChunks);
int MemoryAllocator::max_nof_chunks_ = 0;
int MemoryAllocator::top_ = 0;
void MemoryAllocator::Push(int free_chunk_id) {
ASSERT(max_nof_chunks_ > 0);
ASSERT(top_ < max_nof_chunks_);
free_chunk_ids_[top_++] = free_chunk_id;
}
int MemoryAllocator::Pop() {
ASSERT(top_ > 0);
return free_chunk_ids_[--top_];
}
bool MemoryAllocator::Setup(int capacity) {
capacity_ = RoundUp(capacity, Page::kPageSize);
// Over-estimate the size of chunks_ array. It assumes the expansion of old
// space is always in the unit of a chunk (kChunkSize) except the last
// expansion.
//
// Due to alignment, allocated space might be one page less than required
// number (kPagesPerChunk) of pages for old spaces.
//
// Reserve two chunk ids for semispaces, one for map space, one for old
// space, and one for code space.
max_nof_chunks_ = (capacity_ / (kChunkSize - Page::kPageSize)) + 5;
if (max_nof_chunks_ > kMaxNofChunks) return false;
size_ = 0;
ChunkInfo info; // uninitialized element.
for (int i = max_nof_chunks_ - 1; i >= 0; i--) {
chunks_.Add(info);
free_chunk_ids_.Add(i);
}
top_ = max_nof_chunks_;
return true;
}
void MemoryAllocator::TearDown() {
for (int i = 0; i < max_nof_chunks_; i++) {
if (chunks_[i].address() != NULL) DeleteChunk(i);
}
chunks_.Clear();
free_chunk_ids_.Clear();
if (initial_chunk_ != NULL) {
LOG(DeleteEvent("InitialChunk", initial_chunk_->address()));
delete initial_chunk_;
initial_chunk_ = NULL;
}
ASSERT(top_ == max_nof_chunks_); // all chunks are free
top_ = 0;
capacity_ = 0;
size_ = 0;
max_nof_chunks_ = 0;
}
void* MemoryAllocator::AllocateRawMemory(const size_t requested,
size_t* allocated,
Executability executable) {
if (size_ + static_cast<int>(requested) > capacity_) return NULL;
void* mem = OS::Allocate(requested, allocated, executable == EXECUTABLE);
int alloced = *allocated;
size_ += alloced;
Counters::memory_allocated.Increment(alloced);
return mem;
}
void MemoryAllocator::FreeRawMemory(void* mem, size_t length) {
OS::Free(mem, length);
Counters::memory_allocated.Decrement(length);
size_ -= length;
ASSERT(size_ >= 0);
}
void* MemoryAllocator::ReserveInitialChunk(const size_t requested) {
ASSERT(initial_chunk_ == NULL);
initial_chunk_ = new VirtualMemory(requested);
CHECK(initial_chunk_ != NULL);
if (!initial_chunk_->IsReserved()) {
delete initial_chunk_;
initial_chunk_ = NULL;
return NULL;
}
// We are sure that we have mapped a block of requested addresses.
ASSERT(initial_chunk_->size() == requested);
LOG(NewEvent("InitialChunk", initial_chunk_->address(), requested));
size_ += requested;
return initial_chunk_->address();
}
static int PagesInChunk(Address start, size_t size) {
// The first page starts on the first page-aligned address from start onward
// and the last page ends on the last page-aligned address before
// start+size. Page::kPageSize is a power of two so we can divide by
// shifting.
return (RoundDown(start + size, Page::kPageSize)
- RoundUp(start, Page::kPageSize)) >> Page::kPageSizeBits;
}
Page* MemoryAllocator::AllocatePages(int requested_pages, int* allocated_pages,
PagedSpace* owner) {
if (requested_pages <= 0) return Page::FromAddress(NULL);
size_t chunk_size = requested_pages * Page::kPageSize;
// There is not enough space to guarantee the desired number pages can be
// allocated.
if (size_ + static_cast<int>(chunk_size) > capacity_) {
// Request as many pages as we can.
chunk_size = capacity_ - size_;
requested_pages = chunk_size >> Page::kPageSizeBits;
if (requested_pages <= 0) return Page::FromAddress(NULL);
}
void* chunk = AllocateRawMemory(chunk_size, &chunk_size, owner->executable());
if (chunk == NULL) return Page::FromAddress(NULL);
LOG(NewEvent("PagedChunk", chunk, chunk_size));
*allocated_pages = PagesInChunk(static_cast<Address>(chunk), chunk_size);
if (*allocated_pages == 0) {
FreeRawMemory(chunk, chunk_size);
LOG(DeleteEvent("PagedChunk", chunk));
return Page::FromAddress(NULL);
}
int chunk_id = Pop();
chunks_[chunk_id].init(static_cast<Address>(chunk), chunk_size, owner);
return InitializePagesInChunk(chunk_id, *allocated_pages, owner);
}
Page* MemoryAllocator::CommitPages(Address start, size_t size,
PagedSpace* owner, int* num_pages) {
ASSERT(start != NULL);
*num_pages = PagesInChunk(start, size);
ASSERT(*num_pages > 0);
ASSERT(initial_chunk_ != NULL);
ASSERT(InInitialChunk(start));
ASSERT(InInitialChunk(start + size - 1));
if (!initial_chunk_->Commit(start, size, owner->executable() == EXECUTABLE)) {
return Page::FromAddress(NULL);
}
Counters::memory_allocated.Increment(size);
// So long as we correctly overestimated the number of chunks we should not
// run out of chunk ids.
CHECK(!OutOfChunkIds());
int chunk_id = Pop();
chunks_[chunk_id].init(start, size, owner);
return InitializePagesInChunk(chunk_id, *num_pages, owner);
}
bool MemoryAllocator::CommitBlock(Address start,
size_t size,
Executability executable) {
ASSERT(start != NULL);
ASSERT(size > 0);
ASSERT(initial_chunk_ != NULL);
ASSERT(InInitialChunk(start));
ASSERT(InInitialChunk(start + size - 1));
if (!initial_chunk_->Commit(start, size, executable)) return false;
Counters::memory_allocated.Increment(size);
return true;
}
bool MemoryAllocator::UncommitBlock(Address start, size_t size) {
ASSERT(start != NULL);
ASSERT(size > 0);
ASSERT(initial_chunk_ != NULL);
ASSERT(InInitialChunk(start));
ASSERT(InInitialChunk(start + size - 1));
if (!initial_chunk_->Uncommit(start, size)) return false;
Counters::memory_allocated.Decrement(size);
return true;
}
Page* MemoryAllocator::InitializePagesInChunk(int chunk_id, int pages_in_chunk,
PagedSpace* owner) {
ASSERT(IsValidChunk(chunk_id));
ASSERT(pages_in_chunk > 0);
Address chunk_start = chunks_[chunk_id].address();
Address low = RoundUp(chunk_start, Page::kPageSize);
#ifdef DEBUG
size_t chunk_size = chunks_[chunk_id].size();
Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
ASSERT(pages_in_chunk <=
((OffsetFrom(high) - OffsetFrom(low)) / Page::kPageSize));
#endif
Address page_addr = low;
for (int i = 0; i < pages_in_chunk; i++) {
Page* p = Page::FromAddress(page_addr);
p->opaque_header = OffsetFrom(page_addr + Page::kPageSize) | chunk_id;
p->is_normal_page = 1;
page_addr += Page::kPageSize;
}
// Set the next page of the last page to 0.
Page* last_page = Page::FromAddress(page_addr - Page::kPageSize);
last_page->opaque_header = OffsetFrom(0) | chunk_id;
return Page::FromAddress(low);
}
Page* MemoryAllocator::FreePages(Page* p) {
if (!p->is_valid()) return p;
// Find the first page in the same chunk as 'p'
Page* first_page = FindFirstPageInSameChunk(p);
Page* page_to_return = Page::FromAddress(NULL);
if (p != first_page) {
// Find the last page in the same chunk as 'prev'.
Page* last_page = FindLastPageInSameChunk(p);
first_page = GetNextPage(last_page); // first page in next chunk
// set the next_page of last_page to NULL
SetNextPage(last_page, Page::FromAddress(NULL));
page_to_return = p; // return 'p' when exiting
}
while (first_page->is_valid()) {
int chunk_id = GetChunkId(first_page);
ASSERT(IsValidChunk(chunk_id));
// Find the first page of the next chunk before deleting this chunk.
first_page = GetNextPage(FindLastPageInSameChunk(first_page));
// Free the current chunk.
DeleteChunk(chunk_id);
}
return page_to_return;
}
void MemoryAllocator::DeleteChunk(int chunk_id) {
ASSERT(IsValidChunk(chunk_id));
ChunkInfo& c = chunks_[chunk_id];
// We cannot free a chunk contained in the initial chunk because it was not
// allocated with AllocateRawMemory. Instead we uncommit the virtual
// memory.
if (InInitialChunk(c.address())) {
// TODO(1240712): VirtualMemory::Uncommit has a return value which
// is ignored here.
initial_chunk_->Uncommit(c.address(), c.size());
Counters::memory_allocated.Decrement(c.size());
} else {
LOG(DeleteEvent("PagedChunk", c.address()));
FreeRawMemory(c.address(), c.size());
}
c.init(NULL, 0, NULL);
Push(chunk_id);
}
Page* MemoryAllocator::FindFirstPageInSameChunk(Page* p) {
int chunk_id = GetChunkId(p);
ASSERT(IsValidChunk(chunk_id));
Address low = RoundUp(chunks_[chunk_id].address(), Page::kPageSize);
return Page::FromAddress(low);
}
Page* MemoryAllocator::FindLastPageInSameChunk(Page* p) {
int chunk_id = GetChunkId(p);
ASSERT(IsValidChunk(chunk_id));
Address chunk_start = chunks_[chunk_id].address();
size_t chunk_size = chunks_[chunk_id].size();
Address high = RoundDown(chunk_start + chunk_size, Page::kPageSize);
ASSERT(chunk_start <= p->address() && p->address() < high);
return Page::FromAddress(high - Page::kPageSize);
}
#ifdef DEBUG
void MemoryAllocator::ReportStatistics() {
float pct = static_cast<float>(capacity_ - size_) / capacity_;
PrintF(" capacity: %d, used: %d, available: %%%d\n\n",
capacity_, size_, static_cast<int>(pct*100));
}
#endif
// -----------------------------------------------------------------------------
// PagedSpace implementation
PagedSpace::PagedSpace(int max_capacity,
AllocationSpace id,
Executability executable)
: Space(id, executable) {
max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
* Page::kObjectAreaSize;
accounting_stats_.Clear();
allocation_info_.top = NULL;
allocation_info_.limit = NULL;
mc_forwarding_info_.top = NULL;
mc_forwarding_info_.limit = NULL;
}
bool PagedSpace::Setup(Address start, size_t size) {
if (HasBeenSetup()) return false;
int num_pages = 0;
// Try to use the virtual memory range passed to us. If it is too small to
// contain at least one page, ignore it and allocate instead.
int pages_in_chunk = PagesInChunk(start, size);
if (pages_in_chunk > 0) {
first_page_ = MemoryAllocator::CommitPages(RoundUp(start, Page::kPageSize),
Page::kPageSize * pages_in_chunk,
this, &num_pages);
} else {
int requested_pages = Min(MemoryAllocator::kPagesPerChunk,
max_capacity_ / Page::kObjectAreaSize);
first_page_ =
MemoryAllocator::AllocatePages(requested_pages, &num_pages, this);
if (!first_page_->is_valid()) return false;
}
// We are sure that the first page is valid and that we have at least one
// page.
ASSERT(first_page_->is_valid());
ASSERT(num_pages > 0);
accounting_stats_.ExpandSpace(num_pages * Page::kObjectAreaSize);
ASSERT(Capacity() <= max_capacity_);
// Sequentially initialize remembered sets in the newly allocated
// pages and cache the current last page in the space.
for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
p->ClearRSet();
last_page_ = p;
}
// Use first_page_ for allocation.
SetAllocationInfo(&allocation_info_, first_page_);
return true;
}
bool PagedSpace::HasBeenSetup() {
return (Capacity() > 0);
}
void PagedSpace::TearDown() {
first_page_ = MemoryAllocator::FreePages(first_page_);
ASSERT(!first_page_->is_valid());
accounting_stats_.Clear();
}
#ifdef ENABLE_HEAP_PROTECTION
void PagedSpace::Protect() {
Page* page = first_page_;
while (page->is_valid()) {
MemoryAllocator::ProtectChunkFromPage(page);
page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
}
}
void PagedSpace::Unprotect() {
Page* page = first_page_;
while (page->is_valid()) {
MemoryAllocator::UnprotectChunkFromPage(page);
page = MemoryAllocator::FindLastPageInSameChunk(page)->next_page();
}
}
#endif
void PagedSpace::ClearRSet() {
PageIterator it(this, PageIterator::ALL_PAGES);
while (it.has_next()) {
it.next()->ClearRSet();
}
}
Object* PagedSpace::FindObject(Address addr) {
// Note: this function can only be called before or after mark-compact GC
// because it accesses map pointers.
ASSERT(!MarkCompactCollector::in_use());
if (!Contains(addr)) return Failure::Exception();
Page* p = Page::FromAddress(addr);
ASSERT(IsUsed(p));
Address cur = p->ObjectAreaStart();
Address end = p->AllocationTop();
while (cur < end) {
HeapObject* obj = HeapObject::FromAddress(cur);
Address next = cur + obj->Size();
if ((cur <= addr) && (addr < next)) return obj;
cur = next;
}
UNREACHABLE();
return Failure::Exception();
}
bool PagedSpace::IsUsed(Page* page) {
PageIterator it(this, PageIterator::PAGES_IN_USE);
while (it.has_next()) {
if (page == it.next()) return true;
}
return false;
}
void PagedSpace::SetAllocationInfo(AllocationInfo* alloc_info, Page* p) {
alloc_info->top = p->ObjectAreaStart();
alloc_info->limit = p->ObjectAreaEnd();
ASSERT(alloc_info->VerifyPagedAllocation());
}
void PagedSpace::MCResetRelocationInfo() {
// Set page indexes.
int i = 0;
PageIterator it(this, PageIterator::ALL_PAGES);
while (it.has_next()) {
Page* p = it.next();
p->mc_page_index = i++;
}
// Set mc_forwarding_info_ to the first page in the space.
SetAllocationInfo(&mc_forwarding_info_, first_page_);
// All the bytes in the space are 'available'. We will rediscover
// allocated and wasted bytes during GC.
accounting_stats_.Reset();
}
int PagedSpace::MCSpaceOffsetForAddress(Address addr) {
#ifdef DEBUG
// The Contains function considers the address at the beginning of a
// page in the page, MCSpaceOffsetForAddress considers it is in the
// previous page.
if (Page::IsAlignedToPageSize(addr)) {
ASSERT(Contains(addr - kPointerSize));
} else {
ASSERT(Contains(addr));
}
#endif
// If addr is at the end of a page, it belongs to previous page
Page* p = Page::IsAlignedToPageSize(addr)
? Page::FromAllocationTop(addr)
: Page::FromAddress(addr);
int index = p->mc_page_index;
return (index * Page::kPageSize) + p->Offset(addr);
}
// Slow case for reallocating and promoting objects during a compacting
// collection. This function is not space-specific.
HeapObject* PagedSpace::SlowMCAllocateRaw(int size_in_bytes) {
Page* current_page = TopPageOf(mc_forwarding_info_);
if (!current_page->next_page()->is_valid()) {
if (!Expand(current_page)) {
return NULL;
}
}
// There are surely more pages in the space now.
ASSERT(current_page->next_page()->is_valid());
// We do not add the top of page block for current page to the space's
// free list---the block may contain live objects so we cannot write
// bookkeeping information to it. Instead, we will recover top of page
// blocks when we move objects to their new locations.
//
// We do however write the allocation pointer to the page. The encoding
// of forwarding addresses is as an offset in terms of live bytes, so we
// need quick access to the allocation top of each page to decode
// forwarding addresses.
current_page->mc_relocation_top = mc_forwarding_info_.top;
SetAllocationInfo(&mc_forwarding_info_, current_page->next_page());
return AllocateLinearly(&mc_forwarding_info_, size_in_bytes);
}
bool PagedSpace::Expand(Page* last_page) {
ASSERT(max_capacity_ % Page::kObjectAreaSize == 0);
ASSERT(Capacity() % Page::kObjectAreaSize == 0);
if (Capacity() == max_capacity_) return false;
ASSERT(Capacity() < max_capacity_);
// Last page must be valid and its next page is invalid.
ASSERT(last_page->is_valid() && !last_page->next_page()->is_valid());
int available_pages = (max_capacity_ - Capacity()) / Page::kObjectAreaSize;
if (available_pages <= 0) return false;
int desired_pages = Min(available_pages, MemoryAllocator::kPagesPerChunk);
Page* p = MemoryAllocator::AllocatePages(desired_pages, &desired_pages, this);
if (!p->is_valid()) return false;
accounting_stats_.ExpandSpace(desired_pages * Page::kObjectAreaSize);
ASSERT(Capacity() <= max_capacity_);
MemoryAllocator::SetNextPage(last_page, p);
// Sequentially clear remembered set of new pages and and cache the
// new last page in the space.
while (p->is_valid()) {
p->ClearRSet();
last_page_ = p;
p = p->next_page();
}
return true;
}
#ifdef DEBUG
int PagedSpace::CountTotalPages() {
int count = 0;
for (Page* p = first_page_; p->is_valid(); p = p->next_page()) {
count++;
}
return count;
}
#endif
void PagedSpace::Shrink() {
// Release half of free pages.
Page* top_page = AllocationTopPage();
ASSERT(top_page->is_valid());
// Loop over the pages from the top page to the end of the space to count
// the number of pages to keep and find the last page to keep.
int free_pages = 0;
int pages_to_keep = 0; // Of the free pages.
Page* last_page_to_keep = top_page;
Page* current_page = top_page->next_page();
// Loop over the pages to the end of the space.
while (current_page->is_valid()) {
#if defined(ANDROID)
// Free all chunks if possible
#else
// Advance last_page_to_keep every other step to end up at the midpoint.
if ((free_pages & 0x1) == 1) {
pages_to_keep++;
last_page_to_keep = last_page_to_keep->next_page();
}
#endif
free_pages++;
current_page = current_page->next_page();
}
// Free pages after last_page_to_keep, and adjust the next_page link.
Page* p = MemoryAllocator::FreePages(last_page_to_keep->next_page());
MemoryAllocator::SetNextPage(last_page_to_keep, p);
// Since pages are only freed in whole chunks, we may have kept more
// than pages_to_keep. Count the extra pages and cache the new last
// page in the space.
last_page_ = last_page_to_keep;
while (p->is_valid()) {
pages_to_keep++;
last_page_ = p;
p = p->next_page();
}
// The difference between free_pages and pages_to_keep is the number of
// pages actually freed.
ASSERT(pages_to_keep <= free_pages);
int bytes_freed = (free_pages - pages_to_keep) * Page::kObjectAreaSize;
accounting_stats_.ShrinkSpace(bytes_freed);
ASSERT(Capacity() == CountTotalPages() * Page::kObjectAreaSize);
}
bool PagedSpace::EnsureCapacity(int capacity) {
if (Capacity() >= capacity) return true;
// Start from the allocation top and loop to the last page in the space.
Page* last_page = AllocationTopPage();
Page* next_page = last_page->next_page();
while (next_page->is_valid()) {
last_page = MemoryAllocator::FindLastPageInSameChunk(next_page);
next_page = last_page->next_page();
}
// Expand the space until it has the required capacity or expansion fails.
do {
if (!Expand(last_page)) return false;
ASSERT(last_page->next_page()->is_valid());
last_page =
MemoryAllocator::FindLastPageInSameChunk(last_page->next_page());
} while (Capacity() < capacity);
return true;
}
#ifdef DEBUG
void PagedSpace::Print() { }
#endif
#ifdef DEBUG
// We do not assume that the PageIterator works, because it depends on the
// invariants we are checking during verification.
void PagedSpace::Verify(ObjectVisitor* visitor) {
// The allocation pointer should be valid, and it should be in a page in the
// space.
ASSERT(allocation_info_.VerifyPagedAllocation());
Page* top_page = Page::FromAllocationTop(allocation_info_.top);
ASSERT(MemoryAllocator::IsPageInSpace(top_page, this));
// Loop over all the pages.
bool above_allocation_top = false;
Page* current_page = first_page_;
while (current_page->is_valid()) {
if (above_allocation_top) {
// We don't care what's above the allocation top.
} else {
// Unless this is the last page in the space containing allocated
// objects, the allocation top should be at a constant offset from the
// object area end.
Address top = current_page->AllocationTop();
if (current_page == top_page) {
ASSERT(top == allocation_info_.top);
// The next page will be above the allocation top.
above_allocation_top = true;
} else {
ASSERT(top == current_page->ObjectAreaEnd() - page_extra_);
}
// It should be packed with objects from the bottom to the top.
Address current = current_page->ObjectAreaStart();
while (current < top) {
HeapObject* object = HeapObject::FromAddress(current);
// The first word should be a map, and we expect all map pointers to
// be in map space.
Map* map = object->map();
ASSERT(map->IsMap());
ASSERT(Heap::map_space()->Contains(map));
// Perform space-specific object verification.
VerifyObject(object);
// The object itself should look OK.
object->Verify();
// All the interior pointers should be contained in the heap and
// have their remembered set bits set if required as determined
// by the visitor.
int size = object->Size();
if (object->IsCode()) {
Code::cast(object)->ConvertICTargetsFromAddressToObject();
object->IterateBody(map->instance_type(), size, visitor);
Code::cast(object)->ConvertICTargetsFromObjectToAddress();
} else {
object->IterateBody(map->instance_type(), size, visitor);
}
current += size;
}
// The allocation pointer should not be in the middle of an object.
ASSERT(current == top);
}
current_page = current_page->next_page();
}
}
#endif
// -----------------------------------------------------------------------------
// NewSpace implementation
bool NewSpace::Setup(Address start, int size) {
// Setup new space based on the preallocated memory block defined by
// start and size. The provided space is divided into two semi-spaces.
// To support fast containment testing in the new space, the size of
// this chunk must be a power of two and it must be aligned to its size.
int initial_semispace_capacity = Heap::InitialSemiSpaceSize();
int maximum_semispace_capacity = Heap::SemiSpaceSize();
ASSERT(initial_semispace_capacity <= maximum_semispace_capacity);
ASSERT(IsPowerOf2(maximum_semispace_capacity));
maximum_capacity_ = maximum_semispace_capacity;
capacity_ = initial_semispace_capacity;
// Allocate and setup the histogram arrays if necessary.
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
allocated_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
promoted_histogram_ = NewArray<HistogramInfo>(LAST_TYPE + 1);
#define SET_NAME(name) allocated_histogram_[name].set_name(#name); \
promoted_histogram_[name].set_name(#name);
INSTANCE_TYPE_LIST(SET_NAME)
#undef SET_NAME
#endif
ASSERT(size == 2 * maximum_capacity_);
ASSERT(IsAddressAligned(start, size, 0));
if (!to_space_.Setup(start, capacity_, maximum_capacity_)) {
return false;
}
if (!from_space_.Setup(start + maximum_capacity_,
capacity_,
maximum_capacity_)) {
return false;
}
start_ = start;
address_mask_ = ~(size - 1);
object_mask_ = address_mask_ | kHeapObjectTag;
object_expected_ = reinterpret_cast<uintptr_t>(start) | kHeapObjectTag;
allocation_info_.top = to_space_.low();
allocation_info_.limit = to_space_.high();
mc_forwarding_info_.top = NULL;
mc_forwarding_info_.limit = NULL;
ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
return true;
}
void NewSpace::TearDown() {
#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
if (allocated_histogram_) {
DeleteArray(allocated_histogram_);
allocated_histogram_ = NULL;
}
if (promoted_histogram_) {
DeleteArray(promoted_histogram_);
promoted_histogram_ = NULL;
}
#endif
start_ = NULL;
capacity_ = 0;
allocation_info_.top = NULL;
allocation_info_.limit = NULL;
mc_forwarding_info_.top = NULL;
mc_forwarding_info_.limit = NULL;
to_space_.TearDown();
from_space_.TearDown();
}
#ifdef ENABLE_HEAP_PROTECTION
void NewSpace::Protect() {
MemoryAllocator::Protect(ToSpaceLow(), Capacity());
MemoryAllocator::Protect(FromSpaceLow(), Capacity());
}
void NewSpace::Unprotect() {
MemoryAllocator::Unprotect(ToSpaceLow(), Capacity(),
to_space_.executable());
MemoryAllocator::Unprotect(FromSpaceLow(), Capacity(),
from_space_.executable());
}
#endif
void NewSpace::Flip() {
SemiSpace tmp = from_space_;
from_space_ = to_space_;
to_space_ = tmp;
}
bool NewSpace::Grow() {
ASSERT(capacity_ < maximum_capacity_);
// TODO(1240712): Failure to double the from space can result in
// semispaces of different sizes. In the event of that failure, the
// to space doubling should be rolled back before returning false.
if (!to_space_.Grow() || !from_space_.Grow()) return false;
capacity_ = to_space_.Capacity() + from_space_.Capacity();
allocation_info_.limit = to_space_.high();
ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
return true;
}
void NewSpace::ResetAllocationInfo() {
allocation_info_.top = to_space_.low();
allocation_info_.limit = to_space_.high();
ASSERT_SEMISPACE_ALLOCATION_INFO(allocation_info_, to_space_);
}
void NewSpace::MCResetRelocationInfo() {
mc_forwarding_info_.top = from_space_.low();
mc_forwarding_info_.limit = from_space_.high();
ASSERT_SEMISPACE_ALLOCATION_INFO(mc_forwarding_info_, from_space_);