1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_HEAP_HEAP_H_
6 #define V8_HEAP_HEAP_H_
7
8 #include <atomic>
9 #include <cmath>
10 #include <map>
11 #include <memory>
12 #include <unordered_map>
13 #include <unordered_set>
14 #include <vector>
15
16 // Clients of this interface shouldn't depend on lots of heap internals.
17 // Do not include anything from src/heap here!
18 #include "include/v8-internal.h"
19 #include "include/v8.h"
20 #include "src/base/atomic-utils.h"
21 #include "src/base/enum-set.h"
22 #include "src/base/platform/condition-variable.h"
23 #include "src/builtins/accessors.h"
24 #include "src/common/assert-scope.h"
25 #include "src/common/globals.h"
26 #include "src/heap/allocation-observer.h"
27 #include "src/init/heap-symbols.h"
28 #include "src/objects/allocation-site.h"
29 #include "src/objects/fixed-array.h"
30 #include "src/objects/hash-table.h"
31 #include "src/objects/heap-object.h"
32 #include "src/objects/js-array-buffer.h"
33 #include "src/objects/objects.h"
34 #include "src/objects/smi.h"
35 #include "src/objects/visitors.h"
36 #include "src/roots/roots.h"
37 #include "src/utils/allocation.h"
38 #include "testing/gtest/include/gtest/gtest_prod.h"
39
40 namespace v8 {
41
42 namespace debug {
43 using OutOfMemoryCallback = void (*)(void* data);
44 } // namespace debug
45
46 namespace internal {
47
48 namespace heap {
49 class HeapTester;
50 class TestMemoryAllocatorScope;
51 } // namespace heap
52
53 namespace third_party_heap {
54 class Heap;
55 } // namespace third_party_heap
56
57 class IncrementalMarking;
58 class BackingStore;
59 class JSArrayBuffer;
60 class JSPromise;
61 class NativeContext;
62
63 using v8::MemoryPressureLevel;
64
65 class ArrayBufferCollector;
66 class ArrayBufferSweeper;
67 class BasicMemoryChunk;
68 class CodeLargeObjectSpace;
69 class CollectionBarrier;
70 class ConcurrentMarking;
71 class GCIdleTimeHandler;
72 class GCIdleTimeHeapState;
73 class GCTracer;
74 class GlobalSafepoint;
75 class HeapObjectAllocationTracker;
76 class HeapObjectsFilter;
77 class HeapStats;
78 class Isolate;
79 class JSFinalizationRegistry;
80 class LocalEmbedderHeapTracer;
81 class LocalHeap;
82 class MarkingBarrier;
83 class MemoryAllocator;
84 class MemoryChunk;
85 class MemoryMeasurement;
86 class MemoryReducer;
87 class MinorMarkCompactCollector;
88 class ObjectIterator;
89 class ObjectStats;
90 class Page;
91 class PagedSpace;
92 class ReadOnlyHeap;
93 class RootVisitor;
94 class SafepointScope;
95 class ScavengeJob;
96 class Scavenger;
97 class ScavengerCollector;
98 class SharedReadOnlySpace;
99 class Space;
100 class StressScavengeObserver;
101 class TimedHistogram;
102 class WeakObjectRetainer;
103
104 enum ArrayStorageAllocationMode {
105 DONT_INITIALIZE_ARRAY_ELEMENTS,
106 INITIALIZE_ARRAY_ELEMENTS_WITH_HOLE
107 };
108
109 enum class ClearRecordedSlots { kYes, kNo };
110
111 enum class InvalidateRecordedSlots { kYes, kNo };
112
113 enum class ClearFreedMemoryMode { kClearFreedMemory, kDontClearFreedMemory };
114
115 enum ExternalBackingStoreType { kArrayBuffer, kExternalString, kNumTypes };
116
117 enum class RetainingPathOption { kDefault, kTrackEphemeronPath };
118
119 enum class AllocationOrigin {
120 kGeneratedCode = 0,
121 kRuntime = 1,
122 kGC = 2,
123 kFirstAllocationOrigin = kGeneratedCode,
124 kLastAllocationOrigin = kGC,
125 kNumberOfAllocationOrigins = kLastAllocationOrigin + 1
126 };
127
128 enum class GarbageCollectionReason {
129 kUnknown = 0,
130 kAllocationFailure = 1,
131 kAllocationLimit = 2,
132 kContextDisposal = 3,
133 kCountersExtension = 4,
134 kDebugger = 5,
135 kDeserializer = 6,
136 kExternalMemoryPressure = 7,
137 kFinalizeMarkingViaStackGuard = 8,
138 kFinalizeMarkingViaTask = 9,
139 kFullHashtable = 10,
140 kHeapProfiler = 11,
141 kTask = 12,
142 kLastResort = 13,
143 kLowMemoryNotification = 14,
144 kMakeHeapIterable = 15,
145 kMemoryPressure = 16,
146 kMemoryReducer = 17,
147 kRuntime = 18,
148 kSamplingProfiler = 19,
149 kSnapshotCreator = 20,
150 kTesting = 21,
151 kExternalFinalize = 22,
152 kGlobalAllocationLimit = 23,
153 kMeasureMemory = 24,
154 kBackgroundAllocationFailure = 25,
155 // If you add new items here, then update the incremental_marking_reason,
156 // mark_compact_reason, and scavenge_reason counters in counters.h.
157 // Also update src/tools/metrics/histograms/enums.xml in chromium.
158 };
159
160 enum class YoungGenerationHandling {
161 kRegularScavenge = 0,
162 kFastPromotionDuringScavenge = 1,
163 // Histogram::InspectConstructionArguments in chromium requires us to have at
164 // least three buckets.
165 kUnusedBucket = 2,
166 // If you add new items here, then update the young_generation_handling in
167 // counters.h.
168 // Also update src/tools/metrics/histograms/histograms.xml in chromium.
169 };
170
171 enum class GCIdleTimeAction : uint8_t;
172
173 enum class SkipRoot {
174 kExternalStringTable,
175 kGlobalHandles,
176 kOldGeneration,
177 kStack,
178 kUnserializable,
179 kWeak
180 };
181
182 class StrongRootsEntry {
183 StrongRootsEntry() = default;
184
185 FullObjectSlot start;
186 FullObjectSlot end;
187
188 StrongRootsEntry* prev;
189 StrongRootsEntry* next;
190
191 friend class Heap;
192 };
193
194 class AllocationResult {
195 public:
196 static inline AllocationResult Retry(AllocationSpace space = NEW_SPACE) {
197 return AllocationResult(space);
198 }
199
200 // Implicit constructor from Object.
AllocationResult(Object object)201 AllocationResult(Object object) // NOLINT
202 : object_(object) {
203 // AllocationResults can't return Smis, which are used to represent
204 // failure and the space to retry in.
205 CHECK(!object.IsSmi());
206 }
207
AllocationResult()208 AllocationResult() : object_(Smi::FromInt(NEW_SPACE)) {}
209
IsRetry()210 inline bool IsRetry() { return object_.IsSmi(); }
211 inline HeapObject ToObjectChecked();
212 inline HeapObject ToObject();
213 inline Address ToAddress();
214 inline AllocationSpace RetrySpace();
215
216 template <typename T>
To(T * obj)217 bool To(T* obj) {
218 if (IsRetry()) return false;
219 *obj = T::cast(object_);
220 return true;
221 }
222
223 private:
AllocationResult(AllocationSpace space)224 explicit AllocationResult(AllocationSpace space)
225 : object_(Smi::FromInt(static_cast<int>(space))) {}
226
227 Object object_;
228 };
229
230 STATIC_ASSERT(sizeof(AllocationResult) == kSystemPointerSize);
231
232 #ifdef DEBUG
233 struct CommentStatistic {
234 const char* comment;
235 int size;
236 int count;
ClearCommentStatistic237 void Clear() {
238 comment = nullptr;
239 size = 0;
240 count = 0;
241 }
242 // Must be small, since an iteration is used for lookup.
243 static const int kMaxComments = 64;
244 };
245 #endif
246
247 using EphemeronRememberedSet =
248 std::unordered_map<EphemeronHashTable, std::unordered_set<int>,
249 Object::Hasher>;
250
251 class Heap {
252 public:
253 // Stores ephemeron entries where the EphemeronHashTable is in old-space,
254 // and the key of the entry is in new-space. Such keys do not appear in the
255 // usual OLD_TO_NEW remembered set.
256 EphemeronRememberedSet ephemeron_remembered_set_;
257 enum FindMementoMode { kForRuntime, kForGC };
258
259 enum class HeapGrowingMode { kSlow, kConservative, kMinimal, kDefault };
260
261 enum HeapState {
262 NOT_IN_GC,
263 SCAVENGE,
264 MARK_COMPACT,
265 MINOR_MARK_COMPACT,
266 TEAR_DOWN
267 };
268
269 // Emits GC events for DevTools timeline.
270 class DevToolsTraceEventScope {
271 public:
272 DevToolsTraceEventScope(Heap* heap, const char* event_name,
273 const char* event_type);
274 ~DevToolsTraceEventScope();
275
276 private:
277 Heap* heap_;
278 const char* event_name_;
279 };
280
281 class ExternalMemoryAccounting {
282 public:
total()283 int64_t total() { return total_.load(std::memory_order_relaxed); }
limit()284 int64_t limit() { return limit_.load(std::memory_order_relaxed); }
low_since_mark_compact()285 int64_t low_since_mark_compact() {
286 return low_since_mark_compact_.load(std::memory_order_relaxed);
287 }
288
ResetAfterGC()289 void ResetAfterGC() {
290 set_low_since_mark_compact(total());
291 set_limit(total() + kExternalAllocationSoftLimit);
292 }
293
Update(int64_t delta)294 int64_t Update(int64_t delta) {
295 const int64_t amount =
296 total_.fetch_add(delta, std::memory_order_relaxed) + delta;
297 if (amount < low_since_mark_compact()) {
298 set_low_since_mark_compact(amount);
299 set_limit(amount + kExternalAllocationSoftLimit);
300 }
301 return amount;
302 }
303
AllocatedSinceMarkCompact()304 int64_t AllocatedSinceMarkCompact() {
305 int64_t total_bytes = total();
306 int64_t low_since_mark_compact_bytes = low_since_mark_compact();
307
308 if (total_bytes <= low_since_mark_compact_bytes) {
309 return 0;
310 }
311 return static_cast<uint64_t>(total_bytes - low_since_mark_compact_bytes);
312 }
313
314 private:
set_total(int64_t value)315 void set_total(int64_t value) {
316 total_.store(value, std::memory_order_relaxed);
317 }
318
set_limit(int64_t value)319 void set_limit(int64_t value) {
320 limit_.store(value, std::memory_order_relaxed);
321 }
322
set_low_since_mark_compact(int64_t value)323 void set_low_since_mark_compact(int64_t value) {
324 low_since_mark_compact_.store(value, std::memory_order_relaxed);
325 }
326
327 // The amount of external memory registered through the API.
328 std::atomic<int64_t> total_{0};
329
330 // The limit when to trigger memory pressure from the API.
331 std::atomic<int64_t> limit_{kExternalAllocationSoftLimit};
332
333 // Caches the amount of external memory registered at the last MC.
334 std::atomic<int64_t> low_since_mark_compact_{0};
335 };
336
337 using PretenuringFeedbackMap =
338 std::unordered_map<AllocationSite, size_t, Object::Hasher>;
339
340 // Taking this mutex prevents the GC from entering a phase that relocates
341 // object references.
relocation_mutex()342 base::Mutex* relocation_mutex() { return &relocation_mutex_; }
343
344 // Support for context snapshots. After calling this we have a linear
345 // space to write objects in each space.
346 struct Chunk {
347 uint32_t size;
348 Address start;
349 Address end;
350 };
351 using Reservation = std::vector<Chunk>;
352
353 #if V8_OS_ANDROID
354 // Don't apply pointer multiplier on Android since it has no swap space and
355 // should instead adapt it's heap size based on available physical memory.
356 static const int kPointerMultiplier = 1;
357 static const int kHeapLimitMultiplier = 1;
358 #else
359 static const int kPointerMultiplier = kTaggedSize / 4;
360 // The heap limit needs to be computed based on the system pointer size
361 // because we want a pointer-compressed heap to have larger limit than
362 // an orinary 32-bit which that is contrained by 2GB virtual address space.
363 static const int kHeapLimitMultiplier = kSystemPointerSize / 4;
364 #endif
365
366 static const size_t kMaxInitialOldGenerationSize =
367 256 * MB * kHeapLimitMultiplier;
368
369 // These constants control heap configuration based on the physical memory.
370 static constexpr size_t kPhysicalMemoryToOldGenerationRatio = 4;
371 // Young generation size is the same for compressed heaps and 32-bit heaps.
372 static constexpr size_t kOldGenerationToSemiSpaceRatio =
373 128 * kHeapLimitMultiplier / kPointerMultiplier;
374 static constexpr size_t kOldGenerationToSemiSpaceRatioLowMemory =
375 256 * kHeapLimitMultiplier / kPointerMultiplier;
376 static constexpr size_t kOldGenerationLowMemory =
377 128 * MB * kHeapLimitMultiplier;
378 static constexpr size_t kNewLargeObjectSpaceToSemiSpaceRatio = 1;
379 static constexpr size_t kMinSemiSpaceSize = 512 * KB * kPointerMultiplier;
380 static constexpr size_t kMaxSemiSpaceSize = 8192 * KB * kPointerMultiplier;
381
382 STATIC_ASSERT(kMinSemiSpaceSize % (1 << kPageSizeBits) == 0);
383 STATIC_ASSERT(kMaxSemiSpaceSize % (1 << kPageSizeBits) == 0);
384
385 static const int kTraceRingBufferSize = 512;
386 static const int kStacktraceBufferSize = 512;
387
388 static const int kNoGCFlags = 0;
389 static const int kReduceMemoryFootprintMask = 1;
390 // GCs that are forced, either through testing configurations (requring
391 // --expose-gc) or through DevTools (using LowMemoryNotificaton).
392 static const int kForcedGC = 2;
393
394 // The minimum size of a HeapObject on the heap.
395 static const int kMinObjectSizeInTaggedWords = 2;
396
397 static const int kMinPromotedPercentForFastPromotionMode = 90;
398
399 STATIC_ASSERT(static_cast<int>(RootIndex::kUndefinedValue) ==
400 Internals::kUndefinedValueRootIndex);
401 STATIC_ASSERT(static_cast<int>(RootIndex::kTheHoleValue) ==
402 Internals::kTheHoleValueRootIndex);
403 STATIC_ASSERT(static_cast<int>(RootIndex::kNullValue) ==
404 Internals::kNullValueRootIndex);
405 STATIC_ASSERT(static_cast<int>(RootIndex::kTrueValue) ==
406 Internals::kTrueValueRootIndex);
407 STATIC_ASSERT(static_cast<int>(RootIndex::kFalseValue) ==
408 Internals::kFalseValueRootIndex);
409 STATIC_ASSERT(static_cast<int>(RootIndex::kempty_string) ==
410 Internals::kEmptyStringRootIndex);
411
412 // Calculates the maximum amount of filler that could be required by the
413 // given alignment.
414 V8_EXPORT_PRIVATE static int GetMaximumFillToAlign(
415 AllocationAlignment alignment);
416 // Calculates the actual amount of filler required for a given address at the
417 // given alignment.
418 V8_EXPORT_PRIVATE static int GetFillToAlign(Address address,
419 AllocationAlignment alignment);
420
421 // Returns the size of the initial area of a code-range, which is marked
422 // writable and reserved to contain unwind information.
423 static size_t GetCodeRangeReservedAreaSize();
424
425 [[noreturn]] void FatalProcessOutOfMemory(const char* location);
426
427 // Checks whether the space is valid.
428 static bool IsValidAllocationSpace(AllocationSpace space);
429
430 // Zapping is needed for verify heap, and always done in debug builds.
ShouldZapGarbage()431 static inline bool ShouldZapGarbage() {
432 #ifdef DEBUG
433 return true;
434 #else
435 #ifdef VERIFY_HEAP
436 return FLAG_verify_heap;
437 #else
438 return false;
439 #endif
440 #endif
441 }
442
443 // Helper function to get the bytecode flushing mode based on the flags. This
444 // is required because it is not safe to acess flags in concurrent marker.
GetBytecodeFlushMode()445 static inline BytecodeFlushMode GetBytecodeFlushMode() {
446 if (FLAG_stress_flush_bytecode) {
447 return BytecodeFlushMode::kStressFlushBytecode;
448 } else if (FLAG_flush_bytecode) {
449 return BytecodeFlushMode::kFlushBytecode;
450 }
451 return BytecodeFlushMode::kDoNotFlushBytecode;
452 }
453
ZapValue()454 static uintptr_t ZapValue() {
455 return FLAG_clear_free_memory ? kClearedFreeMemoryValue : kZapValue;
456 }
457
IsYoungGenerationCollector(GarbageCollector collector)458 static inline bool IsYoungGenerationCollector(GarbageCollector collector) {
459 return collector == SCAVENGER || collector == MINOR_MARK_COMPACTOR;
460 }
461
YoungGenerationCollector()462 static inline GarbageCollector YoungGenerationCollector() {
463 #if ENABLE_MINOR_MC
464 return (FLAG_minor_mc) ? MINOR_MARK_COMPACTOR : SCAVENGER;
465 #else
466 return SCAVENGER;
467 #endif // ENABLE_MINOR_MC
468 }
469
CollectorName(GarbageCollector collector)470 static inline const char* CollectorName(GarbageCollector collector) {
471 switch (collector) {
472 case SCAVENGER:
473 return "Scavenger";
474 case MARK_COMPACTOR:
475 return "Mark-Compact";
476 case MINOR_MARK_COMPACTOR:
477 return "Minor Mark-Compact";
478 }
479 return "Unknown collector";
480 }
481
482 // Copy block of memory from src to dst. Size of block should be aligned
483 // by pointer size.
484 static inline void CopyBlock(Address dst, Address src, int byte_size);
485
486 // Executes generational and/or marking write barrier for a [start, end) range
487 // of non-weak slots inside |object|.
488 template <typename TSlot>
489 V8_EXPORT_PRIVATE void WriteBarrierForRange(HeapObject object, TSlot start,
490 TSlot end);
491
492 V8_EXPORT_PRIVATE static void WriteBarrierForCodeSlow(Code host);
493
494 V8_EXPORT_PRIVATE static void GenerationalBarrierSlow(HeapObject object,
495 Address slot,
496 HeapObject value);
497 V8_EXPORT_PRIVATE inline void RecordEphemeronKeyWrite(
498 EphemeronHashTable table, Address key_slot);
499 V8_EXPORT_PRIVATE static void EphemeronKeyWriteBarrierFromCode(
500 Address raw_object, Address address, Isolate* isolate);
501 V8_EXPORT_PRIVATE static void GenerationalBarrierForCodeSlow(
502 Code host, RelocInfo* rinfo, HeapObject value);
503 V8_EXPORT_PRIVATE static bool PageFlagsAreConsistent(HeapObject object);
504
505 // Notifies the heap that is ok to start marking or other activities that
506 // should not happen during deserialization.
507 void NotifyDeserializationComplete();
508
509 void NotifyBootstrapComplete();
510
511 void NotifyOldGenerationExpansion(AllocationSpace space, MemoryChunk* chunk);
512
513 inline Address* NewSpaceAllocationTopAddress();
514 inline Address* NewSpaceAllocationLimitAddress();
515 inline Address* OldSpaceAllocationTopAddress();
516 inline Address* OldSpaceAllocationLimitAddress();
517
518 // Move len non-weak tagged elements from src_slot to dst_slot of dst_object.
519 // The source and destination memory ranges can overlap.
520 V8_EXPORT_PRIVATE void MoveRange(HeapObject dst_object, ObjectSlot dst_slot,
521 ObjectSlot src_slot, int len,
522 WriteBarrierMode mode);
523
524 // Copy len non-weak tagged elements from src_slot to dst_slot of dst_object.
525 // The source and destination memory ranges must not overlap.
526 template <typename TSlot>
527 void CopyRange(HeapObject dst_object, TSlot dst_slot, TSlot src_slot, int len,
528 WriteBarrierMode mode);
529
530 // Initialize a filler object to keep the ability to iterate over the heap
531 // when introducing gaps within pages. If slots could have been recorded in
532 // the freed area, then pass ClearRecordedSlots::kYes as the mode. Otherwise,
533 // pass ClearRecordedSlots::kNo. Clears memory if clearing slots.
534 V8_EXPORT_PRIVATE HeapObject CreateFillerObjectAt(
535 Address addr, int size, ClearRecordedSlots clear_slots_mode);
536
537 void CreateFillerObjectAtBackground(Address addr, int size,
538 ClearFreedMemoryMode clear_memory_mode);
539
540 template <typename T>
541 void CreateFillerForArray(T object, int elements_to_trim, int bytes_to_trim);
542
543 bool CanMoveObjectStart(HeapObject object);
544
545 bool IsImmovable(HeapObject object);
546
547 V8_EXPORT_PRIVATE static bool IsLargeObject(HeapObject object);
548
549 // This method supports the deserialization allocator. All allocations
550 // are word-aligned. The method should never fail to allocate since the
551 // total space requirements of the deserializer are known at build time.
552 inline Address DeserializerAllocate(AllocationType type, int size_in_bytes);
553
554 // Trim the given array from the left. Note that this relocates the object
555 // start and hence is only valid if there is only a single reference to it.
556 V8_EXPORT_PRIVATE FixedArrayBase LeftTrimFixedArray(FixedArrayBase obj,
557 int elements_to_trim);
558
559 // Trim the given array from the right.
560 V8_EXPORT_PRIVATE void RightTrimFixedArray(FixedArrayBase obj,
561 int elements_to_trim);
562 void RightTrimWeakFixedArray(WeakFixedArray obj, int elements_to_trim);
563
564 // Converts the given boolean condition to JavaScript boolean value.
565 inline Oddball ToBoolean(bool condition);
566
567 // Notify the heap that a context has been disposed.
568 V8_EXPORT_PRIVATE int NotifyContextDisposed(bool dependant_context);
569
set_native_contexts_list(Object object)570 void set_native_contexts_list(Object object) {
571 native_contexts_list_ = object;
572 }
native_contexts_list()573 Object native_contexts_list() const { return native_contexts_list_; }
574
set_allocation_sites_list(Object object)575 void set_allocation_sites_list(Object object) {
576 allocation_sites_list_ = object;
577 }
allocation_sites_list()578 Object allocation_sites_list() { return allocation_sites_list_; }
579
set_dirty_js_finalization_registries_list(Object object)580 void set_dirty_js_finalization_registries_list(Object object) {
581 dirty_js_finalization_registries_list_ = object;
582 }
dirty_js_finalization_registries_list()583 Object dirty_js_finalization_registries_list() {
584 return dirty_js_finalization_registries_list_;
585 }
set_dirty_js_finalization_registries_list_tail(Object object)586 void set_dirty_js_finalization_registries_list_tail(Object object) {
587 dirty_js_finalization_registries_list_tail_ = object;
588 }
dirty_js_finalization_registries_list_tail()589 Object dirty_js_finalization_registries_list_tail() {
590 return dirty_js_finalization_registries_list_tail_;
591 }
592
593 // Used in CreateAllocationSiteStub and the (de)serializer.
allocation_sites_list_address()594 Address allocation_sites_list_address() {
595 return reinterpret_cast<Address>(&allocation_sites_list_);
596 }
597
598 // Traverse all the allocaions_sites [nested_site and weak_next] in the list
599 // and foreach call the visitor
600 void ForeachAllocationSite(
601 Object list, const std::function<void(AllocationSite)>& visitor);
602
603 // Number of mark-sweeps.
ms_count()604 int ms_count() const { return ms_count_; }
605
606 // Checks whether the given object is allowed to be migrated from it's
607 // current space into the given destination space. Used for debugging.
608 bool AllowedToBeMigrated(Map map, HeapObject object, AllocationSpace dest);
609
610 void CheckHandleCount();
611
612 // Number of "runtime allocations" done so far.
allocations_count()613 uint32_t allocations_count() { return allocations_count_; }
614
615 // Print short heap statistics.
616 void PrintShortHeapStatistics();
617
618 // Print statistics of freelists of old_space:
619 // with FLAG_trace_gc_freelists: summary of each FreeListCategory.
620 // with FLAG_trace_gc_freelists_verbose: also prints the statistics of each
621 // FreeListCategory of each page.
622 void PrintFreeListsStats();
623
624 // Dump heap statistics in JSON format.
625 void DumpJSONHeapStatistics(std::stringstream& stream);
626
write_protect_code_memory()627 bool write_protect_code_memory() const { return write_protect_code_memory_; }
628
code_space_memory_modification_scope_depth()629 uintptr_t code_space_memory_modification_scope_depth() {
630 return code_space_memory_modification_scope_depth_;
631 }
632
increment_code_space_memory_modification_scope_depth()633 void increment_code_space_memory_modification_scope_depth() {
634 code_space_memory_modification_scope_depth_++;
635 }
636
decrement_code_space_memory_modification_scope_depth()637 void decrement_code_space_memory_modification_scope_depth() {
638 code_space_memory_modification_scope_depth_--;
639 }
640
641 void UnprotectAndRegisterMemoryChunk(MemoryChunk* chunk);
642 V8_EXPORT_PRIVATE void UnprotectAndRegisterMemoryChunk(HeapObject object);
643 void UnregisterUnprotectedMemoryChunk(MemoryChunk* chunk);
644 V8_EXPORT_PRIVATE void ProtectUnprotectedMemoryChunks();
645
EnableUnprotectedMemoryChunksRegistry()646 void EnableUnprotectedMemoryChunksRegistry() {
647 unprotected_memory_chunks_registry_enabled_ = true;
648 }
649
DisableUnprotectedMemoryChunksRegistry()650 void DisableUnprotectedMemoryChunksRegistry() {
651 unprotected_memory_chunks_registry_enabled_ = false;
652 }
653
unprotected_memory_chunks_registry_enabled()654 bool unprotected_memory_chunks_registry_enabled() {
655 return unprotected_memory_chunks_registry_enabled_;
656 }
657
gc_state()658 inline HeapState gc_state() const {
659 return gc_state_.load(std::memory_order_relaxed);
660 }
661 void SetGCState(HeapState state);
IsTearingDown()662 bool IsTearingDown() const { return gc_state() == TEAR_DOWN; }
force_oom()663 bool force_oom() const { return force_oom_; }
664
IsInGCPostProcessing()665 inline bool IsInGCPostProcessing() { return gc_post_processing_depth_ > 0; }
666
667 // If an object has an AllocationMemento trailing it, return it, otherwise
668 // return a null AllocationMemento.
669 template <FindMementoMode mode>
670 inline AllocationMemento FindAllocationMemento(Map map, HeapObject object);
671
672 // Requests collection and blocks until GC is finished.
673 void RequestCollectionBackground(LocalHeap* local_heap);
674
675 //
676 // Support for the API.
677 //
678
679 void CreateApiObjects();
680
681 // Implements the corresponding V8 API function.
682 bool IdleNotification(double deadline_in_seconds);
683 bool IdleNotification(int idle_time_in_ms);
684
685 V8_EXPORT_PRIVATE void MemoryPressureNotification(MemoryPressureLevel level,
686 bool is_isolate_locked);
687 void CheckMemoryPressure();
688
689 V8_EXPORT_PRIVATE void AddNearHeapLimitCallback(v8::NearHeapLimitCallback,
690 void* data);
691 V8_EXPORT_PRIVATE void RemoveNearHeapLimitCallback(
692 v8::NearHeapLimitCallback callback, size_t heap_limit);
693 V8_EXPORT_PRIVATE void AutomaticallyRestoreInitialHeapLimit(
694 double threshold_percent);
695
696 void AppendArrayBufferExtension(JSArrayBuffer object,
697 ArrayBufferExtension* extension);
698
safepoint()699 GlobalSafepoint* safepoint() { return safepoint_.get(); }
700
701 V8_EXPORT_PRIVATE double MonotonicallyIncreasingTimeInMs();
702
703 void VerifyNewSpaceTop();
704
705 void RecordStats(HeapStats* stats, bool take_snapshot = false);
706
707 bool MeasureMemory(std::unique_ptr<v8::MeasureMemoryDelegate> delegate,
708 v8::MeasureMemoryExecution execution);
709
710 std::unique_ptr<v8::MeasureMemoryDelegate> MeasureMemoryDelegate(
711 Handle<NativeContext> context, Handle<JSPromise> promise,
712 v8::MeasureMemoryMode mode);
713
714 // Check new space expansion criteria and expand semispaces if it was hit.
715 void CheckNewSpaceExpansionCriteria();
716
717 void VisitExternalResources(v8::ExternalResourceVisitor* visitor);
718
719 // An object should be promoted if the object has survived a
720 // scavenge operation.
721 inline bool ShouldBePromoted(Address old_address);
722
723 void IncrementDeferredCount(v8::Isolate::UseCounterFeature feature);
724
725 inline int NextScriptId();
726 inline int NextDebuggingId();
727 inline int GetNextTemplateSerialNumber();
728
729 void SetSerializedObjects(FixedArray objects);
730 void SetSerializedGlobalProxySizes(FixedArray sizes);
731
732 void SetBasicBlockProfilingData(Handle<ArrayList> list);
733
734 // For post mortem debugging.
735 void RememberUnmappedPage(Address page, bool compacted);
736
external_memory_hard_limit()737 int64_t external_memory_hard_limit() { return max_old_generation_size() / 2; }
738
739 V8_INLINE int64_t external_memory();
740 V8_EXPORT_PRIVATE int64_t external_memory_limit();
741 V8_INLINE int64_t update_external_memory(int64_t delta);
742
743 V8_EXPORT_PRIVATE size_t YoungArrayBufferBytes();
744 V8_EXPORT_PRIVATE size_t OldArrayBufferBytes();
745
backing_store_bytes()746 size_t backing_store_bytes() const { return backing_store_bytes_; }
747
748 void CompactWeakArrayLists(AllocationType allocation);
749
750 V8_EXPORT_PRIVATE void AddRetainedMap(Handle<NativeContext> context,
751 Handle<Map> map);
752
753 // This event is triggered after successful allocation of a new object made
754 // by runtime. Allocations of target space for object evacuation do not
755 // trigger the event. In order to track ALL allocations one must turn off
756 // FLAG_inline_new.
757 inline void OnAllocationEvent(HeapObject object, int size_in_bytes);
758
759 // This event is triggered after object is moved to a new place.
760 void OnMoveEvent(HeapObject target, HeapObject source, int size_in_bytes);
761
762 inline bool CanAllocateInReadOnlySpace();
deserialization_complete()763 bool deserialization_complete() const { return deserialization_complete_; }
764
765 bool HasLowAllocationRate();
766 bool HasHighFragmentation();
767 bool HasHighFragmentation(size_t used, size_t committed);
768
769 void ActivateMemoryReducerIfNeeded();
770
771 V8_EXPORT_PRIVATE bool ShouldOptimizeForMemoryUsage();
772
HighMemoryPressure()773 bool HighMemoryPressure() {
774 return memory_pressure_level_.load(std::memory_order_relaxed) !=
775 MemoryPressureLevel::kNone;
776 }
777
778 bool CollectionRequested();
779
780 void CheckCollectionRequested();
781
RestoreHeapLimit(size_t heap_limit)782 void RestoreHeapLimit(size_t heap_limit) {
783 // Do not set the limit lower than the live size + some slack.
784 size_t min_limit = SizeOfObjects() + SizeOfObjects() / 4;
785 set_max_old_generation_size(
786 Min(max_old_generation_size(), Max(heap_limit, min_limit)));
787 }
788
789 // ===========================================================================
790 // Initialization. ===========================================================
791 // ===========================================================================
792
793 void ConfigureHeap(const v8::ResourceConstraints& constraints);
794 void ConfigureHeapDefault();
795
796 // Prepares the heap, setting up for deserialization.
797 void SetUp();
798
799 // Sets read-only heap and space.
800 void SetUpFromReadOnlyHeap(ReadOnlyHeap* ro_heap);
801
802 void ReplaceReadOnlySpace(SharedReadOnlySpace* shared_ro_space);
803
804 // Sets up the heap memory without creating any objects.
805 void SetUpSpaces();
806
807 // (Re-)Initialize hash seed from flag or RNG.
808 void InitializeHashSeed();
809
810 // Bootstraps the object heap with the core set of objects required to run.
811 // Returns whether it succeeded.
812 bool CreateHeapObjects();
813
814 // Create ObjectStats if live_object_stats_ or dead_object_stats_ are nullptr.
815 void CreateObjectStats();
816
817 // Sets the TearDown state, so no new GC tasks get posted.
818 void StartTearDown();
819
820 // Destroys all memory allocated by the heap.
821 void TearDown();
822
823 // Returns whether SetUp has been called.
824 bool HasBeenSetUp() const;
825
826 // ===========================================================================
827 // Getters for spaces. =======================================================
828 // ===========================================================================
829
830 inline Address NewSpaceTop();
831
new_space()832 NewSpace* new_space() { return new_space_; }
old_space()833 OldSpace* old_space() { return old_space_; }
code_space()834 CodeSpace* code_space() { return code_space_; }
map_space()835 MapSpace* map_space() { return map_space_; }
lo_space()836 OldLargeObjectSpace* lo_space() { return lo_space_; }
code_lo_space()837 CodeLargeObjectSpace* code_lo_space() { return code_lo_space_; }
new_lo_space()838 NewLargeObjectSpace* new_lo_space() { return new_lo_space_; }
read_only_space()839 ReadOnlySpace* read_only_space() { return read_only_space_; }
840
841 inline PagedSpace* paged_space(int idx);
842 inline Space* space(int idx);
843
844 // ===========================================================================
845 // Getters to other components. ==============================================
846 // ===========================================================================
847
tracer()848 GCTracer* tracer() { return tracer_.get(); }
849
memory_allocator()850 MemoryAllocator* memory_allocator() { return memory_allocator_.get(); }
memory_allocator()851 const MemoryAllocator* memory_allocator() const {
852 return memory_allocator_.get();
853 }
854
855 inline Isolate* isolate();
856
mark_compact_collector()857 MarkCompactCollector* mark_compact_collector() {
858 return mark_compact_collector_.get();
859 }
860
minor_mark_compact_collector()861 MinorMarkCompactCollector* minor_mark_compact_collector() {
862 return minor_mark_compact_collector_;
863 }
864
array_buffer_sweeper()865 ArrayBufferSweeper* array_buffer_sweeper() {
866 return array_buffer_sweeper_.get();
867 }
868
869 const base::AddressRegion& code_range();
870
871 // ===========================================================================
872 // Root set access. ==========================================================
873 // ===========================================================================
874
875 // Shortcut to the roots table stored in the Isolate.
876 V8_INLINE RootsTable& roots_table();
877
878 // Heap root getters.
879 #define ROOT_ACCESSOR(type, name, CamelName) inline type name();
880 MUTABLE_ROOT_LIST(ROOT_ACCESSOR)
881 #undef ROOT_ACCESSOR
882
883 V8_INLINE void SetRootMaterializedObjects(FixedArray objects);
884 V8_INLINE void SetRootScriptList(Object value);
885 V8_INLINE void SetRootNoScriptSharedFunctionInfos(Object value);
886 V8_INLINE void SetMessageListeners(TemplateList value);
887 V8_INLINE void SetPendingOptimizeForTestBytecode(Object bytecode);
888
889 StrongRootsEntry* RegisterStrongRoots(FullObjectSlot start,
890 FullObjectSlot end);
891 void UnregisterStrongRoots(StrongRootsEntry* entry);
892 void UpdateStrongRoots(StrongRootsEntry* entry, FullObjectSlot start,
893 FullObjectSlot end);
894
895 void SetBuiltinsConstantsTable(FixedArray cache);
896 void SetDetachedContexts(WeakArrayList detached_contexts);
897
898 // A full copy of the interpreter entry trampoline, used as a template to
899 // create copies of the builtin at runtime. The copies are used to create
900 // better profiling information for ticks in bytecode execution. Note that
901 // this is always a copy of the full builtin, i.e. not the off-heap
902 // trampoline.
903 // See also: FLAG_interpreted_frames_native_stack.
904 void SetInterpreterEntryTrampolineForProfiling(Code code);
905
906 void EnqueueDirtyJSFinalizationRegistry(
907 JSFinalizationRegistry finalization_registry,
908 std::function<void(HeapObject object, ObjectSlot slot, Object target)>
909 gc_notify_updated_slot);
910
911 MaybeHandle<JSFinalizationRegistry> DequeueDirtyJSFinalizationRegistry();
912
913 // Called from Heap::NotifyContextDisposed to remove all
914 // FinalizationRegistries with {context} from the dirty list when the context
915 // e.g. navigates away or is detached. If the dirty list is empty afterwards,
916 // the cleanup task is aborted if needed.
917 void RemoveDirtyFinalizationRegistriesOnContext(NativeContext context);
918
919 inline bool HasDirtyJSFinalizationRegistries();
920
921 void PostFinalizationRegistryCleanupTaskIfNeeded();
922
set_is_finalization_registry_cleanup_task_posted(bool posted)923 void set_is_finalization_registry_cleanup_task_posted(bool posted) {
924 is_finalization_registry_cleanup_task_posted_ = posted;
925 }
926
is_finalization_registry_cleanup_task_posted()927 bool is_finalization_registry_cleanup_task_posted() {
928 return is_finalization_registry_cleanup_task_posted_;
929 }
930
931 V8_EXPORT_PRIVATE void KeepDuringJob(Handle<JSReceiver> target);
932 void ClearKeptObjects();
933
934 // ===========================================================================
935 // Inline allocation. ========================================================
936 // ===========================================================================
937
938 // Indicates whether inline bump-pointer allocation has been disabled.
inline_allocation_disabled()939 bool inline_allocation_disabled() { return inline_allocation_disabled_; }
940
941 // Switch whether inline bump-pointer allocation should be used.
942 V8_EXPORT_PRIVATE void EnableInlineAllocation();
943 V8_EXPORT_PRIVATE void DisableInlineAllocation();
944
945 // ===========================================================================
946 // Methods triggering GCs. ===================================================
947 // ===========================================================================
948
949 // Performs garbage collection operation.
950 // Returns whether there is a chance that another major GC could
951 // collect more garbage.
952 V8_EXPORT_PRIVATE bool CollectGarbage(
953 AllocationSpace space, GarbageCollectionReason gc_reason,
954 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
955
956 // Performs a full garbage collection.
957 V8_EXPORT_PRIVATE void CollectAllGarbage(
958 int flags, GarbageCollectionReason gc_reason,
959 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
960
961 // Last hope GC, should try to squeeze as much as possible.
962 V8_EXPORT_PRIVATE void CollectAllAvailableGarbage(
963 GarbageCollectionReason gc_reason);
964
965 // Precise garbage collection that potentially finalizes already running
966 // incremental marking before performing an atomic garbage collection.
967 // Only use if absolutely necessary or in tests to avoid floating garbage!
968 V8_EXPORT_PRIVATE void PreciseCollectAllGarbage(
969 int flags, GarbageCollectionReason gc_reason,
970 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
971
972 // Reports and external memory pressure event, either performs a major GC or
973 // completes incremental marking in order to free external resources.
974 void ReportExternalMemoryPressure();
975
976 using GetExternallyAllocatedMemoryInBytesCallback =
977 v8::Isolate::GetExternallyAllocatedMemoryInBytesCallback;
978
SetGetExternallyAllocatedMemoryInBytesCallback(GetExternallyAllocatedMemoryInBytesCallback callback)979 void SetGetExternallyAllocatedMemoryInBytesCallback(
980 GetExternallyAllocatedMemoryInBytesCallback callback) {
981 external_memory_callback_ = callback;
982 }
983
984 // Invoked when GC was requested via the stack guard.
985 void HandleGCRequest();
986
987 // ===========================================================================
988 // Builtins. =================================================================
989 // ===========================================================================
990
991 V8_EXPORT_PRIVATE Code builtin(int index);
992 Address builtin_address(int index);
993 void set_builtin(int index, Code builtin);
994
995 // ===========================================================================
996 // Iterators. ================================================================
997 // ===========================================================================
998
999 // None of these methods iterate over the read-only roots. To do this use
1000 // ReadOnlyRoots::Iterate. Read-only root iteration is not necessary for
1001 // garbage collection and is usually only performed as part of
1002 // (de)serialization or heap verification.
1003
1004 // Iterates over the strong roots and the weak roots.
1005 void IterateRoots(RootVisitor* v, base::EnumSet<SkipRoot> options);
1006 // Iterates over entries in the smi roots list. Only interesting to the
1007 // serializer/deserializer, since GC does not care about smis.
1008 void IterateSmiRoots(RootVisitor* v);
1009 // Iterates over weak string tables.
1010 void IterateWeakRoots(RootVisitor* v, base::EnumSet<SkipRoot> options);
1011 void IterateWeakGlobalHandles(RootVisitor* v);
1012 void IterateBuiltins(RootVisitor* v);
1013 void IterateStackRoots(RootVisitor* v);
1014
1015 // ===========================================================================
1016 // Store buffer API. =========================================================
1017 // ===========================================================================
1018
1019 // Used for query incremental marking status in generated code.
IsMarkingFlagAddress()1020 Address* IsMarkingFlagAddress() {
1021 return reinterpret_cast<Address*>(&is_marking_flag_);
1022 }
1023
SetIsMarkingFlag(uint8_t flag)1024 void SetIsMarkingFlag(uint8_t flag) { is_marking_flag_ = flag; }
1025
1026 V8_EXPORT_PRIVATE Address* store_buffer_top_address();
1027 static intptr_t store_buffer_mask_constant();
1028 static Address store_buffer_overflow_function_address();
1029
1030 void ClearRecordedSlot(HeapObject object, ObjectSlot slot);
1031 void ClearRecordedSlotRange(Address start, Address end);
1032 static int InsertIntoRememberedSetFromCode(MemoryChunk* chunk, Address slot);
1033
1034 #ifdef DEBUG
1035 void VerifyClearedSlot(HeapObject object, ObjectSlot slot);
1036 void VerifySlotRangeHasNoRecordedSlots(Address start, Address end);
1037 #endif
1038
1039 // ===========================================================================
1040 // Incremental marking API. ==================================================
1041 // ===========================================================================
1042
GCFlagsForIncrementalMarking()1043 int GCFlagsForIncrementalMarking() {
1044 return ShouldOptimizeForMemoryUsage() ? kReduceMemoryFootprintMask
1045 : kNoGCFlags;
1046 }
1047
1048 // Start incremental marking and ensure that idle time handler can perform
1049 // incremental steps.
1050 V8_EXPORT_PRIVATE void StartIdleIncrementalMarking(
1051 GarbageCollectionReason gc_reason,
1052 GCCallbackFlags gc_callback_flags = GCCallbackFlags::kNoGCCallbackFlags);
1053
1054 // Starts incremental marking assuming incremental marking is currently
1055 // stopped.
1056 V8_EXPORT_PRIVATE void StartIncrementalMarking(
1057 int gc_flags, GarbageCollectionReason gc_reason,
1058 GCCallbackFlags gc_callback_flags = GCCallbackFlags::kNoGCCallbackFlags);
1059
1060 void StartIncrementalMarkingIfAllocationLimitIsReached(
1061 int gc_flags,
1062 GCCallbackFlags gc_callback_flags = GCCallbackFlags::kNoGCCallbackFlags);
1063 void StartIncrementalMarkingIfAllocationLimitIsReachedBackground();
1064
1065 void FinalizeIncrementalMarkingIfComplete(GarbageCollectionReason gc_reason);
1066 // Synchronously finalizes incremental marking.
1067 V8_EXPORT_PRIVATE void FinalizeIncrementalMarkingAtomically(
1068 GarbageCollectionReason gc_reason);
1069
incremental_marking()1070 IncrementalMarking* incremental_marking() {
1071 return incremental_marking_.get();
1072 }
1073
marking_barrier()1074 MarkingBarrier* marking_barrier() { return marking_barrier_.get(); }
1075
1076 // ===========================================================================
1077 // Concurrent marking API. ===================================================
1078 // ===========================================================================
1079
concurrent_marking()1080 ConcurrentMarking* concurrent_marking() { return concurrent_marking_.get(); }
1081
1082 // The runtime uses this function to notify potentially unsafe object layout
1083 // changes that require special synchronization with the concurrent marker.
1084 // The old size is the size of the object before layout change.
1085 // By default recorded slots in the object are invalidated. Pass
1086 // InvalidateRecordedSlots::kNo if this is not necessary or to perform this
1087 // manually.
1088 void NotifyObjectLayoutChange(
1089 HeapObject object, const DisallowHeapAllocation&,
1090 InvalidateRecordedSlots invalidate_recorded_slots =
1091 InvalidateRecordedSlots::kYes);
1092
1093 #ifdef VERIFY_HEAP
1094 // This function checks that either
1095 // - the map transition is safe,
1096 // - or it was communicated to GC using NotifyObjectLayoutChange.
1097 V8_EXPORT_PRIVATE void VerifyObjectLayoutChange(HeapObject object,
1098 Map new_map);
1099 #endif
1100
1101 // ===========================================================================
1102 // Deoptimization support API. ===============================================
1103 // ===========================================================================
1104
1105 // Setters for code offsets of well-known deoptimization targets.
1106 void SetArgumentsAdaptorDeoptPCOffset(int pc_offset);
1107 void SetConstructStubCreateDeoptPCOffset(int pc_offset);
1108 void SetConstructStubInvokeDeoptPCOffset(int pc_offset);
1109 void SetInterpreterEntryReturnPCOffset(int pc_offset);
1110
1111 // Invalidates references in the given {code} object that are referenced
1112 // transitively from the deoptimization data. Mutates write-protected code.
1113 void InvalidateCodeDeoptimizationData(Code code);
1114
1115 void DeoptMarkedAllocationSites();
1116
1117 bool DeoptMaybeTenuredAllocationSites();
1118
1119 // ===========================================================================
1120 // Embedder heap tracer support. =============================================
1121 // ===========================================================================
1122
local_embedder_heap_tracer()1123 LocalEmbedderHeapTracer* local_embedder_heap_tracer() const {
1124 return local_embedder_heap_tracer_.get();
1125 }
1126
1127 V8_EXPORT_PRIVATE void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
1128 EmbedderHeapTracer* GetEmbedderHeapTracer() const;
1129
1130 void RegisterExternallyReferencedObject(Address* location);
1131 V8_EXPORT_PRIVATE void SetEmbedderStackStateForNextFinalization(
1132 EmbedderHeapTracer::EmbedderStackState stack_state);
1133
1134 EmbedderHeapTracer::TraceFlags flags_for_embedder_tracer() const;
1135
1136 // ===========================================================================
1137 // External string table API. ================================================
1138 // ===========================================================================
1139
1140 // Registers an external string.
1141 inline void RegisterExternalString(String string);
1142
1143 // Called when a string's resource is changed. The size of the payload is sent
1144 // as argument of the method.
1145 V8_EXPORT_PRIVATE void UpdateExternalString(String string, size_t old_payload,
1146 size_t new_payload);
1147
1148 // Finalizes an external string by deleting the associated external
1149 // data and clearing the resource pointer.
1150 inline void FinalizeExternalString(String string);
1151
1152 static String UpdateYoungReferenceInExternalStringTableEntry(
1153 Heap* heap, FullObjectSlot pointer);
1154
1155 // ===========================================================================
1156 // Methods checking/returning the space of a given object/address. ===========
1157 // ===========================================================================
1158
1159 // Returns whether the object resides in new space.
1160 static inline bool InYoungGeneration(Object object);
1161 static inline bool InYoungGeneration(MaybeObject object);
1162 static inline bool InYoungGeneration(HeapObject heap_object);
1163 static inline bool InFromPage(Object object);
1164 static inline bool InFromPage(MaybeObject object);
1165 static inline bool InFromPage(HeapObject heap_object);
1166 static inline bool InToPage(Object object);
1167 static inline bool InToPage(MaybeObject object);
1168 static inline bool InToPage(HeapObject heap_object);
1169
1170 // Returns whether the object resides in old space.
1171 inline bool InOldSpace(Object object);
1172
1173 // Checks whether an address/object is in the non-read-only heap (including
1174 // auxiliary area and unused area). Use IsValidHeapObject if checking both
1175 // heaps is required.
1176 V8_EXPORT_PRIVATE bool Contains(HeapObject value) const;
1177
1178 // Checks whether an address/object in a space.
1179 // Currently used by tests, serialization and heap verification only.
1180 V8_EXPORT_PRIVATE bool InSpace(HeapObject value, AllocationSpace space) const;
1181
1182 // Slow methods that can be used for verification as they can also be used
1183 // with off-heap Addresses.
1184 V8_EXPORT_PRIVATE bool InSpaceSlow(Address addr, AllocationSpace space) const;
1185
1186 static inline Heap* FromWritableHeapObject(HeapObject obj);
1187
1188 // ===========================================================================
1189 // Object statistics tracking. ===============================================
1190 // ===========================================================================
1191
1192 // Returns the number of buckets used by object statistics tracking during a
1193 // major GC. Note that the following methods fail gracefully when the bounds
1194 // are exceeded though.
1195 size_t NumberOfTrackedHeapObjectTypes();
1196
1197 // Returns object statistics about count and size at the last major GC.
1198 // Objects are being grouped into buckets that roughly resemble existing
1199 // instance types.
1200 size_t ObjectCountAtLastGC(size_t index);
1201 size_t ObjectSizeAtLastGC(size_t index);
1202
1203 // Retrieves names of buckets used by object statistics tracking.
1204 bool GetObjectTypeName(size_t index, const char** object_type,
1205 const char** object_sub_type);
1206
1207 // The total number of native contexts object on the heap.
1208 size_t NumberOfNativeContexts();
1209 // The total number of native contexts that were detached but were not
1210 // garbage collected yet.
1211 size_t NumberOfDetachedContexts();
1212
1213 // ===========================================================================
1214 // Code statistics. ==========================================================
1215 // ===========================================================================
1216
1217 // Collect code (Code and BytecodeArray objects) statistics.
1218 void CollectCodeStatistics();
1219
1220 // ===========================================================================
1221 // GC statistics. ============================================================
1222 // ===========================================================================
1223
1224 // Returns the maximum amount of memory reserved for the heap.
1225 V8_EXPORT_PRIVATE size_t MaxReserved();
MaxSemiSpaceSize()1226 size_t MaxSemiSpaceSize() { return max_semi_space_size_; }
InitialSemiSpaceSize()1227 size_t InitialSemiSpaceSize() { return initial_semispace_size_; }
MaxOldGenerationSize()1228 size_t MaxOldGenerationSize() { return max_old_generation_size(); }
1229
1230 // Limit on the max old generation size imposed by the underlying allocator.
1231 V8_EXPORT_PRIVATE static size_t AllocatorLimitOnMaxOldGenerationSize();
1232
1233 V8_EXPORT_PRIVATE static size_t HeapSizeFromPhysicalMemory(
1234 uint64_t physical_memory);
1235 V8_EXPORT_PRIVATE static void GenerationSizesFromHeapSize(
1236 size_t heap_size, size_t* young_generation_size,
1237 size_t* old_generation_size);
1238 V8_EXPORT_PRIVATE static size_t YoungGenerationSizeFromOldGenerationSize(
1239 size_t old_generation_size);
1240 V8_EXPORT_PRIVATE static size_t YoungGenerationSizeFromSemiSpaceSize(
1241 size_t semi_space_size);
1242 V8_EXPORT_PRIVATE static size_t SemiSpaceSizeFromYoungGenerationSize(
1243 size_t young_generation_size);
1244 V8_EXPORT_PRIVATE static size_t MinYoungGenerationSize();
1245 V8_EXPORT_PRIVATE static size_t MinOldGenerationSize();
1246 V8_EXPORT_PRIVATE static size_t MaxOldGenerationSize(
1247 uint64_t physical_memory);
1248
1249 // Returns the capacity of the heap in bytes w/o growing. Heap grows when
1250 // more spaces are needed until it reaches the limit.
1251 size_t Capacity();
1252
1253 // Returns the capacity of the old generation.
1254 V8_EXPORT_PRIVATE size_t OldGenerationCapacity();
1255
1256 // Returns the amount of memory currently held alive by the unmapper.
1257 size_t CommittedMemoryOfUnmapper();
1258
1259 // Returns the amount of memory currently committed for the heap.
1260 size_t CommittedMemory();
1261
1262 // Returns the amount of memory currently committed for the old space.
1263 size_t CommittedOldGenerationMemory();
1264
1265 // Returns the amount of executable memory currently committed for the heap.
1266 size_t CommittedMemoryExecutable();
1267
1268 // Returns the amount of phyical memory currently committed for the heap.
1269 size_t CommittedPhysicalMemory();
1270
1271 // Returns the maximum amount of memory ever committed for the heap.
MaximumCommittedMemory()1272 size_t MaximumCommittedMemory() { return maximum_committed_; }
1273
1274 // Updates the maximum committed memory for the heap. Should be called
1275 // whenever a space grows.
1276 void UpdateMaximumCommitted();
1277
1278 // Returns the available bytes in space w/o growing.
1279 // Heap doesn't guarantee that it can allocate an object that requires
1280 // all available bytes. Check MaxHeapObjectSize() instead.
1281 size_t Available();
1282
1283 // Returns size of all objects residing in the heap.
1284 V8_EXPORT_PRIVATE size_t SizeOfObjects();
1285
1286 // Returns size of all global handles in the heap.
1287 V8_EXPORT_PRIVATE size_t TotalGlobalHandlesSize();
1288
1289 // Returns size of all allocated/used global handles in the heap.
1290 V8_EXPORT_PRIVATE size_t UsedGlobalHandlesSize();
1291
1292 void UpdateSurvivalStatistics(int start_new_space_size);
1293
IncrementPromotedObjectsSize(size_t object_size)1294 inline void IncrementPromotedObjectsSize(size_t object_size) {
1295 promoted_objects_size_ += object_size;
1296 }
promoted_objects_size()1297 inline size_t promoted_objects_size() { return promoted_objects_size_; }
1298
IncrementSemiSpaceCopiedObjectSize(size_t object_size)1299 inline void IncrementSemiSpaceCopiedObjectSize(size_t object_size) {
1300 semi_space_copied_object_size_ += object_size;
1301 }
semi_space_copied_object_size()1302 inline size_t semi_space_copied_object_size() {
1303 return semi_space_copied_object_size_;
1304 }
1305
SurvivedYoungObjectSize()1306 inline size_t SurvivedYoungObjectSize() {
1307 return promoted_objects_size_ + semi_space_copied_object_size_;
1308 }
1309
IncrementNodesDiedInNewSpace()1310 inline void IncrementNodesDiedInNewSpace() { nodes_died_in_new_space_++; }
1311
IncrementNodesCopiedInNewSpace()1312 inline void IncrementNodesCopiedInNewSpace() { nodes_copied_in_new_space_++; }
1313
IncrementNodesPromoted()1314 inline void IncrementNodesPromoted() { nodes_promoted_++; }
1315
IncrementYoungSurvivorsCounter(size_t survived)1316 inline void IncrementYoungSurvivorsCounter(size_t survived) {
1317 survived_last_scavenge_ = survived;
1318 survived_since_last_expansion_ += survived;
1319 }
1320
1321 inline void UpdateNewSpaceAllocationCounter();
1322
1323 inline size_t NewSpaceAllocationCounter();
1324
1325 // This should be used only for testing.
set_new_space_allocation_counter(size_t new_value)1326 void set_new_space_allocation_counter(size_t new_value) {
1327 new_space_allocation_counter_ = new_value;
1328 }
1329
UpdateOldGenerationAllocationCounter()1330 void UpdateOldGenerationAllocationCounter() {
1331 old_generation_allocation_counter_at_last_gc_ =
1332 OldGenerationAllocationCounter();
1333 old_generation_size_at_last_gc_ = 0;
1334 }
1335
OldGenerationAllocationCounter()1336 size_t OldGenerationAllocationCounter() {
1337 return old_generation_allocation_counter_at_last_gc_ +
1338 PromotedSinceLastGC();
1339 }
1340
1341 size_t EmbedderAllocationCounter() const;
1342
1343 // This should be used only for testing.
set_old_generation_allocation_counter_at_last_gc(size_t new_value)1344 void set_old_generation_allocation_counter_at_last_gc(size_t new_value) {
1345 old_generation_allocation_counter_at_last_gc_ = new_value;
1346 }
1347
PromotedSinceLastGC()1348 size_t PromotedSinceLastGC() {
1349 size_t old_generation_size = OldGenerationSizeOfObjects();
1350 return old_generation_size > old_generation_size_at_last_gc_
1351 ? old_generation_size - old_generation_size_at_last_gc_
1352 : 0;
1353 }
1354
gc_count()1355 int gc_count() const { return gc_count_; }
1356
is_current_gc_forced()1357 bool is_current_gc_forced() const { return is_current_gc_forced_; }
1358
1359 // Returns the size of objects residing in non-new spaces.
1360 // Excludes external memory held by those objects.
1361 V8_EXPORT_PRIVATE size_t OldGenerationSizeOfObjects();
1362
1363 V8_EXPORT_PRIVATE size_t GlobalSizeOfObjects();
1364
1365 // We allow incremental marking to overshoot the V8 and global allocation
1366 // limit for performace reasons. If the overshoot is too large then we are
1367 // more eager to finalize incremental marking.
1368 bool AllocationLimitOvershotByLargeMargin();
1369
1370 // Return the maximum size objects can be before having to allocate them as
1371 // large objects. This takes into account allocating in the code space for
1372 // which the size of the allocatable space per V8 page may depend on the OS
1373 // page size at runtime. You may use kMaxRegularHeapObjectSize as a constant
1374 // instead if you know the allocation isn't in the code spaces.
1375 V8_EXPORT_PRIVATE static int MaxRegularHeapObjectSize(
1376 AllocationType allocation);
1377
1378 // ===========================================================================
1379 // Prologue/epilogue callback methods.========================================
1380 // ===========================================================================
1381
1382 void AddGCPrologueCallback(v8::Isolate::GCCallbackWithData callback,
1383 GCType gc_type_filter, void* data);
1384 void RemoveGCPrologueCallback(v8::Isolate::GCCallbackWithData callback,
1385 void* data);
1386
1387 void AddGCEpilogueCallback(v8::Isolate::GCCallbackWithData callback,
1388 GCType gc_type_filter, void* data);
1389 void RemoveGCEpilogueCallback(v8::Isolate::GCCallbackWithData callback,
1390 void* data);
1391
1392 void CallGCPrologueCallbacks(GCType gc_type, GCCallbackFlags flags);
1393 void CallGCEpilogueCallbacks(GCType gc_type, GCCallbackFlags flags);
1394
1395 // ===========================================================================
1396 // Allocation methods. =======================================================
1397 // ===========================================================================
1398
1399 // Creates a filler object and returns a heap object immediately after it.
1400 V8_EXPORT_PRIVATE static HeapObject PrecedeWithFiller(ReadOnlyRoots roots,
1401 HeapObject object,
1402 int filler_size);
1403
1404 // Creates a filler object if needed for alignment and returns a heap object
1405 // immediately after it. If any space is left after the returned object,
1406 // another filler object is created so the over allocated memory is iterable.
1407 static V8_WARN_UNUSED_RESULT HeapObject
1408 AlignWithFiller(ReadOnlyRoots roots, HeapObject object, int object_size,
1409 int allocation_size, AllocationAlignment alignment);
1410
1411 // Allocate an external backing store with the given allocation callback.
1412 // If the callback fails (indicated by a nullptr result) then this function
1413 // will re-try the allocation after performing GCs. This is useful for
1414 // external backing stores that may be retained by (unreachable) V8 objects
1415 // such as ArrayBuffers, ExternalStrings, etc.
1416 //
1417 // The function may also proactively trigger GCs even if the allocation
1418 // callback does not fail to keep the memory usage low.
1419 V8_EXPORT_PRIVATE void* AllocateExternalBackingStore(
1420 const std::function<void*(size_t)>& allocate, size_t byte_length);
1421
1422 // ===========================================================================
1423 // Allocation site tracking. =================================================
1424 // ===========================================================================
1425
1426 // Updates the AllocationSite of a given {object}. The entry (including the
1427 // count) is cached on the local pretenuring feedback.
1428 inline void UpdateAllocationSite(
1429 Map map, HeapObject object, PretenuringFeedbackMap* pretenuring_feedback);
1430
1431 // Merges local pretenuring feedback into the global one. Note that this
1432 // method needs to be called after evacuation, as allocation sites may be
1433 // evacuated and this method resolves forward pointers accordingly.
1434 void MergeAllocationSitePretenuringFeedback(
1435 const PretenuringFeedbackMap& local_pretenuring_feedback);
1436
1437 // ===========================================================================
1438 // Allocation tracking. ======================================================
1439 // ===========================================================================
1440
1441 // Adds {new_space_observer} to new space and {observer} to any other space.
1442 void AddAllocationObserversToAllSpaces(
1443 AllocationObserver* observer, AllocationObserver* new_space_observer);
1444
1445 // Removes {new_space_observer} from new space and {observer} from any other
1446 // space.
1447 void RemoveAllocationObserversFromAllSpaces(
1448 AllocationObserver* observer, AllocationObserver* new_space_observer);
1449
1450 // ===========================================================================
1451 // Heap object allocation tracking. ==========================================
1452 // ===========================================================================
1453
1454 V8_EXPORT_PRIVATE void AddHeapObjectAllocationTracker(
1455 HeapObjectAllocationTracker* tracker);
1456 V8_EXPORT_PRIVATE void RemoveHeapObjectAllocationTracker(
1457 HeapObjectAllocationTracker* tracker);
has_heap_object_allocation_tracker()1458 bool has_heap_object_allocation_tracker() const {
1459 return !allocation_trackers_.empty();
1460 }
1461
1462 // ===========================================================================
1463 // Retaining path tracking. ==================================================
1464 // ===========================================================================
1465
1466 // Adds the given object to the weak table of retaining path targets.
1467 // On each GC if the marker discovers the object, it will print the retaining
1468 // path. This requires --track-retaining-path flag.
1469 void AddRetainingPathTarget(Handle<HeapObject> object,
1470 RetainingPathOption option);
1471
1472 // ===========================================================================
1473 // Stack frame support. ======================================================
1474 // ===========================================================================
1475
1476 // Returns the Code object for a given interior pointer.
1477 Code GcSafeFindCodeForInnerPointer(Address inner_pointer);
1478
1479 // Returns true if {addr} is contained within {code} and false otherwise.
1480 // Mostly useful for debugging.
1481 bool GcSafeCodeContains(Code code, Address addr);
1482
1483 // Casts a heap object to a code object and checks if the inner_pointer is
1484 // within the object.
1485 Code GcSafeCastToCode(HeapObject object, Address inner_pointer);
1486
1487 // Returns the map of an object. Can be used during garbage collection, i.e.
1488 // it supports a forwarded map. Fails if the map is not the code map.
1489 Map GcSafeMapOfCodeSpaceObject(HeapObject object);
1490
1491 // =============================================================================
1492 #ifdef VERIFY_HEAP
1493 // Verify the heap is in its normal state before or after a GC.
1494 V8_EXPORT_PRIVATE void Verify();
1495 // Verify the read-only heap after all read-only heap objects have been
1496 // created.
1497 void VerifyReadOnlyHeap();
1498 void VerifyRememberedSetFor(HeapObject object);
1499 #endif
1500
1501 #ifdef V8_ENABLE_ALLOCATION_TIMEOUT
set_allocation_timeout(int timeout)1502 void set_allocation_timeout(int timeout) { allocation_timeout_ = timeout; }
1503 #endif
1504
1505 #ifdef DEBUG
1506 void VerifyCountersAfterSweeping();
1507 void VerifyCountersBeforeConcurrentSweeping();
1508
1509 void Print();
1510 void PrintHandles();
1511
1512 // Report code statistics.
1513 void ReportCodeStatistics(const char* title);
1514 #endif
GetRandomMmapAddr()1515 void* GetRandomMmapAddr() {
1516 void* result = v8::internal::GetRandomMmapAddr();
1517 #if V8_TARGET_ARCH_X64
1518 #if V8_OS_MACOSX
1519 // The Darwin kernel [as of macOS 10.12.5] does not clean up page
1520 // directory entries [PDE] created from mmap or mach_vm_allocate, even
1521 // after the region is destroyed. Using a virtual address space that is
1522 // too large causes a leak of about 1 wired [can never be paged out] page
1523 // per call to mmap(). The page is only reclaimed when the process is
1524 // killed. Confine the hint to a 32-bit section of the virtual address
1525 // space. See crbug.com/700928.
1526 uintptr_t offset = reinterpret_cast<uintptr_t>(result) & kMmapRegionMask;
1527 result = reinterpret_cast<void*>(mmap_region_base_ + offset);
1528 #endif // V8_OS_MACOSX
1529 #endif // V8_TARGET_ARCH_X64
1530 return result;
1531 }
1532
1533 static const char* GarbageCollectionReasonToString(
1534 GarbageCollectionReason gc_reason);
1535
1536 // Calculates the nof entries for the full sized number to string cache.
1537 inline int MaxNumberToStringCacheSize() const;
1538
1539 static Isolate* GetIsolateFromWritableObject(HeapObject object);
1540
1541 private:
1542 using ExternalStringTableUpdaterCallback = String (*)(Heap* heap,
1543 FullObjectSlot pointer);
1544
1545 // External strings table is a place where all external strings are
1546 // registered. We need to keep track of such strings to properly
1547 // finalize them.
1548 class ExternalStringTable {
1549 public:
ExternalStringTable(Heap * heap)1550 explicit ExternalStringTable(Heap* heap) : heap_(heap) {}
1551
1552 // Registers an external string.
1553 inline void AddString(String string);
1554 bool Contains(String string);
1555
1556 void IterateAll(RootVisitor* v);
1557 void IterateYoung(RootVisitor* v);
1558 void PromoteYoung();
1559
1560 // Restores internal invariant and gets rid of collected strings. Must be
1561 // called after each Iterate*() that modified the strings.
1562 void CleanUpAll();
1563 void CleanUpYoung();
1564
1565 // Finalize all registered external strings and clear tables.
1566 void TearDown();
1567
1568 void UpdateYoungReferences(
1569 Heap::ExternalStringTableUpdaterCallback updater_func);
1570 void UpdateReferences(
1571 Heap::ExternalStringTableUpdaterCallback updater_func);
1572
1573 private:
1574 void Verify();
1575 void VerifyYoung();
1576
1577 Heap* const heap_;
1578
1579 // To speed up scavenge collections young string are kept separate from old
1580 // strings.
1581 std::vector<Object> young_strings_;
1582 std::vector<Object> old_strings_;
1583
1584 DISALLOW_COPY_AND_ASSIGN(ExternalStringTable);
1585 };
1586
1587 struct StringTypeTable {
1588 InstanceType type;
1589 int size;
1590 RootIndex index;
1591 };
1592
1593 struct ConstantStringTable {
1594 const char* contents;
1595 RootIndex index;
1596 };
1597
1598 struct StructTable {
1599 InstanceType type;
1600 int size;
1601 RootIndex index;
1602 };
1603
1604 struct GCCallbackTuple {
GCCallbackTupleGCCallbackTuple1605 GCCallbackTuple(v8::Isolate::GCCallbackWithData callback, GCType gc_type,
1606 void* data)
1607 : callback(callback), gc_type(gc_type), data(data) {}
1608
1609 bool operator==(const GCCallbackTuple& other) const;
1610 GCCallbackTuple& operator=(const GCCallbackTuple& other) V8_NOEXCEPT;
1611
1612 v8::Isolate::GCCallbackWithData callback;
1613 GCType gc_type;
1614 void* data;
1615 };
1616
1617 static const int kInitialEvalCacheSize = 64;
1618 static const int kInitialNumberStringCacheSize = 256;
1619
1620 static const int kRememberedUnmappedPages = 128;
1621
1622 static const StringTypeTable string_type_table[];
1623 static const ConstantStringTable constant_string_table[];
1624 static const StructTable struct_table[];
1625
1626 static const int kYoungSurvivalRateHighThreshold = 90;
1627 static const int kYoungSurvivalRateAllowedDeviation = 15;
1628 static const int kOldSurvivalRateLowThreshold = 10;
1629
1630 static const int kMaxMarkCompactsInIdleRound = 7;
1631
1632 static const int kInitialFeedbackCapacity = 256;
1633
1634 Heap();
1635 ~Heap();
1636
IsRegularObjectAllocation(AllocationType allocation)1637 static bool IsRegularObjectAllocation(AllocationType allocation) {
1638 return AllocationType::kYoung == allocation ||
1639 AllocationType::kOld == allocation;
1640 }
1641
DefaultGetExternallyAllocatedMemoryInBytesCallback()1642 static size_t DefaultGetExternallyAllocatedMemoryInBytesCallback() {
1643 return 0;
1644 }
1645
1646 #define ROOT_ACCESSOR(type, name, CamelName) inline void set_##name(type value);
ROOT_LIST(ROOT_ACCESSOR)1647 ROOT_LIST(ROOT_ACCESSOR)
1648 #undef ROOT_ACCESSOR
1649
1650 void set_current_gc_flags(int flags) { current_gc_flags_ = flags; }
1651
ShouldReduceMemory()1652 inline bool ShouldReduceMemory() const {
1653 return (current_gc_flags_ & kReduceMemoryFootprintMask) != 0;
1654 }
1655
1656 int NumberOfScavengeTasks();
1657
1658 // Checks whether a global GC is necessary
1659 GarbageCollector SelectGarbageCollector(AllocationSpace space,
1660 const char** reason);
1661
1662 // Make sure there is a filler value behind the top of the new space
1663 // so that the GC does not confuse some unintialized/stale memory
1664 // with the allocation memento of the object at the top
1665 void EnsureFillerObjectAtTop();
1666
1667 // Ensure that we have swept all spaces in such a way that we can iterate
1668 // over all objects. May cause a GC.
1669 void MakeHeapIterable();
1670
1671 // Ensure that LABs of local heaps are iterable.
1672 void MakeLocalHeapLabsIterable();
1673
1674 // Performs garbage collection in a safepoint.
1675 // Returns the number of freed global handles.
1676 size_t PerformGarbageCollection(
1677 GarbageCollector collector,
1678 const GCCallbackFlags gc_callback_flags = kNoGCCallbackFlags);
1679
1680 inline void UpdateOldSpaceLimits();
1681
1682 bool CreateInitialMaps();
1683 void CreateInternalAccessorInfoObjects();
1684 void CreateInitialObjects();
1685
1686 // Commits from space if it is uncommitted.
1687 void EnsureFromSpaceIsCommitted();
1688
1689 // Uncommit unused semi space.
1690 V8_EXPORT_PRIVATE bool UncommitFromSpace();
1691
1692 // Fill in bogus values in from space
1693 void ZapFromSpace();
1694
1695 // Zaps the memory of a code object.
1696 V8_EXPORT_PRIVATE void ZapCodeObject(Address start_address,
1697 int size_in_bytes);
1698
1699 // Initialize a filler object to keep the ability to iterate over the heap
1700 // when introducing gaps within pages. If the memory after the object header
1701 // of the filler should be cleared, pass in kClearFreedMemory. The default is
1702 // kDontClearFreedMemory.
1703 V8_EXPORT_PRIVATE static HeapObject CreateFillerObjectAt(
1704 ReadOnlyRoots roots, Address addr, int size,
1705 ClearFreedMemoryMode clear_memory_mode =
1706 ClearFreedMemoryMode::kDontClearFreedMemory);
1707
1708 // Range write barrier implementation.
1709 template <int kModeMask, typename TSlot>
1710 V8_INLINE void WriteBarrierForRangeImpl(MemoryChunk* source_page,
1711 HeapObject object, TSlot start_slot,
1712 TSlot end_slot);
1713
1714 // Deopts all code that contains allocation instruction which are tenured or
1715 // not tenured. Moreover it clears the pretenuring allocation site statistics.
1716 void ResetAllAllocationSitesDependentCode(AllocationType allocation);
1717
1718 // Evaluates local pretenuring for the old space and calls
1719 // ResetAllTenuredAllocationSitesDependentCode if too many objects died in
1720 // the old space.
1721 void EvaluateOldSpaceLocalPretenuring(uint64_t size_of_objects_before_gc);
1722
1723 // Record statistics after garbage collection.
1724 void ReportStatisticsAfterGC();
1725
1726 // Flush the number to string cache.
1727 void FlushNumberStringCache();
1728
1729 void ConfigureInitialOldGenerationSize();
1730
1731 double ComputeMutatorUtilization(const char* tag, double mutator_speed,
1732 double gc_speed);
1733 bool HasLowYoungGenerationAllocationRate();
1734 bool HasLowOldGenerationAllocationRate();
1735 bool HasLowEmbedderAllocationRate();
1736
1737 void ReduceNewSpaceSize();
1738
1739 GCIdleTimeHeapState ComputeHeapState();
1740
1741 bool PerformIdleTimeAction(GCIdleTimeAction action,
1742 GCIdleTimeHeapState heap_state,
1743 double deadline_in_ms);
1744
1745 void IdleNotificationEpilogue(GCIdleTimeAction action,
1746 GCIdleTimeHeapState heap_state, double start_ms,
1747 double deadline_in_ms);
1748
1749 int NextAllocationTimeout(int current_timeout = 0);
1750 inline void UpdateAllocationsHash(HeapObject object);
1751 inline void UpdateAllocationsHash(uint32_t value);
1752 void PrintAllocationsHash();
1753
1754 void PrintMaxMarkingLimitReached();
1755 void PrintMaxNewSpaceSizeReached();
1756
1757 int NextStressMarkingLimit();
1758
1759 void AddToRingBuffer(const char* string);
1760 void GetFromRingBuffer(char* buffer);
1761
1762 void CompactRetainedMaps(WeakArrayList retained_maps);
1763
1764 void CollectGarbageOnMemoryPressure();
1765
1766 void EagerlyFreeExternalMemory();
1767
1768 bool InvokeNearHeapLimitCallback();
1769
1770 void ComputeFastPromotionMode();
1771
1772 // Attempt to over-approximate the weak closure by marking object groups and
1773 // implicit references from global handles, but don't atomically complete
1774 // marking. If we continue to mark incrementally, we might have marked
1775 // objects that die later.
1776 void FinalizeIncrementalMarkingIncrementally(
1777 GarbageCollectionReason gc_reason);
1778
1779 void InvokeIncrementalMarkingPrologueCallbacks();
1780 void InvokeIncrementalMarkingEpilogueCallbacks();
1781
1782 // Returns the timer used for a given GC type.
1783 // - GCScavenger: young generation GC
1784 // - GCCompactor: full GC
1785 // - GCFinalzeMC: finalization of incremental full GC
1786 // - GCFinalizeMCReduceMemory: finalization of incremental full GC with
1787 // memory reduction
1788 TimedHistogram* GCTypeTimer(GarbageCollector collector);
1789 TimedHistogram* GCTypePriorityTimer(GarbageCollector collector);
1790
1791 // ===========================================================================
1792 // Pretenuring. ==============================================================
1793 // ===========================================================================
1794
1795 // Pretenuring decisions are made based on feedback collected during new space
1796 // evacuation. Note that between feedback collection and calling this method
1797 // object in old space must not move.
1798 void ProcessPretenuringFeedback();
1799
1800 // Removes an entry from the global pretenuring storage.
1801 void RemoveAllocationSitePretenuringFeedback(AllocationSite site);
1802
1803 // ===========================================================================
1804 // Actual GC. ================================================================
1805 // ===========================================================================
1806
1807 // Code that should be run before and after each GC. Includes some
1808 // reporting/verification activities when compiled with DEBUG set.
1809 void GarbageCollectionPrologue();
1810 void GarbageCollectionPrologueInSafepoint();
1811 void GarbageCollectionEpilogue();
1812 void GarbageCollectionEpilogueInSafepoint(GarbageCollector collector);
1813
1814 // Performs a major collection in the whole heap.
1815 void MarkCompact();
1816 // Performs a minor collection of just the young generation.
1817 void MinorMarkCompact();
1818
1819 // Code to be run before and after mark-compact.
1820 void MarkCompactPrologue();
1821 void MarkCompactEpilogue();
1822
1823 // Performs a minor collection in new generation.
1824 void Scavenge();
1825 void EvacuateYoungGeneration();
1826
1827 void UpdateYoungReferencesInExternalStringTable(
1828 ExternalStringTableUpdaterCallback updater_func);
1829
1830 void UpdateReferencesInExternalStringTable(
1831 ExternalStringTableUpdaterCallback updater_func);
1832
1833 void ProcessAllWeakReferences(WeakObjectRetainer* retainer);
1834 void ProcessYoungWeakReferences(WeakObjectRetainer* retainer);
1835 void ProcessNativeContexts(WeakObjectRetainer* retainer);
1836 void ProcessAllocationSites(WeakObjectRetainer* retainer);
1837 void ProcessDirtyJSFinalizationRegistries(WeakObjectRetainer* retainer);
1838 void ProcessWeakListRoots(WeakObjectRetainer* retainer);
1839
1840 // ===========================================================================
1841 // GC statistics. ============================================================
1842 // ===========================================================================
1843
OldGenerationSpaceAvailable()1844 inline size_t OldGenerationSpaceAvailable() {
1845 uint64_t bytes = OldGenerationSizeOfObjects() +
1846 AllocatedExternalMemorySinceMarkCompact();
1847
1848 if (old_generation_allocation_limit() <= bytes) return 0;
1849 return old_generation_allocation_limit() - static_cast<size_t>(bytes);
1850 }
1851
1852 void UpdateTotalGCTime(double duration);
1853
MaximumSizeScavenge()1854 bool MaximumSizeScavenge() { return maximum_size_scavenges_ > 0; }
1855
1856 bool IsIneffectiveMarkCompact(size_t old_generation_size,
1857 double mutator_utilization);
1858 void CheckIneffectiveMarkCompact(size_t old_generation_size,
1859 double mutator_utilization);
1860
1861 inline void IncrementExternalBackingStoreBytes(ExternalBackingStoreType type,
1862 size_t amount);
1863
1864 inline void DecrementExternalBackingStoreBytes(ExternalBackingStoreType type,
1865 size_t amount);
1866
1867 // ===========================================================================
1868 // Growing strategy. =========================================================
1869 // ===========================================================================
1870
memory_reducer()1871 MemoryReducer* memory_reducer() { return memory_reducer_.get(); }
1872
1873 // For some webpages RAIL mode does not switch from PERFORMANCE_LOAD.
1874 // This constant limits the effect of load RAIL mode on GC.
1875 // The value is arbitrary and chosen as the largest load time observed in
1876 // v8 browsing benchmarks.
1877 static const int kMaxLoadTimeMs = 7000;
1878
1879 bool ShouldOptimizeForLoadTime();
1880
old_generation_allocation_limit()1881 size_t old_generation_allocation_limit() const {
1882 return old_generation_allocation_limit_.load(std::memory_order_relaxed);
1883 }
1884
set_old_generation_allocation_limit(size_t newlimit)1885 void set_old_generation_allocation_limit(size_t newlimit) {
1886 old_generation_allocation_limit_.store(newlimit, std::memory_order_relaxed);
1887 }
1888
global_allocation_limit()1889 size_t global_allocation_limit() const { return global_allocation_limit_; }
1890
max_old_generation_size()1891 size_t max_old_generation_size() {
1892 return max_old_generation_size_.load(std::memory_order_relaxed);
1893 }
1894
set_max_old_generation_size(size_t value)1895 void set_max_old_generation_size(size_t value) {
1896 max_old_generation_size_.store(value, std::memory_order_relaxed);
1897 }
1898
always_allocate()1899 bool always_allocate() { return always_allocate_scope_count_ != 0; }
1900
1901 V8_EXPORT_PRIVATE bool CanExpandOldGeneration(size_t size);
1902 V8_EXPORT_PRIVATE bool CanExpandOldGenerationBackground(size_t size);
1903 V8_EXPORT_PRIVATE bool CanPromoteYoungAndExpandOldGeneration(size_t size);
1904
1905 bool ShouldExpandOldGenerationOnSlowAllocation(
1906 LocalHeap* local_heap = nullptr);
1907 bool IsRetryOfFailedAllocation(LocalHeap* local_heap);
1908
1909 HeapGrowingMode CurrentHeapGrowingMode();
1910
1911 double PercentToOldGenerationLimit();
1912 double PercentToGlobalMemoryLimit();
1913 enum class IncrementalMarkingLimit { kNoLimit, kSoftLimit, kHardLimit };
1914 IncrementalMarkingLimit IncrementalMarkingLimitReached();
1915
1916 bool ShouldStressCompaction() const;
1917
UseGlobalMemoryScheduling()1918 bool UseGlobalMemoryScheduling() const {
1919 return FLAG_global_gc_scheduling && local_embedder_heap_tracer();
1920 }
1921
1922 base::Optional<size_t> GlobalMemoryAvailable();
1923
1924 void RecomputeLimits(GarbageCollector collector);
1925
1926 // ===========================================================================
1927 // Idle notification. ========================================================
1928 // ===========================================================================
1929
1930 bool RecentIdleNotificationHappened();
1931
1932 // ===========================================================================
1933 // GC Tasks. =================================================================
1934 // ===========================================================================
1935
1936 void ScheduleScavengeTaskIfNeeded();
1937
1938 // ===========================================================================
1939 // Allocation methods. =======================================================
1940 // ===========================================================================
1941
1942 // Allocates a JS Map in the heap.
1943 V8_WARN_UNUSED_RESULT AllocationResult
1944 AllocateMap(InstanceType instance_type, int instance_size,
1945 ElementsKind elements_kind = TERMINAL_FAST_ELEMENTS_KIND,
1946 int inobject_properties = 0);
1947
1948 // Allocate an uninitialized object. The memory is non-executable if the
1949 // hardware and OS allow. This is the single choke-point for allocations
1950 // performed by the runtime and should not be bypassed (to extend this to
1951 // inlined allocations, use the Heap::DisableInlineAllocation() support).
1952 V8_WARN_UNUSED_RESULT inline AllocationResult AllocateRaw(
1953 int size_in_bytes, AllocationType allocation,
1954 AllocationOrigin origin = AllocationOrigin::kRuntime,
1955 AllocationAlignment alignment = kWordAligned);
1956
1957 // This method will try to allocate objects quickly (AllocationType::kYoung)
1958 // otherwise it falls back to a slower path indicated by the mode.
1959 enum AllocationRetryMode { kLightRetry, kRetryOrFail };
1960 template <AllocationRetryMode mode>
1961 V8_WARN_UNUSED_RESULT inline HeapObject AllocateRawWith(
1962 int size, AllocationType allocation,
1963 AllocationOrigin origin = AllocationOrigin::kRuntime,
1964 AllocationAlignment alignment = kWordAligned);
1965
1966 // This method will try to perform an allocation of a given size of a given
1967 // AllocationType. If the allocation fails, a regular full garbage collection
1968 // is triggered and the allocation is retried. This is performed multiple
1969 // times. If after that retry procedure the allocation still fails nullptr is
1970 // returned.
1971 V8_WARN_UNUSED_RESULT HeapObject AllocateRawWithLightRetrySlowPath(
1972 int size, AllocationType allocation, AllocationOrigin origin,
1973 AllocationAlignment alignment = kWordAligned);
1974
1975 // This method will try to perform an allocation of a given size of a given
1976 // AllocationType. If the allocation fails, a regular full garbage collection
1977 // is triggered and the allocation is retried. This is performed multiple
1978 // times. If after that retry procedure the allocation still fails a "hammer"
1979 // garbage collection is triggered which tries to significantly reduce memory.
1980 // If the allocation still fails after that a fatal error is thrown.
1981 V8_WARN_UNUSED_RESULT HeapObject AllocateRawWithRetryOrFailSlowPath(
1982 int size, AllocationType allocation, AllocationOrigin origin,
1983 AllocationAlignment alignment = kWordAligned);
1984
1985 // Allocates a heap object based on the map.
1986 V8_WARN_UNUSED_RESULT AllocationResult Allocate(Map map,
1987 AllocationType allocation);
1988
1989 // Allocates a partial map for bootstrapping.
1990 V8_WARN_UNUSED_RESULT AllocationResult
1991 AllocatePartialMap(InstanceType instance_type, int instance_size);
1992
1993 void FinalizePartialMap(Map map);
1994
set_force_oom(bool value)1995 void set_force_oom(bool value) { force_oom_ = value; }
set_force_gc_on_next_allocation()1996 void set_force_gc_on_next_allocation() {
1997 force_gc_on_next_allocation_ = true;
1998 }
1999
2000 // ===========================================================================
2001 // Retaining path tracing ====================================================
2002 // ===========================================================================
2003
2004 void AddRetainer(HeapObject retainer, HeapObject object);
2005 void AddEphemeronRetainer(HeapObject retainer, HeapObject object);
2006 void AddRetainingRoot(Root root, HeapObject object);
2007 // Returns true if the given object is a target of retaining path tracking.
2008 // Stores the option corresponding to the object in the provided *option.
2009 bool IsRetainingPathTarget(HeapObject object, RetainingPathOption* option);
2010 void PrintRetainingPath(HeapObject object, RetainingPathOption option);
2011
2012 #ifdef DEBUG
2013 V8_EXPORT_PRIVATE void IncrementObjectCounters();
2014 #endif // DEBUG
2015
2016 std::vector<Handle<NativeContext>> FindAllNativeContexts();
2017 std::vector<WeakArrayList> FindAllRetainedMaps();
memory_measurement()2018 MemoryMeasurement* memory_measurement() { return memory_measurement_.get(); }
2019
2020 // The amount of memory that has been freed concurrently.
2021 std::atomic<uintptr_t> external_memory_concurrently_freed_{0};
2022 ExternalMemoryAccounting external_memory_;
2023
2024 // This can be calculated directly from a pointer to the heap; however, it is
2025 // more expedient to get at the isolate directly from within Heap methods.
2026 Isolate* isolate_ = nullptr;
2027
2028 // These limits are initialized in Heap::ConfigureHeap based on the resource
2029 // constraints and flags.
2030 size_t code_range_size_ = 0;
2031 size_t max_semi_space_size_ = 0;
2032 size_t initial_semispace_size_ = 0;
2033 // Full garbage collections can be skipped if the old generation size
2034 // is below this threshold.
2035 size_t min_old_generation_size_ = 0;
2036 // If the old generation size exceeds this limit, then V8 will
2037 // crash with out-of-memory error.
2038 std::atomic<size_t> max_old_generation_size_{0};
2039 // TODO(mlippautz): Clarify whether this should take some embedder
2040 // configurable limit into account.
2041 size_t min_global_memory_size_ = 0;
2042 size_t max_global_memory_size_ = 0;
2043
2044 size_t initial_max_old_generation_size_ = 0;
2045 size_t initial_max_old_generation_size_threshold_ = 0;
2046 size_t initial_old_generation_size_ = 0;
2047 bool old_generation_size_configured_ = false;
2048 size_t maximum_committed_ = 0;
2049 size_t old_generation_capacity_after_bootstrap_ = 0;
2050
2051 // Backing store bytes (array buffers and external strings).
2052 std::atomic<size_t> backing_store_bytes_{0};
2053
2054 // For keeping track of how much data has survived
2055 // scavenge since last new space expansion.
2056 size_t survived_since_last_expansion_ = 0;
2057
2058 // ... and since the last scavenge.
2059 size_t survived_last_scavenge_ = 0;
2060
2061 // This is not the depth of nested AlwaysAllocateScope's but rather a single
2062 // count, as scopes can be acquired from multiple tasks (read: threads).
2063 std::atomic<size_t> always_allocate_scope_count_{0};
2064
2065 // Stores the memory pressure level that set by MemoryPressureNotification
2066 // and reset by a mark-compact garbage collection.
2067 std::atomic<MemoryPressureLevel> memory_pressure_level_;
2068
2069 std::vector<std::pair<v8::NearHeapLimitCallback, void*>>
2070 near_heap_limit_callbacks_;
2071
2072 // For keeping track of context disposals.
2073 int contexts_disposed_ = 0;
2074
2075 NewSpace* new_space_ = nullptr;
2076 OldSpace* old_space_ = nullptr;
2077 CodeSpace* code_space_ = nullptr;
2078 MapSpace* map_space_ = nullptr;
2079 OldLargeObjectSpace* lo_space_ = nullptr;
2080 CodeLargeObjectSpace* code_lo_space_ = nullptr;
2081 NewLargeObjectSpace* new_lo_space_ = nullptr;
2082 ReadOnlySpace* read_only_space_ = nullptr;
2083 // Map from the space id to the space.
2084 Space* space_[LAST_SPACE + 1];
2085
2086 // List for tracking ArrayBufferExtensions
2087 ArrayBufferExtension* old_array_buffer_extensions_ = nullptr;
2088 ArrayBufferExtension* young_array_buffer_extensions_ = nullptr;
2089
2090 // Determines whether code space is write-protected. This is essentially a
2091 // race-free copy of the {FLAG_write_protect_code_memory} flag.
2092 bool write_protect_code_memory_ = false;
2093
2094 // Holds the number of open CodeSpaceMemoryModificationScopes.
2095 uintptr_t code_space_memory_modification_scope_depth_ = 0;
2096
2097 std::atomic<HeapState> gc_state_{NOT_IN_GC};
2098
2099 int gc_post_processing_depth_ = 0;
2100
2101 // Returns the amount of external memory registered since last global gc.
2102 V8_EXPORT_PRIVATE uint64_t AllocatedExternalMemorySinceMarkCompact();
2103
2104 // How many "runtime allocations" happened.
2105 uint32_t allocations_count_ = 0;
2106
2107 // Running hash over allocations performed.
2108 uint32_t raw_allocations_hash_ = 0;
2109
2110 // Starts marking when stress_marking_percentage_% of the marking start limit
2111 // is reached.
2112 int stress_marking_percentage_ = 0;
2113
2114 // Observer that causes more frequent checks for reached incremental marking
2115 // limit.
2116 AllocationObserver* stress_marking_observer_ = nullptr;
2117
2118 // Observer that can cause early scavenge start.
2119 StressScavengeObserver* stress_scavenge_observer_ = nullptr;
2120
2121 // The maximum percent of the marking limit reached wihout causing marking.
2122 // This is tracked when specyfing --fuzzer-gc-analysis.
2123 double max_marking_limit_reached_ = 0.0;
2124
2125 // How many mark-sweep collections happened.
2126 unsigned int ms_count_ = 0;
2127
2128 // How many gc happened.
2129 unsigned int gc_count_ = 0;
2130
2131 // The number of Mark-Compact garbage collections that are considered as
2132 // ineffective. See IsIneffectiveMarkCompact() predicate.
2133 int consecutive_ineffective_mark_compacts_ = 0;
2134
2135 static const uintptr_t kMmapRegionMask = 0xFFFFFFFFu;
2136 uintptr_t mmap_region_base_ = 0;
2137
2138 // For post mortem debugging.
2139 int remembered_unmapped_pages_index_ = 0;
2140 Address remembered_unmapped_pages_[kRememberedUnmappedPages];
2141
2142 // Limit that triggers a global GC on the next (normally caused) GC. This
2143 // is checked when we have already decided to do a GC to help determine
2144 // which collector to invoke, before expanding a paged space in the old
2145 // generation and on every allocation in large object space.
2146 std::atomic<size_t> old_generation_allocation_limit_{0};
2147 size_t global_allocation_limit_ = 0;
2148
2149 // Indicates that inline bump-pointer allocation has been globally disabled
2150 // for all spaces. This is used to disable allocations in generated code.
2151 bool inline_allocation_disabled_ = false;
2152
2153 // Weak list heads, threaded through the objects.
2154 // List heads are initialized lazily and contain the undefined_value at start.
2155 Object native_contexts_list_;
2156 Object allocation_sites_list_;
2157 Object dirty_js_finalization_registries_list_;
2158 // Weak list tails.
2159 Object dirty_js_finalization_registries_list_tail_;
2160
2161 std::vector<GCCallbackTuple> gc_epilogue_callbacks_;
2162 std::vector<GCCallbackTuple> gc_prologue_callbacks_;
2163
2164 GetExternallyAllocatedMemoryInBytesCallback external_memory_callback_;
2165
2166 int deferred_counters_[v8::Isolate::kUseCounterFeatureCount];
2167
2168 size_t promoted_objects_size_ = 0;
2169 double promotion_ratio_ = 0.0;
2170 double promotion_rate_ = 0.0;
2171 size_t semi_space_copied_object_size_ = 0;
2172 size_t previous_semi_space_copied_object_size_ = 0;
2173 double semi_space_copied_rate_ = 0.0;
2174 int nodes_died_in_new_space_ = 0;
2175 int nodes_copied_in_new_space_ = 0;
2176 int nodes_promoted_ = 0;
2177
2178 // This is the pretenuring trigger for allocation sites that are in maybe
2179 // tenure state. When we switched to the maximum new space size we deoptimize
2180 // the code that belongs to the allocation site and derive the lifetime
2181 // of the allocation site.
2182 unsigned int maximum_size_scavenges_ = 0;
2183
2184 // Total time spent in GC.
2185 double total_gc_time_ms_ = 0.0;
2186
2187 // Last time an idle notification happened.
2188 double last_idle_notification_time_ = 0.0;
2189
2190 // Last time a garbage collection happened.
2191 double last_gc_time_ = 0.0;
2192
2193 std::unique_ptr<GCTracer> tracer_;
2194 std::unique_ptr<MarkCompactCollector> mark_compact_collector_;
2195 MinorMarkCompactCollector* minor_mark_compact_collector_ = nullptr;
2196 std::unique_ptr<ScavengerCollector> scavenger_collector_;
2197 std::unique_ptr<ArrayBufferSweeper> array_buffer_sweeper_;
2198
2199 std::unique_ptr<MemoryAllocator> memory_allocator_;
2200 std::unique_ptr<IncrementalMarking> incremental_marking_;
2201 std::unique_ptr<ConcurrentMarking> concurrent_marking_;
2202 std::unique_ptr<GCIdleTimeHandler> gc_idle_time_handler_;
2203 std::unique_ptr<MemoryMeasurement> memory_measurement_;
2204 std::unique_ptr<MemoryReducer> memory_reducer_;
2205 std::unique_ptr<ObjectStats> live_object_stats_;
2206 std::unique_ptr<ObjectStats> dead_object_stats_;
2207 std::unique_ptr<ScavengeJob> scavenge_job_;
2208 std::unique_ptr<AllocationObserver> scavenge_task_observer_;
2209 std::unique_ptr<AllocationObserver> stress_concurrent_allocation_observer_;
2210 std::unique_ptr<LocalEmbedderHeapTracer> local_embedder_heap_tracer_;
2211 std::unique_ptr<MarkingBarrier> marking_barrier_;
2212
2213 StrongRootsEntry* strong_roots_head_ = nullptr;
2214 base::Mutex strong_roots_mutex_;
2215
2216 bool need_to_remove_stress_concurrent_allocation_observer_ = false;
2217
2218 // This counter is increased before each GC and never reset.
2219 // To account for the bytes allocated since the last GC, use the
2220 // NewSpaceAllocationCounter() function.
2221 size_t new_space_allocation_counter_ = 0;
2222
2223 // This counter is increased before each GC and never reset. To
2224 // account for the bytes allocated since the last GC, use the
2225 // OldGenerationAllocationCounter() function.
2226 size_t old_generation_allocation_counter_at_last_gc_ = 0;
2227
2228 // The size of objects in old generation after the last MarkCompact GC.
2229 size_t old_generation_size_at_last_gc_{0};
2230
2231 // The size of global memory after the last MarkCompact GC.
2232 size_t global_memory_at_last_gc_ = 0;
2233
2234 // The feedback storage is used to store allocation sites (keys) and how often
2235 // they have been visited (values) by finding a memento behind an object. The
2236 // storage is only alive temporary during a GC. The invariant is that all
2237 // pointers in this map are already fixed, i.e., they do not point to
2238 // forwarding pointers.
2239 PretenuringFeedbackMap global_pretenuring_feedback_;
2240
2241 char trace_ring_buffer_[kTraceRingBufferSize];
2242
2243 // Used as boolean.
2244 uint8_t is_marking_flag_ = 0;
2245
2246 // If it's not full then the data is from 0 to ring_buffer_end_. If it's
2247 // full then the data is from ring_buffer_end_ to the end of the buffer and
2248 // from 0 to ring_buffer_end_.
2249 bool ring_buffer_full_ = false;
2250 size_t ring_buffer_end_ = 0;
2251
2252 // Flag is set when the heap has been configured. The heap can be repeatedly
2253 // configured through the API until it is set up.
2254 bool configured_ = false;
2255
2256 // Currently set GC flags that are respected by all GC components.
2257 int current_gc_flags_ = Heap::kNoGCFlags;
2258
2259 // Currently set GC callback flags that are used to pass information between
2260 // the embedder and V8's GC.
2261 GCCallbackFlags current_gc_callback_flags_ =
2262 GCCallbackFlags::kNoGCCallbackFlags;
2263
2264 std::unique_ptr<GlobalSafepoint> safepoint_;
2265
2266 bool is_current_gc_forced_ = false;
2267
2268 ExternalStringTable external_string_table_;
2269
2270 base::Mutex relocation_mutex_;
2271
2272 std::unique_ptr<CollectionBarrier> collection_barrier_;
2273
2274 int gc_callbacks_depth_ = 0;
2275
2276 bool deserialization_complete_ = false;
2277
2278 bool fast_promotion_mode_ = false;
2279
2280 // Used for testing purposes.
2281 bool force_oom_ = false;
2282 bool force_gc_on_next_allocation_ = false;
2283 bool delay_sweeper_tasks_for_testing_ = false;
2284
2285 HeapObject pending_layout_change_object_;
2286
2287 base::Mutex unprotected_memory_chunks_mutex_;
2288 std::unordered_set<MemoryChunk*> unprotected_memory_chunks_;
2289 bool unprotected_memory_chunks_registry_enabled_ = false;
2290
2291 #ifdef V8_ENABLE_ALLOCATION_TIMEOUT
2292 // If the --gc-interval flag is set to a positive value, this
2293 // variable holds the value indicating the number of allocations
2294 // remain until the next failure and garbage collection.
2295 int allocation_timeout_ = 0;
2296 #endif // V8_ENABLE_ALLOCATION_TIMEOUT
2297
2298 std::map<HeapObject, HeapObject, Object::Comparer> retainer_;
2299 std::map<HeapObject, Root, Object::Comparer> retaining_root_;
2300 // If an object is retained by an ephemeron, then the retaining key of the
2301 // ephemeron is stored in this map.
2302 std::map<HeapObject, HeapObject, Object::Comparer> ephemeron_retainer_;
2303 // For each index inthe retaining_path_targets_ array this map
2304 // stores the option of the corresponding target.
2305 std::map<int, RetainingPathOption> retaining_path_target_option_;
2306
2307 std::vector<HeapObjectAllocationTracker*> allocation_trackers_;
2308
2309 bool is_finalization_registry_cleanup_task_posted_ = false;
2310
2311 std::unique_ptr<third_party_heap::Heap> tp_heap_;
2312
2313 // Classes in "heap" can be friends.
2314 friend class AlwaysAllocateScope;
2315 friend class ArrayBufferCollector;
2316 friend class ArrayBufferSweeper;
2317 friend class ConcurrentMarking;
2318 friend class GCCallbacksScope;
2319 friend class GCTracer;
2320 friend class HeapObjectIterator;
2321 friend class ScavengeTaskObserver;
2322 friend class IncrementalMarking;
2323 friend class IncrementalMarkingJob;
2324 friend class OldLargeObjectSpace;
2325 template <typename ConcreteVisitor, typename MarkingState>
2326 friend class MarkingVisitorBase;
2327 friend class MarkCompactCollector;
2328 friend class MarkCompactCollectorBase;
2329 friend class MinorMarkCompactCollector;
2330 friend class NewLargeObjectSpace;
2331 friend class NewSpace;
2332 friend class ObjectStatsCollector;
2333 friend class Page;
2334 friend class PagedSpace;
2335 friend class ReadOnlyRoots;
2336 friend class Scavenger;
2337 friend class ScavengerCollector;
2338 friend class StressConcurrentAllocationObserver;
2339 friend class Space;
2340 friend class Sweeper;
2341 friend class heap::TestMemoryAllocatorScope;
2342
2343 // The allocator interface.
2344 friend class Factory;
2345 friend class Deserializer;
2346
2347 // The Isolate constructs us.
2348 friend class Isolate;
2349
2350 // Used in cctest.
2351 friend class heap::HeapTester;
2352
2353 DISALLOW_COPY_AND_ASSIGN(Heap);
2354 };
2355
2356 class HeapStats {
2357 public:
2358 static const int kStartMarker = 0xDECADE00;
2359 static const int kEndMarker = 0xDECADE01;
2360
2361 intptr_t* start_marker; // 0
2362 size_t* ro_space_size; // 1
2363 size_t* ro_space_capacity; // 2
2364 size_t* new_space_size; // 3
2365 size_t* new_space_capacity; // 4
2366 size_t* old_space_size; // 5
2367 size_t* old_space_capacity; // 6
2368 size_t* code_space_size; // 7
2369 size_t* code_space_capacity; // 8
2370 size_t* map_space_size; // 9
2371 size_t* map_space_capacity; // 10
2372 size_t* lo_space_size; // 11
2373 size_t* code_lo_space_size; // 12
2374 size_t* global_handle_count; // 13
2375 size_t* weak_global_handle_count; // 14
2376 size_t* pending_global_handle_count; // 15
2377 size_t* near_death_global_handle_count; // 16
2378 size_t* free_global_handle_count; // 17
2379 size_t* memory_allocator_size; // 18
2380 size_t* memory_allocator_capacity; // 19
2381 size_t* malloced_memory; // 20
2382 size_t* malloced_peak_memory; // 21
2383 size_t* objects_per_type; // 22
2384 size_t* size_per_type; // 23
2385 int* os_error; // 24
2386 char* last_few_messages; // 25
2387 char* js_stacktrace; // 26
2388 intptr_t* end_marker; // 27
2389 };
2390
2391 // Disables GC for all allocations. It should not be used
2392 // outside heap, deserializer, and isolate bootstrap.
2393 // Use AlwaysAllocateScopeForTesting in tests.
2394 class AlwaysAllocateScope {
2395 public:
2396 inline ~AlwaysAllocateScope();
2397
2398 private:
2399 friend class AlwaysAllocateScopeForTesting;
2400 friend class Deserializer;
2401 friend class DeserializerAllocator;
2402 friend class Evacuator;
2403 friend class Heap;
2404 friend class Isolate;
2405
2406 explicit inline AlwaysAllocateScope(Heap* heap);
2407 Heap* heap_;
2408 };
2409
2410 class AlwaysAllocateScopeForTesting {
2411 public:
2412 explicit inline AlwaysAllocateScopeForTesting(Heap* heap);
2413
2414 private:
2415 AlwaysAllocateScope scope_;
2416 };
2417
2418 // The CodeSpaceMemoryModificationScope can only be used by the main thread.
2419 class CodeSpaceMemoryModificationScope {
2420 public:
2421 explicit inline CodeSpaceMemoryModificationScope(Heap* heap);
2422 inline ~CodeSpaceMemoryModificationScope();
2423
2424 private:
2425 Heap* heap_;
2426 };
2427
2428 // The CodePageCollectionMemoryModificationScope can only be used by the main
2429 // thread. It will not be enabled if a CodeSpaceMemoryModificationScope is
2430 // already active.
2431 class CodePageCollectionMemoryModificationScope {
2432 public:
2433 explicit inline CodePageCollectionMemoryModificationScope(Heap* heap);
2434 inline ~CodePageCollectionMemoryModificationScope();
2435
2436 private:
2437 Heap* heap_;
2438 };
2439
2440 // The CodePageMemoryModificationScope does not check if tansitions to
2441 // writeable and back to executable are actually allowed, i.e. the MemoryChunk
2442 // was registered to be executable. It can be used by concurrent threads.
2443 class CodePageMemoryModificationScope {
2444 public:
2445 explicit inline CodePageMemoryModificationScope(BasicMemoryChunk* chunk);
2446 explicit inline CodePageMemoryModificationScope(Code object);
2447 inline ~CodePageMemoryModificationScope();
2448
2449 private:
2450 BasicMemoryChunk* chunk_;
2451 bool scope_active_;
2452
2453 // Disallow any GCs inside this scope, as a relocation of the underlying
2454 // object would change the {MemoryChunk} that this scope targets.
2455 DISALLOW_HEAP_ALLOCATION(no_heap_allocation_)
2456 };
2457
2458 // Visitor class to verify interior pointers in spaces that do not contain
2459 // or care about intergenerational references. All heap object pointers have to
2460 // point into the heap to a location that has a map pointer at its first word.
2461 // Caveat: Heap::Contains is an approximation because it can return true for
2462 // objects in a heap space but above the allocation pointer.
2463 class VerifyPointersVisitor : public ObjectVisitor, public RootVisitor {
2464 public:
VerifyPointersVisitor(Heap * heap)2465 explicit VerifyPointersVisitor(Heap* heap) : heap_(heap) {}
2466 void VisitPointers(HeapObject host, ObjectSlot start,
2467 ObjectSlot end) override;
2468 void VisitPointers(HeapObject host, MaybeObjectSlot start,
2469 MaybeObjectSlot end) override;
2470 void VisitCodeTarget(Code host, RelocInfo* rinfo) override;
2471 void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override;
2472
2473 void VisitRootPointers(Root root, const char* description,
2474 FullObjectSlot start, FullObjectSlot end) override;
2475 void VisitRootPointers(Root root, const char* description,
2476 OffHeapObjectSlot start,
2477 OffHeapObjectSlot end) override;
2478
2479 protected:
2480 V8_INLINE void VerifyHeapObjectImpl(HeapObject heap_object);
2481
2482 template <typename TSlot>
2483 V8_INLINE void VerifyPointersImpl(TSlot start, TSlot end);
2484
2485 virtual void VerifyPointers(HeapObject host, MaybeObjectSlot start,
2486 MaybeObjectSlot end);
2487
2488 Heap* heap_;
2489 };
2490
2491 // Verify that all objects are Smis.
2492 class VerifySmisVisitor : public RootVisitor {
2493 public:
2494 void VisitRootPointers(Root root, const char* description,
2495 FullObjectSlot start, FullObjectSlot end) override;
2496 };
2497
2498 // Space iterator for iterating over all the paged spaces of the heap: Map
2499 // space, old space and code space. Returns each space in turn, and null when it
2500 // is done.
2501 class V8_EXPORT_PRIVATE PagedSpaceIterator {
2502 public:
PagedSpaceIterator(Heap * heap)2503 explicit PagedSpaceIterator(Heap* heap)
2504 : heap_(heap), counter_(FIRST_GROWABLE_PAGED_SPACE) {}
2505 PagedSpace* Next();
2506
2507 private:
2508 Heap* heap_;
2509 int counter_;
2510 };
2511
2512 class V8_EXPORT_PRIVATE SpaceIterator : public Malloced {
2513 public:
2514 explicit SpaceIterator(Heap* heap);
2515 virtual ~SpaceIterator();
2516
2517 bool HasNext();
2518 Space* Next();
2519
2520 private:
2521 Heap* heap_;
2522 int current_space_; // from enum AllocationSpace.
2523 };
2524
2525 // A HeapObjectIterator provides iteration over the entire non-read-only heap.
2526 // It aggregates the specific iterators for the different spaces as these can
2527 // only iterate over one space only.
2528 //
2529 // HeapObjectIterator ensures there is no allocation during its lifetime (using
2530 // an embedded DisallowHeapAllocation instance).
2531 //
2532 // HeapObjectIterator can skip free list nodes (that is, de-allocated heap
2533 // objects that still remain in the heap). As implementation of free nodes
2534 // filtering uses GC marks, it can't be used during MS/MC GC phases. Also, it is
2535 // forbidden to interrupt iteration in this mode, as this will leave heap
2536 // objects marked (and thus, unusable).
2537 //
2538 // See ReadOnlyHeapObjectIterator if you need to iterate over read-only space
2539 // objects, or CombinedHeapObjectIterator if you need to iterate over both
2540 // heaps.
2541 class V8_EXPORT_PRIVATE HeapObjectIterator {
2542 public:
2543 enum HeapObjectsFiltering { kNoFiltering, kFilterUnreachable };
2544
2545 explicit HeapObjectIterator(Heap* heap,
2546 HeapObjectsFiltering filtering = kNoFiltering);
2547 ~HeapObjectIterator();
2548
2549 HeapObject Next();
2550
2551 private:
2552 HeapObject NextObject();
2553
2554 DISALLOW_HEAP_ALLOCATION(no_heap_allocation_)
2555
2556 Heap* heap_;
2557 std::unique_ptr<SafepointScope> safepoint_scope_;
2558 HeapObjectsFiltering filtering_;
2559 HeapObjectsFilter* filter_;
2560 // Space iterator for iterating all the spaces.
2561 SpaceIterator* space_iterator_;
2562 // Object iterator for the space currently being iterated.
2563 std::unique_ptr<ObjectIterator> object_iterator_;
2564 };
2565
2566 // Abstract base class for checking whether a weak object should be retained.
2567 class WeakObjectRetainer {
2568 public:
2569 virtual ~WeakObjectRetainer() = default;
2570
2571 // Return whether this object should be retained. If nullptr is returned the
2572 // object has no references. Otherwise the address of the retained object
2573 // should be returned as in some GC situations the object has been moved.
2574 virtual Object RetainAs(Object object) = 0;
2575 };
2576
2577 // -----------------------------------------------------------------------------
2578 // Allows observation of heap object allocations.
2579 class HeapObjectAllocationTracker {
2580 public:
2581 virtual void AllocationEvent(Address addr, int size) = 0;
MoveEvent(Address from,Address to,int size)2582 virtual void MoveEvent(Address from, Address to, int size) {}
UpdateObjectSizeEvent(Address addr,int size)2583 virtual void UpdateObjectSizeEvent(Address addr, int size) {}
2584 virtual ~HeapObjectAllocationTracker() = default;
2585 };
2586
2587 template <typename T>
ForwardingAddress(T heap_obj)2588 T ForwardingAddress(T heap_obj) {
2589 MapWord map_word = heap_obj.map_word();
2590
2591 if (map_word.IsForwardingAddress()) {
2592 return T::cast(map_word.ToForwardingAddress());
2593 } else if (Heap::InFromPage(heap_obj)) {
2594 return T();
2595 } else {
2596 // TODO(ulan): Support minor mark-compactor here.
2597 return heap_obj;
2598 }
2599 }
2600
2601 // Address block allocator compatible with standard containers which registers
2602 // its allocated range as strong roots.
2603 class StrongRootBlockAllocator {
2604 public:
2605 using pointer = Address*;
2606 using const_pointer = const Address*;
2607 using reference = Address&;
2608 using const_reference = const Address&;
2609 using value_type = Address;
2610 using size_type = size_t;
2611 using difference_type = ptrdiff_t;
2612 template <class U>
2613 struct rebind {
2614 STATIC_ASSERT((std::is_same<Address, U>::value));
2615 using other = StrongRootBlockAllocator;
2616 };
2617
StrongRootBlockAllocator(Heap * heap)2618 explicit StrongRootBlockAllocator(Heap* heap) : heap_(heap) {}
2619
2620 Address* allocate(size_t n);
2621 void deallocate(Address* p, size_t n) noexcept;
2622
2623 private:
2624 Heap* heap_;
2625 };
2626
2627 } // namespace internal
2628 } // namespace v8
2629
2630 #endif // V8_HEAP_HEAP_H_
2631