This repository has been archived by the owner on Apr 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
spaces.cc
2866 lines (2367 loc) · 89.7 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 2011 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 "liveobjectlist-inl.h"
#include "macro-assembler.h"
#include "mark-compact.h"
#include "platform.h"
namespace v8 {
namespace internal {
// ----------------------------------------------------------------------------
// HeapObjectIterator
HeapObjectIterator::HeapObjectIterator(PagedSpace* space) {
// You can't actually iterate over the anchor page. It is not a real page,
// just an anchor for the double linked page list. Initialize as if we have
// reached the end of the anchor page, then the first iteration will move on
// to the first page.
Initialize(space,
NULL,
NULL,
kAllPagesInSpace,
NULL);
}
HeapObjectIterator::HeapObjectIterator(PagedSpace* space,
HeapObjectCallback size_func) {
// You can't actually iterate over the anchor page. It is not a real page,
// just an anchor for the double linked page list. Initialize the current
// address and end as NULL, then the first iteration will move on
// to the first page.
Initialize(space,
NULL,
NULL,
kAllPagesInSpace,
size_func);
}
HeapObjectIterator::HeapObjectIterator(Page* page,
HeapObjectCallback size_func) {
Space* owner = page->owner();
ASSERT(owner == HEAP->old_pointer_space() ||
owner == HEAP->old_data_space() ||
owner == HEAP->map_space() ||
owner == HEAP->cell_space() ||
owner == HEAP->code_space());
Initialize(reinterpret_cast<PagedSpace*>(owner),
page->area_start(),
page->area_end(),
kOnePageOnly,
size_func);
ASSERT(page->WasSweptPrecisely());
}
void HeapObjectIterator::Initialize(PagedSpace* space,
Address cur, Address end,
HeapObjectIterator::PageMode mode,
HeapObjectCallback size_f) {
// Check that we actually can iterate this space.
ASSERT(!space->was_swept_conservatively());
space_ = space;
cur_addr_ = cur;
cur_end_ = end;
page_mode_ = mode;
size_func_ = size_f;
}
// We have hit the end of the page and should advance to the next block of
// objects. This happens at the end of the page.
bool HeapObjectIterator::AdvanceToNextPage() {
ASSERT(cur_addr_ == cur_end_);
if (page_mode_ == kOnePageOnly) return false;
Page* cur_page;
if (cur_addr_ == NULL) {
cur_page = space_->anchor();
} else {
cur_page = Page::FromAddress(cur_addr_ - 1);
ASSERT(cur_addr_ == cur_page->area_end());
}
cur_page = cur_page->next_page();
if (cur_page == space_->anchor()) return false;
cur_addr_ = cur_page->area_start();
cur_end_ = cur_page->area_end();
ASSERT(cur_page->WasSweptPrecisely());
return true;
}
// -----------------------------------------------------------------------------
// CodeRange
CodeRange::CodeRange(Isolate* isolate)
: isolate_(isolate),
code_range_(NULL),
free_list_(0),
allocation_list_(0),
current_allocation_block_index_(0) {
}
bool CodeRange::SetUp(const size_t requested) {
ASSERT(code_range_ == NULL);
code_range_ = new VirtualMemory(requested);
CHECK(code_range_ != NULL);
if (!code_range_->IsReserved()) {
delete code_range_;
code_range_ = NULL;
return false;
}
// We are sure that we have mapped a block of requested addresses.
ASSERT(code_range_->size() == requested);
LOG(isolate_, NewEvent("CodeRange", code_range_->address(), requested));
Address base = reinterpret_cast<Address>(code_range_->address());
Address aligned_base =
RoundUp(reinterpret_cast<Address>(code_range_->address()),
MemoryChunk::kAlignment);
size_t size = code_range_->size() - (aligned_base - base);
allocation_list_.Add(FreeBlock(aligned_base, size));
current_allocation_block_index_ = 0;
return true;
}
int CodeRange::CompareFreeBlockAddress(const FreeBlock* left,
const FreeBlock* right) {
// The entire point of CodeRange is that the difference between two
// addresses in the range can be represented as a signed 32-bit int,
// so the cast is semantically correct.
return static_cast<int>(left->start - right->start);
}
void CodeRange::GetNextAllocationBlock(size_t requested) {
for (current_allocation_block_index_++;
current_allocation_block_index_ < allocation_list_.length();
current_allocation_block_index_++) {
if (requested <= allocation_list_[current_allocation_block_index_].size) {
return; // Found a large enough allocation block.
}
}
// Sort and merge the free blocks on the free list and the allocation list.
free_list_.AddAll(allocation_list_);
allocation_list_.Clear();
free_list_.Sort(&CompareFreeBlockAddress);
for (int i = 0; i < free_list_.length();) {
FreeBlock merged = free_list_[i];
i++;
// Add adjacent free blocks to the current merged block.
while (i < free_list_.length() &&
free_list_[i].start == merged.start + merged.size) {
merged.size += free_list_[i].size;
i++;
}
if (merged.size > 0) {
allocation_list_.Add(merged);
}
}
free_list_.Clear();
for (current_allocation_block_index_ = 0;
current_allocation_block_index_ < allocation_list_.length();
current_allocation_block_index_++) {
if (requested <= allocation_list_[current_allocation_block_index_].size) {
return; // Found a large enough allocation block.
}
}
// Code range is full or too fragmented.
V8::FatalProcessOutOfMemory("CodeRange::GetNextAllocationBlock");
}
Address CodeRange::AllocateRawMemory(const size_t requested,
size_t* allocated) {
ASSERT(current_allocation_block_index_ < allocation_list_.length());
if (requested > allocation_list_[current_allocation_block_index_].size) {
// Find an allocation block large enough. This function call may
// call V8::FatalProcessOutOfMemory if it cannot find a large enough block.
GetNextAllocationBlock(requested);
}
// Commit the requested memory at the start of the current allocation block.
size_t aligned_requested = RoundUp(requested, MemoryChunk::kAlignment);
FreeBlock current = allocation_list_[current_allocation_block_index_];
if (aligned_requested >= (current.size - Page::kPageSize)) {
// Don't leave a small free block, useless for a large object or chunk.
*allocated = current.size;
} else {
*allocated = aligned_requested;
}
ASSERT(*allocated <= current.size);
ASSERT(IsAddressAligned(current.start, MemoryChunk::kAlignment));
if (!MemoryAllocator::CommitCodePage(code_range_,
current.start,
*allocated)) {
*allocated = 0;
return NULL;
}
allocation_list_[current_allocation_block_index_].start += *allocated;
allocation_list_[current_allocation_block_index_].size -= *allocated;
if (*allocated == current.size) {
GetNextAllocationBlock(0); // This block is used up, get the next one.
}
return current.start;
}
void CodeRange::FreeRawMemory(Address address, size_t length) {
ASSERT(IsAddressAligned(address, MemoryChunk::kAlignment));
free_list_.Add(FreeBlock(address, length));
code_range_->Uncommit(address, length);
}
void CodeRange::TearDown() {
delete code_range_; // Frees all memory in the virtual memory range.
code_range_ = NULL;
free_list_.Free();
allocation_list_.Free();
}
// -----------------------------------------------------------------------------
// MemoryAllocator
//
MemoryAllocator::MemoryAllocator(Isolate* isolate)
: isolate_(isolate),
capacity_(0),
capacity_executable_(0),
size_(0),
size_executable_(0) {
}
bool MemoryAllocator::SetUp(intptr_t capacity, intptr_t capacity_executable) {
capacity_ = RoundUp(capacity, Page::kPageSize);
capacity_executable_ = RoundUp(capacity_executable, Page::kPageSize);
ASSERT_GE(capacity_, capacity_executable_);
size_ = 0;
size_executable_ = 0;
return true;
}
void MemoryAllocator::TearDown() {
// Check that spaces were torn down before MemoryAllocator.
ASSERT(size_ == 0);
// TODO(gc) this will be true again when we fix FreeMemory.
// ASSERT(size_executable_ == 0);
capacity_ = 0;
capacity_executable_ = 0;
}
void MemoryAllocator::FreeMemory(VirtualMemory* reservation,
Executability executable) {
// TODO(gc) make code_range part of memory allocator?
ASSERT(reservation->IsReserved());
size_t size = reservation->size();
ASSERT(size_ >= size);
size_ -= size;
isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size));
if (executable == EXECUTABLE) {
ASSERT(size_executable_ >= size);
size_executable_ -= size;
}
// Code which is part of the code-range does not have its own VirtualMemory.
ASSERT(!isolate_->code_range()->contains(
static_cast<Address>(reservation->address())));
ASSERT(executable == NOT_EXECUTABLE || !isolate_->code_range()->exists());
reservation->Release();
}
void MemoryAllocator::FreeMemory(Address base,
size_t size,
Executability executable) {
// TODO(gc) make code_range part of memory allocator?
ASSERT(size_ >= size);
size_ -= size;
isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size));
if (executable == EXECUTABLE) {
ASSERT(size_executable_ >= size);
size_executable_ -= size;
}
if (isolate_->code_range()->contains(static_cast<Address>(base))) {
ASSERT(executable == EXECUTABLE);
isolate_->code_range()->FreeRawMemory(base, size);
} else {
ASSERT(executable == NOT_EXECUTABLE || !isolate_->code_range()->exists());
bool result = VirtualMemory::ReleaseRegion(base, size);
USE(result);
ASSERT(result);
}
}
Address MemoryAllocator::ReserveAlignedMemory(size_t size,
size_t alignment,
VirtualMemory* controller) {
VirtualMemory reservation(size, alignment);
if (!reservation.IsReserved()) return NULL;
size_ += reservation.size();
Address base = RoundUp(static_cast<Address>(reservation.address()),
alignment);
controller->TakeControl(&reservation);
return base;
}
Address MemoryAllocator::AllocateAlignedMemory(size_t size,
size_t alignment,
Executability executable,
VirtualMemory* controller) {
VirtualMemory reservation;
Address base = ReserveAlignedMemory(size, alignment, &reservation);
if (base == NULL) return NULL;
if (executable == EXECUTABLE) {
if (!CommitCodePage(&reservation, base, size)) {
base = NULL;
}
} else {
if (!reservation.Commit(base, size, false)) {
base = NULL;
}
}
if (base == NULL) {
// Failed to commit the body. Release the mapping and any partially
// commited regions inside it.
reservation.Release();
return NULL;
}
controller->TakeControl(&reservation);
return base;
}
void Page::InitializeAsAnchor(PagedSpace* owner) {
set_owner(owner);
set_prev_page(this);
set_next_page(this);
}
NewSpacePage* NewSpacePage::Initialize(Heap* heap,
Address start,
SemiSpace* semi_space) {
Address area_start = start + NewSpacePage::kObjectStartOffset;
Address area_end = start + Page::kPageSize;
MemoryChunk* chunk = MemoryChunk::Initialize(heap,
start,
Page::kPageSize,
area_start,
area_end,
NOT_EXECUTABLE,
semi_space);
chunk->set_next_chunk(NULL);
chunk->set_prev_chunk(NULL);
chunk->initialize_scan_on_scavenge(true);
bool in_to_space = (semi_space->id() != kFromSpace);
chunk->SetFlag(in_to_space ? MemoryChunk::IN_TO_SPACE
: MemoryChunk::IN_FROM_SPACE);
ASSERT(!chunk->IsFlagSet(in_to_space ? MemoryChunk::IN_FROM_SPACE
: MemoryChunk::IN_TO_SPACE));
NewSpacePage* page = static_cast<NewSpacePage*>(chunk);
heap->incremental_marking()->SetNewSpacePageFlags(page);
return page;
}
void NewSpacePage::InitializeAsAnchor(SemiSpace* semi_space) {
set_owner(semi_space);
set_next_chunk(this);
set_prev_chunk(this);
// Flags marks this invalid page as not being in new-space.
// All real new-space pages will be in new-space.
SetFlags(0, ~0);
}
MemoryChunk* MemoryChunk::Initialize(Heap* heap,
Address base,
size_t size,
Address area_start,
Address area_end,
Executability executable,
Space* owner) {
MemoryChunk* chunk = FromAddress(base);
ASSERT(base == chunk->address());
chunk->heap_ = heap;
chunk->size_ = size;
chunk->area_start_ = area_start;
chunk->area_end_ = area_end;
chunk->flags_ = 0;
chunk->set_owner(owner);
chunk->InitializeReservedMemory();
chunk->slots_buffer_ = NULL;
chunk->skip_list_ = NULL;
chunk->ResetLiveBytes();
Bitmap::Clear(chunk);
chunk->initialize_scan_on_scavenge(false);
chunk->SetFlag(WAS_SWEPT_PRECISELY);
ASSERT(OFFSET_OF(MemoryChunk, flags_) == kFlagsOffset);
ASSERT(OFFSET_OF(MemoryChunk, live_byte_count_) == kLiveBytesOffset);
if (executable == EXECUTABLE) {
chunk->SetFlag(IS_EXECUTABLE);
}
if (owner == heap->old_data_space()) {
chunk->SetFlag(CONTAINS_ONLY_DATA);
}
return chunk;
}
void MemoryChunk::InsertAfter(MemoryChunk* other) {
next_chunk_ = other->next_chunk_;
prev_chunk_ = other;
other->next_chunk_->prev_chunk_ = this;
other->next_chunk_ = this;
}
void MemoryChunk::Unlink() {
if (!InNewSpace() && IsFlagSet(SCAN_ON_SCAVENGE)) {
heap_->decrement_scan_on_scavenge_pages();
ClearFlag(SCAN_ON_SCAVENGE);
}
next_chunk_->prev_chunk_ = prev_chunk_;
prev_chunk_->next_chunk_ = next_chunk_;
prev_chunk_ = NULL;
next_chunk_ = NULL;
}
MemoryChunk* MemoryAllocator::AllocateChunk(intptr_t body_size,
Executability executable,
Space* owner) {
size_t chunk_size;
Heap* heap = isolate_->heap();
Address base = NULL;
VirtualMemory reservation;
Address area_start = NULL;
Address area_end = NULL;
if (executable == EXECUTABLE) {
chunk_size = RoundUp(CodePageAreaStartOffset() + body_size,
OS::CommitPageSize()) + CodePageGuardSize();
// Check executable memory limit.
if (size_executable_ + chunk_size > capacity_executable_) {
LOG(isolate_,
StringEvent("MemoryAllocator::AllocateRawMemory",
"V8 Executable Allocation capacity exceeded"));
return NULL;
}
// Allocate executable memory either from code range or from the
// OS.
if (isolate_->code_range()->exists()) {
base = isolate_->code_range()->AllocateRawMemory(chunk_size, &chunk_size);
ASSERT(IsAligned(reinterpret_cast<intptr_t>(base),
MemoryChunk::kAlignment));
if (base == NULL) return NULL;
size_ += chunk_size;
// Update executable memory size.
size_executable_ += chunk_size;
} else {
base = AllocateAlignedMemory(chunk_size,
MemoryChunk::kAlignment,
executable,
&reservation);
if (base == NULL) return NULL;
// Update executable memory size.
size_executable_ += reservation.size();
}
#ifdef DEBUG
ZapBlock(base, CodePageGuardStartOffset());
ZapBlock(base + CodePageAreaStartOffset(), body_size);
#endif
area_start = base + CodePageAreaStartOffset();
area_end = area_start + body_size;
} else {
chunk_size = MemoryChunk::kObjectStartOffset + body_size;
base = AllocateAlignedMemory(chunk_size,
MemoryChunk::kAlignment,
executable,
&reservation);
if (base == NULL) return NULL;
#ifdef DEBUG
ZapBlock(base, chunk_size);
#endif
area_start = base + Page::kObjectStartOffset;
area_end = base + chunk_size;
}
isolate_->counters()->memory_allocated()->
Increment(static_cast<int>(chunk_size));
LOG(isolate_, NewEvent("MemoryChunk", base, chunk_size));
if (owner != NULL) {
ObjectSpace space = static_cast<ObjectSpace>(1 << owner->identity());
PerformAllocationCallback(space, kAllocationActionAllocate, chunk_size);
}
MemoryChunk* result = MemoryChunk::Initialize(heap,
base,
chunk_size,
area_start,
area_end,
executable,
owner);
result->set_reserved_memory(&reservation);
return result;
}
Page* MemoryAllocator::AllocatePage(intptr_t size,
PagedSpace* owner,
Executability executable) {
MemoryChunk* chunk = AllocateChunk(size, executable, owner);
if (chunk == NULL) return NULL;
return Page::Initialize(isolate_->heap(), chunk, executable, owner);
}
LargePage* MemoryAllocator::AllocateLargePage(intptr_t object_size,
Space* owner,
Executability executable) {
MemoryChunk* chunk = AllocateChunk(object_size, executable, owner);
if (chunk == NULL) return NULL;
return LargePage::Initialize(isolate_->heap(), chunk);
}
void MemoryAllocator::Free(MemoryChunk* chunk) {
LOG(isolate_, DeleteEvent("MemoryChunk", chunk));
if (chunk->owner() != NULL) {
ObjectSpace space =
static_cast<ObjectSpace>(1 << chunk->owner()->identity());
PerformAllocationCallback(space, kAllocationActionFree, chunk->size());
}
isolate_->heap()->RememberUnmappedPage(
reinterpret_cast<Address>(chunk), chunk->IsEvacuationCandidate());
delete chunk->slots_buffer();
delete chunk->skip_list();
VirtualMemory* reservation = chunk->reserved_memory();
if (reservation->IsReserved()) {
FreeMemory(reservation, chunk->executable());
} else {
FreeMemory(chunk->address(),
chunk->size(),
chunk->executable());
}
}
bool MemoryAllocator::CommitBlock(Address start,
size_t size,
Executability executable) {
if (!VirtualMemory::CommitRegion(start, size, executable)) return false;
#ifdef DEBUG
ZapBlock(start, size);
#endif
isolate_->counters()->memory_allocated()->Increment(static_cast<int>(size));
return true;
}
bool MemoryAllocator::UncommitBlock(Address start, size_t size) {
if (!VirtualMemory::UncommitRegion(start, size)) return false;
isolate_->counters()->memory_allocated()->Decrement(static_cast<int>(size));
return true;
}
void MemoryAllocator::ZapBlock(Address start, size_t size) {
for (size_t s = 0; s + kPointerSize <= size; s += kPointerSize) {
Memory::Address_at(start + s) = kZapValue;
}
}
void MemoryAllocator::PerformAllocationCallback(ObjectSpace space,
AllocationAction action,
size_t size) {
for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) {
MemoryAllocationCallbackRegistration registration =
memory_allocation_callbacks_[i];
if ((registration.space & space) == space &&
(registration.action & action) == action)
registration.callback(space, action, static_cast<int>(size));
}
}
bool MemoryAllocator::MemoryAllocationCallbackRegistered(
MemoryAllocationCallback callback) {
for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) {
if (memory_allocation_callbacks_[i].callback == callback) return true;
}
return false;
}
void MemoryAllocator::AddMemoryAllocationCallback(
MemoryAllocationCallback callback,
ObjectSpace space,
AllocationAction action) {
ASSERT(callback != NULL);
MemoryAllocationCallbackRegistration registration(callback, space, action);
ASSERT(!MemoryAllocator::MemoryAllocationCallbackRegistered(callback));
return memory_allocation_callbacks_.Add(registration);
}
void MemoryAllocator::RemoveMemoryAllocationCallback(
MemoryAllocationCallback callback) {
ASSERT(callback != NULL);
for (int i = 0; i < memory_allocation_callbacks_.length(); ++i) {
if (memory_allocation_callbacks_[i].callback == callback) {
memory_allocation_callbacks_.Remove(i);
return;
}
}
UNREACHABLE();
}
#ifdef DEBUG
void MemoryAllocator::ReportStatistics() {
float pct = static_cast<float>(capacity_ - size_) / capacity_;
PrintF(" capacity: %" V8_PTR_PREFIX "d"
", used: %" V8_PTR_PREFIX "d"
", available: %%%d\n\n",
capacity_, size_, static_cast<int>(pct*100));
}
#endif
int MemoryAllocator::CodePageGuardStartOffset() {
// We are guarding code pages: the first OS page after the header
// will be protected as non-writable.
return RoundUp(Page::kObjectStartOffset, OS::CommitPageSize());
}
int MemoryAllocator::CodePageGuardSize() {
return static_cast<int>(OS::CommitPageSize());
}
int MemoryAllocator::CodePageAreaStartOffset() {
// We are guarding code pages: the first OS page after the header
// will be protected as non-writable.
return CodePageGuardStartOffset() + CodePageGuardSize();
}
int MemoryAllocator::CodePageAreaEndOffset() {
// We are guarding code pages: the last OS page will be protected as
// non-writable.
return Page::kPageSize - static_cast<int>(OS::CommitPageSize());
}
bool MemoryAllocator::CommitCodePage(VirtualMemory* vm,
Address start,
size_t size) {
// Commit page header (not executable).
if (!vm->Commit(start,
CodePageGuardStartOffset(),
false)) {
return false;
}
// Create guard page after the header.
if (!vm->Guard(start + CodePageGuardStartOffset())) {
return false;
}
// Commit page body (executable).
size_t area_size = size - CodePageAreaStartOffset() - CodePageGuardSize();
if (!vm->Commit(start + CodePageAreaStartOffset(),
area_size,
true)) {
return false;
}
// Create guard page after the allocatable area.
if (!vm->Guard(start + CodePageAreaStartOffset() + area_size)) {
return false;
}
return true;
}
// -----------------------------------------------------------------------------
// MemoryChunk implementation
void MemoryChunk::IncrementLiveBytesFromMutator(Address address, int by) {
MemoryChunk* chunk = MemoryChunk::FromAddress(address);
if (!chunk->InNewSpace() && !static_cast<Page*>(chunk)->WasSwept()) {
static_cast<PagedSpace*>(chunk->owner())->IncrementUnsweptFreeBytes(-by);
}
chunk->IncrementLiveBytes(by);
}
// -----------------------------------------------------------------------------
// PagedSpace implementation
PagedSpace::PagedSpace(Heap* heap,
intptr_t max_capacity,
AllocationSpace id,
Executability executable)
: Space(heap, id, executable),
free_list_(this),
was_swept_conservatively_(false),
first_unswept_page_(Page::FromAddress(NULL)),
unswept_free_bytes_(0) {
if (id == CODE_SPACE) {
area_size_ = heap->isolate()->memory_allocator()->
CodePageAreaSize();
} else {
area_size_ = Page::kPageSize - Page::kObjectStartOffset;
}
max_capacity_ = (RoundDown(max_capacity, Page::kPageSize) / Page::kPageSize)
* AreaSize();
accounting_stats_.Clear();
allocation_info_.top = NULL;
allocation_info_.limit = NULL;
anchor_.InitializeAsAnchor(this);
}
bool PagedSpace::SetUp() {
return true;
}
bool PagedSpace::HasBeenSetUp() {
return true;
}
void PagedSpace::TearDown() {
PageIterator iterator(this);
while (iterator.has_next()) {
heap()->isolate()->memory_allocator()->Free(iterator.next());
}
anchor_.set_next_page(&anchor_);
anchor_.set_prev_page(&anchor_);
accounting_stats_.Clear();
}
MaybeObject* PagedSpace::FindObject(Address addr) {
// Note: this function can only be called on precisely swept spaces.
ASSERT(!heap()->mark_compact_collector()->in_use());
if (!Contains(addr)) return Failure::Exception();
Page* p = Page::FromAddress(addr);
HeapObjectIterator it(p, NULL);
for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
Address cur = obj->address();
Address next = cur + obj->Size();
if ((cur <= addr) && (addr < next)) return obj;
}
UNREACHABLE();
return Failure::Exception();
}
bool PagedSpace::CanExpand() {
ASSERT(max_capacity_ % AreaSize() == 0);
if (Capacity() == max_capacity_) return false;
ASSERT(Capacity() < max_capacity_);
// Are we going to exceed capacity for this space?
if ((Capacity() + Page::kPageSize) > max_capacity_) return false;
return true;
}
bool PagedSpace::Expand() {
if (!CanExpand()) return false;
intptr_t size = AreaSize();
if (anchor_.next_page() == &anchor_) {
size = SizeOfFirstPage();
}
Page* p = heap()->isolate()->memory_allocator()->AllocatePage(
size, this, executable());
if (p == NULL) return false;
ASSERT(Capacity() <= max_capacity_);
p->InsertAfter(anchor_.prev_page());
return true;
}
intptr_t PagedSpace::SizeOfFirstPage() {
int size = 0;
switch (identity()) {
case OLD_POINTER_SPACE:
size = 64 * kPointerSize * KB;
break;
case OLD_DATA_SPACE:
size = 192 * KB;
break;
case MAP_SPACE:
size = 128 * KB;
break;
case CELL_SPACE:
size = 96 * KB;
break;
case CODE_SPACE:
if (kPointerSize == 8) {
// On x64 we allocate code pages in a special way (from the reserved
// 2Byte area). That part of the code is not yet upgraded to handle
// small pages.
size = AreaSize();
} else {
size = 384 * KB;
}
break;
default:
UNREACHABLE();
}
return Min(size, AreaSize());
}
int PagedSpace::CountTotalPages() {
PageIterator it(this);
int count = 0;
while (it.has_next()) {
it.next();
count++;
}
return count;
}
void PagedSpace::ReleasePage(Page* page) {
ASSERT(page->LiveBytes() == 0);
ASSERT(AreaSize() == page->area_size());
// Adjust list of unswept pages if the page is the head of the list.
if (first_unswept_page_ == page) {
first_unswept_page_ = page->next_page();
if (first_unswept_page_ == anchor()) {
first_unswept_page_ = Page::FromAddress(NULL);
}
}
if (page->WasSwept()) {
intptr_t size = free_list_.EvictFreeListItems(page);
accounting_stats_.AllocateBytes(size);
ASSERT_EQ(AreaSize(), static_cast<int>(size));
} else {
DecreaseUnsweptFreeBytes(page);
}
if (Page::FromAllocationTop(allocation_info_.top) == page) {
allocation_info_.top = allocation_info_.limit = NULL;
}
page->Unlink();
if (page->IsFlagSet(MemoryChunk::CONTAINS_ONLY_DATA)) {
heap()->isolate()->memory_allocator()->Free(page);
} else {
heap()->QueueMemoryChunkForFree(page);
}
ASSERT(Capacity() > 0);
accounting_stats_.ShrinkSpace(AreaSize());
}
void PagedSpace::ReleaseAllUnusedPages() {
PageIterator it(this);
while (it.has_next()) {
Page* page = it.next();
if (!page->WasSwept()) {
if (page->LiveBytes() == 0) ReleasePage(page);
} else {
HeapObject* obj = HeapObject::FromAddress(page->area_start());
if (obj->IsFreeSpace() &&
FreeSpace::cast(obj)->size() == AreaSize()) {
// Sometimes we allocate memory from free list but don't
// immediately initialize it (e.g. see PagedSpace::ReserveSpace
// called from Heap::ReserveSpace that can cause GC before
// reserved space is actually initialized).
// Thus we can't simply assume that obj represents a valid
// node still owned by a free list
// Instead we should verify that the page is fully covered
// by free list items.
FreeList::SizeStats sizes;
free_list_.CountFreeListItems(page, &sizes);
if (sizes.Total() == AreaSize()) {
ReleasePage(page);
}
}
}
}
heap()->FreeQueuedChunks();
}
#ifdef DEBUG
void PagedSpace::Print() { }
#endif
#ifdef DEBUG
void PagedSpace::Verify(ObjectVisitor* visitor) {
// We can only iterate over the pages if they were swept precisely.
if (was_swept_conservatively_) return;
bool allocation_pointer_found_in_space =
(allocation_info_.top == allocation_info_.limit);
PageIterator page_iterator(this);
while (page_iterator.has_next()) {
Page* page = page_iterator.next();
ASSERT(page->owner() == this);
if (page == Page::FromAllocationTop(allocation_info_.top)) {
allocation_pointer_found_in_space = true;