1 // Copyright 2013 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.
7 #include "src/heap-snapshot-generator-inl.h"
9 #include "src/allocation-tracker.h"
10 #include "src/code-stubs.h"
11 #include "src/conversions.h"
12 #include "src/debug.h"
13 #include "src/heap-profiler.h"
14 #include "src/types.h"
20 HeapGraphEdge::HeapGraphEdge(Type type, const char* name, int from, int to)
21 : bit_field_(TypeField::encode(type) | FromIndexField::encode(from)),
24 DCHECK(type == kContextVariable
32 HeapGraphEdge::HeapGraphEdge(Type type, int index, int from, int to)
33 : bit_field_(TypeField::encode(type) | FromIndexField::encode(from)),
36 DCHECK(type == kElement || type == kHidden);
40 void HeapGraphEdge::ReplaceToIndexWithEntry(HeapSnapshot* snapshot) {
41 to_entry_ = &snapshot->entries()[to_index_];
45 const int HeapEntry::kNoEntry = -1;
47 HeapEntry::HeapEntry(HeapSnapshot* snapshot,
52 unsigned trace_node_id)
56 self_size_(self_size),
60 trace_node_id_(trace_node_id) { }
63 void HeapEntry::SetNamedReference(HeapGraphEdge::Type type,
66 HeapGraphEdge edge(type, name, this->index(), entry->index());
67 snapshot_->edges().Add(edge);
72 void HeapEntry::SetIndexedReference(HeapGraphEdge::Type type,
75 HeapGraphEdge edge(type, index, this->index(), entry->index());
76 snapshot_->edges().Add(edge);
81 void HeapEntry::Print(
82 const char* prefix, const char* edge_name, int max_depth, int indent) {
83 STATIC_ASSERT(sizeof(unsigned) == sizeof(id()));
84 base::OS::Print("%6" V8PRIuPTR " @%6u %*c %s%s: ", self_size(), id(), indent,
85 ' ', prefix, edge_name);
86 if (type() != kString) {
87 base::OS::Print("%s %.40s\n", TypeAsString(), name_);
89 base::OS::Print("\"");
90 const char* c = name_;
91 while (*c && (c - name_) <= 40) {
93 base::OS::Print("%c", *c);
95 base::OS::Print("\\n");
98 base::OS::Print("\"\n");
100 if (--max_depth == 0) return;
101 Vector<HeapGraphEdge*> ch = children();
102 for (int i = 0; i < ch.length(); ++i) {
103 HeapGraphEdge& edge = *ch[i];
104 const char* edge_prefix = "";
105 EmbeddedVector<char, 64> index;
106 const char* edge_name = index.start();
107 switch (edge.type()) {
108 case HeapGraphEdge::kContextVariable:
110 edge_name = edge.name();
112 case HeapGraphEdge::kElement:
113 SNPrintF(index, "%d", edge.index());
115 case HeapGraphEdge::kInternal:
117 edge_name = edge.name();
119 case HeapGraphEdge::kProperty:
120 edge_name = edge.name();
122 case HeapGraphEdge::kHidden:
124 SNPrintF(index, "%d", edge.index());
126 case HeapGraphEdge::kShortcut:
128 edge_name = edge.name();
130 case HeapGraphEdge::kWeak:
132 edge_name = edge.name();
135 SNPrintF(index, "!!! unknown edge type: %d ", edge.type());
137 edge.to()->Print(edge_prefix, edge_name, max_depth, indent + 2);
142 const char* HeapEntry::TypeAsString() {
144 case kHidden: return "/hidden/";
145 case kObject: return "/object/";
146 case kClosure: return "/closure/";
147 case kString: return "/string/";
148 case kCode: return "/code/";
149 case kArray: return "/array/";
150 case kRegExp: return "/regexp/";
151 case kHeapNumber: return "/number/";
152 case kNative: return "/native/";
153 case kSynthetic: return "/synthetic/";
154 case kConsString: return "/concatenated string/";
155 case kSlicedString: return "/sliced string/";
156 case kSymbol: return "/symbol/";
157 default: return "???";
162 // It is very important to keep objects that form a heap snapshot
163 // as small as possible.
164 namespace { // Avoid littering the global namespace.
166 template <size_t ptr_size> struct SnapshotSizeConstants;
168 template <> struct SnapshotSizeConstants<4> {
169 static const int kExpectedHeapGraphEdgeSize = 12;
170 static const int kExpectedHeapEntrySize = 28;
173 template <> struct SnapshotSizeConstants<8> {
174 static const int kExpectedHeapGraphEdgeSize = 24;
175 static const int kExpectedHeapEntrySize = 40;
181 HeapSnapshot::HeapSnapshot(HeapProfiler* profiler,
184 : profiler_(profiler),
187 root_index_(HeapEntry::kNoEntry),
188 gc_roots_index_(HeapEntry::kNoEntry),
189 max_snapshot_js_object_id_(0) {
191 sizeof(HeapGraphEdge) ==
192 SnapshotSizeConstants<kPointerSize>::kExpectedHeapGraphEdgeSize);
195 SnapshotSizeConstants<kPointerSize>::kExpectedHeapEntrySize);
196 USE(SnapshotSizeConstants<4>::kExpectedHeapGraphEdgeSize);
197 USE(SnapshotSizeConstants<4>::kExpectedHeapEntrySize);
198 USE(SnapshotSizeConstants<8>::kExpectedHeapGraphEdgeSize);
199 USE(SnapshotSizeConstants<8>::kExpectedHeapEntrySize);
200 for (int i = 0; i < VisitorSynchronization::kNumberOfSyncTags; ++i) {
201 gc_subroot_indexes_[i] = HeapEntry::kNoEntry;
206 void HeapSnapshot::Delete() {
207 profiler_->RemoveSnapshot(this);
212 void HeapSnapshot::RememberLastJSObjectId() {
213 max_snapshot_js_object_id_ = profiler_->heap_object_map()->last_assigned_id();
217 void HeapSnapshot::AddSyntheticRootEntries() {
220 SnapshotObjectId id = HeapObjectsMap::kGcRootsFirstSubrootId;
221 for (int tag = 0; tag < VisitorSynchronization::kNumberOfSyncTags; tag++) {
222 AddGcSubrootEntry(tag, id);
223 id += HeapObjectsMap::kObjectIdStep;
225 DCHECK(HeapObjectsMap::kFirstAvailableObjectId == id);
229 HeapEntry* HeapSnapshot::AddRootEntry() {
230 DCHECK(root_index_ == HeapEntry::kNoEntry);
231 DCHECK(entries_.is_empty()); // Root entry must be the first one.
232 HeapEntry* entry = AddEntry(HeapEntry::kSynthetic,
234 HeapObjectsMap::kInternalRootObjectId,
237 root_index_ = entry->index();
238 DCHECK(root_index_ == 0);
243 HeapEntry* HeapSnapshot::AddGcRootsEntry() {
244 DCHECK(gc_roots_index_ == HeapEntry::kNoEntry);
245 HeapEntry* entry = AddEntry(HeapEntry::kSynthetic,
247 HeapObjectsMap::kGcRootsObjectId,
250 gc_roots_index_ = entry->index();
255 HeapEntry* HeapSnapshot::AddGcSubrootEntry(int tag, SnapshotObjectId id) {
256 DCHECK(gc_subroot_indexes_[tag] == HeapEntry::kNoEntry);
257 DCHECK(0 <= tag && tag < VisitorSynchronization::kNumberOfSyncTags);
258 HeapEntry* entry = AddEntry(HeapEntry::kSynthetic,
259 VisitorSynchronization::kTagNames[tag], id, 0, 0);
260 gc_subroot_indexes_[tag] = entry->index();
265 HeapEntry* HeapSnapshot::AddEntry(HeapEntry::Type type,
269 unsigned trace_node_id) {
270 HeapEntry entry(this, type, name, id, size, trace_node_id);
272 return &entries_.last();
276 void HeapSnapshot::FillChildren() {
277 DCHECK(children().is_empty());
278 children().Allocate(edges().length());
279 int children_index = 0;
280 for (int i = 0; i < entries().length(); ++i) {
281 HeapEntry* entry = &entries()[i];
282 children_index = entry->set_children_index(children_index);
284 DCHECK(edges().length() == children_index);
285 for (int i = 0; i < edges().length(); ++i) {
286 HeapGraphEdge* edge = &edges()[i];
287 edge->ReplaceToIndexWithEntry(this);
288 edge->from()->add_child(edge);
293 class FindEntryById {
295 explicit FindEntryById(SnapshotObjectId id) : id_(id) { }
296 int operator()(HeapEntry* const* entry) {
297 if ((*entry)->id() == id_) return 0;
298 return (*entry)->id() < id_ ? -1 : 1;
301 SnapshotObjectId id_;
305 HeapEntry* HeapSnapshot::GetEntryById(SnapshotObjectId id) {
306 List<HeapEntry*>* entries_by_id = GetSortedEntriesList();
307 // Perform a binary search by id.
308 int index = SortedListBSearch(*entries_by_id, FindEntryById(id));
311 return entries_by_id->at(index);
316 static int SortByIds(const T* entry1_ptr,
317 const T* entry2_ptr) {
318 if ((*entry1_ptr)->id() == (*entry2_ptr)->id()) return 0;
319 return (*entry1_ptr)->id() < (*entry2_ptr)->id() ? -1 : 1;
323 List<HeapEntry*>* HeapSnapshot::GetSortedEntriesList() {
324 if (sorted_entries_.is_empty()) {
325 sorted_entries_.Allocate(entries_.length());
326 for (int i = 0; i < entries_.length(); ++i) {
327 sorted_entries_[i] = &entries_[i];
329 sorted_entries_.Sort(SortByIds);
331 return &sorted_entries_;
335 void HeapSnapshot::Print(int max_depth) {
336 root()->Print("", "", max_depth, 0);
340 size_t HeapSnapshot::RawSnapshotSize() const {
343 GetMemoryUsedByList(entries_) +
344 GetMemoryUsedByList(edges_) +
345 GetMemoryUsedByList(children_) +
346 GetMemoryUsedByList(sorted_entries_);
350 // We split IDs on evens for embedder objects (see
351 // HeapObjectsMap::GenerateId) and odds for native objects.
352 const SnapshotObjectId HeapObjectsMap::kInternalRootObjectId = 1;
353 const SnapshotObjectId HeapObjectsMap::kGcRootsObjectId =
354 HeapObjectsMap::kInternalRootObjectId + HeapObjectsMap::kObjectIdStep;
355 const SnapshotObjectId HeapObjectsMap::kGcRootsFirstSubrootId =
356 HeapObjectsMap::kGcRootsObjectId + HeapObjectsMap::kObjectIdStep;
357 const SnapshotObjectId HeapObjectsMap::kFirstAvailableObjectId =
358 HeapObjectsMap::kGcRootsFirstSubrootId +
359 VisitorSynchronization::kNumberOfSyncTags * HeapObjectsMap::kObjectIdStep;
362 static bool AddressesMatch(void* key1, void* key2) {
367 HeapObjectsMap::HeapObjectsMap(Heap* heap)
368 : next_id_(kFirstAvailableObjectId),
369 entries_map_(AddressesMatch),
371 // This dummy element solves a problem with entries_map_.
372 // When we do lookup in HashMap we see no difference between two cases:
373 // it has an entry with NULL as the value or it has created
374 // a new entry on the fly with NULL as the default value.
375 // With such dummy element we have a guaranty that all entries_map_ entries
376 // will have the value field grater than 0.
377 // This fact is using in MoveObject method.
378 entries_.Add(EntryInfo(0, NULL, 0));
382 bool HeapObjectsMap::MoveObject(Address from, Address to, int object_size) {
384 DCHECK(from != NULL);
385 if (from == to) return false;
386 void* from_value = entries_map_.Remove(from, ComputePointerHash(from));
387 if (from_value == NULL) {
388 // It may occur that some untracked object moves to an address X and there
389 // is a tracked object at that address. In this case we should remove the
390 // entry as we know that the object has died.
391 void* to_value = entries_map_.Remove(to, ComputePointerHash(to));
392 if (to_value != NULL) {
393 int to_entry_info_index =
394 static_cast<int>(reinterpret_cast<intptr_t>(to_value));
395 entries_.at(to_entry_info_index).addr = NULL;
398 HashMap::Entry* to_entry = entries_map_.Lookup(to, ComputePointerHash(to),
400 if (to_entry->value != NULL) {
401 // We found the existing entry with to address for an old object.
402 // Without this operation we will have two EntryInfo's with the same
403 // value in addr field. It is bad because later at RemoveDeadEntries
404 // one of this entry will be removed with the corresponding entries_map_
406 int to_entry_info_index =
407 static_cast<int>(reinterpret_cast<intptr_t>(to_entry->value));
408 entries_.at(to_entry_info_index).addr = NULL;
410 int from_entry_info_index =
411 static_cast<int>(reinterpret_cast<intptr_t>(from_value));
412 entries_.at(from_entry_info_index).addr = to;
413 // Size of an object can change during its life, so to keep information
414 // about the object in entries_ consistent, we have to adjust size when the
415 // object is migrated.
416 if (FLAG_heap_profiler_trace_objects) {
417 PrintF("Move object from %p to %p old size %6d new size %6d\n",
420 entries_.at(from_entry_info_index).size,
423 entries_.at(from_entry_info_index).size = object_size;
424 to_entry->value = from_value;
426 return from_value != NULL;
430 void HeapObjectsMap::UpdateObjectSize(Address addr, int size) {
431 FindOrAddEntry(addr, size, false);
435 SnapshotObjectId HeapObjectsMap::FindEntry(Address addr) {
436 HashMap::Entry* entry = entries_map_.Lookup(addr, ComputePointerHash(addr),
438 if (entry == NULL) return 0;
439 int entry_index = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
440 EntryInfo& entry_info = entries_.at(entry_index);
441 DCHECK(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
442 return entry_info.id;
446 SnapshotObjectId HeapObjectsMap::FindOrAddEntry(Address addr,
449 DCHECK(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
450 HashMap::Entry* entry = entries_map_.Lookup(addr, ComputePointerHash(addr),
452 if (entry->value != NULL) {
454 static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
455 EntryInfo& entry_info = entries_.at(entry_index);
456 entry_info.accessed = accessed;
457 if (FLAG_heap_profiler_trace_objects) {
458 PrintF("Update object size : %p with old size %d and new size %d\n",
463 entry_info.size = size;
464 return entry_info.id;
466 entry->value = reinterpret_cast<void*>(entries_.length());
467 SnapshotObjectId id = next_id_;
468 next_id_ += kObjectIdStep;
469 entries_.Add(EntryInfo(id, addr, size, accessed));
470 DCHECK(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
475 void HeapObjectsMap::StopHeapObjectsTracking() {
476 time_intervals_.Clear();
480 void HeapObjectsMap::UpdateHeapObjectsMap() {
481 if (FLAG_heap_profiler_trace_objects) {
482 PrintF("Begin HeapObjectsMap::UpdateHeapObjectsMap. map has %d entries.\n",
483 entries_map_.occupancy());
485 heap_->CollectAllGarbage(Heap::kMakeHeapIterableMask,
486 "HeapObjectsMap::UpdateHeapObjectsMap");
487 HeapIterator iterator(heap_);
488 for (HeapObject* obj = iterator.next();
490 obj = iterator.next()) {
491 FindOrAddEntry(obj->address(), obj->Size());
492 if (FLAG_heap_profiler_trace_objects) {
493 PrintF("Update object : %p %6d. Next address is %p\n",
496 obj->address() + obj->Size());
500 if (FLAG_heap_profiler_trace_objects) {
501 PrintF("End HeapObjectsMap::UpdateHeapObjectsMap. map has %d entries.\n",
502 entries_map_.occupancy());
510 struct HeapObjectInfo {
511 HeapObjectInfo(HeapObject* obj, int expected_size)
513 expected_size(expected_size) {
519 bool IsValid() const { return expected_size == obj->Size(); }
522 if (expected_size == 0) {
523 PrintF("Untracked object : %p %6d. Next address is %p\n",
526 obj->address() + obj->Size());
527 } else if (obj->Size() != expected_size) {
528 PrintF("Wrong size %6d: %p %6d. Next address is %p\n",
532 obj->address() + obj->Size());
534 PrintF("Good object : %p %6d. Next address is %p\n",
537 obj->address() + obj->Size());
543 static int comparator(const HeapObjectInfo* a, const HeapObjectInfo* b) {
544 if (a->obj < b->obj) return -1;
545 if (a->obj > b->obj) return 1;
553 int HeapObjectsMap::FindUntrackedObjects() {
554 List<HeapObjectInfo> heap_objects(1000);
556 HeapIterator iterator(heap_);
558 for (HeapObject* obj = iterator.next();
560 obj = iterator.next()) {
561 HashMap::Entry* entry = entries_map_.Lookup(
562 obj->address(), ComputePointerHash(obj->address()), false);
565 if (FLAG_heap_profiler_trace_objects) {
566 heap_objects.Add(HeapObjectInfo(obj, 0));
569 int entry_index = static_cast<int>(
570 reinterpret_cast<intptr_t>(entry->value));
571 EntryInfo& entry_info = entries_.at(entry_index);
572 if (FLAG_heap_profiler_trace_objects) {
573 heap_objects.Add(HeapObjectInfo(obj,
574 static_cast<int>(entry_info.size)));
575 if (obj->Size() != static_cast<int>(entry_info.size))
578 CHECK_EQ(obj->Size(), static_cast<int>(entry_info.size));
582 if (FLAG_heap_profiler_trace_objects) {
583 PrintF("\nBegin HeapObjectsMap::FindUntrackedObjects. %d entries in map.\n",
584 entries_map_.occupancy());
585 heap_objects.Sort(comparator);
586 int last_printed_object = -1;
587 bool print_next_object = false;
588 for (int i = 0; i < heap_objects.length(); ++i) {
589 const HeapObjectInfo& object_info = heap_objects[i];
590 if (!object_info.IsValid()) {
592 if (last_printed_object != i - 1) {
594 PrintF("%d objects were skipped\n", i - 1 - last_printed_object);
595 heap_objects[i - 1].Print();
599 last_printed_object = i;
600 print_next_object = true;
601 } else if (print_next_object) {
603 print_next_object = false;
604 last_printed_object = i;
607 if (last_printed_object < heap_objects.length() - 1) {
608 PrintF("Last %d objects were skipped\n",
609 heap_objects.length() - 1 - last_printed_object);
611 PrintF("End HeapObjectsMap::FindUntrackedObjects. %d entries in map.\n\n",
612 entries_map_.occupancy());
618 SnapshotObjectId HeapObjectsMap::PushHeapObjectsStats(OutputStream* stream) {
619 UpdateHeapObjectsMap();
620 time_intervals_.Add(TimeInterval(next_id_));
621 int prefered_chunk_size = stream->GetChunkSize();
622 List<v8::HeapStatsUpdate> stats_buffer;
623 DCHECK(!entries_.is_empty());
624 EntryInfo* entry_info = &entries_.first();
625 EntryInfo* end_entry_info = &entries_.last() + 1;
626 for (int time_interval_index = 0;
627 time_interval_index < time_intervals_.length();
628 ++time_interval_index) {
629 TimeInterval& time_interval = time_intervals_[time_interval_index];
630 SnapshotObjectId time_interval_id = time_interval.id;
631 uint32_t entries_size = 0;
632 EntryInfo* start_entry_info = entry_info;
633 while (entry_info < end_entry_info && entry_info->id < time_interval_id) {
634 entries_size += entry_info->size;
637 uint32_t entries_count =
638 static_cast<uint32_t>(entry_info - start_entry_info);
639 if (time_interval.count != entries_count ||
640 time_interval.size != entries_size) {
641 stats_buffer.Add(v8::HeapStatsUpdate(
643 time_interval.count = entries_count,
644 time_interval.size = entries_size));
645 if (stats_buffer.length() >= prefered_chunk_size) {
646 OutputStream::WriteResult result = stream->WriteHeapStatsChunk(
647 &stats_buffer.first(), stats_buffer.length());
648 if (result == OutputStream::kAbort) return last_assigned_id();
649 stats_buffer.Clear();
653 DCHECK(entry_info == end_entry_info);
654 if (!stats_buffer.is_empty()) {
655 OutputStream::WriteResult result = stream->WriteHeapStatsChunk(
656 &stats_buffer.first(), stats_buffer.length());
657 if (result == OutputStream::kAbort) return last_assigned_id();
659 stream->EndOfStream();
660 return last_assigned_id();
664 void HeapObjectsMap::RemoveDeadEntries() {
665 DCHECK(entries_.length() > 0 &&
666 entries_.at(0).id == 0 &&
667 entries_.at(0).addr == NULL);
668 int first_free_entry = 1;
669 for (int i = 1; i < entries_.length(); ++i) {
670 EntryInfo& entry_info = entries_.at(i);
671 if (entry_info.accessed) {
672 if (first_free_entry != i) {
673 entries_.at(first_free_entry) = entry_info;
675 entries_.at(first_free_entry).accessed = false;
676 HashMap::Entry* entry = entries_map_.Lookup(
677 entry_info.addr, ComputePointerHash(entry_info.addr), false);
679 entry->value = reinterpret_cast<void*>(first_free_entry);
682 if (entry_info.addr) {
683 entries_map_.Remove(entry_info.addr,
684 ComputePointerHash(entry_info.addr));
688 entries_.Rewind(first_free_entry);
689 DCHECK(static_cast<uint32_t>(entries_.length()) - 1 ==
690 entries_map_.occupancy());
694 SnapshotObjectId HeapObjectsMap::GenerateId(v8::RetainedObjectInfo* info) {
695 SnapshotObjectId id = static_cast<SnapshotObjectId>(info->GetHash());
696 const char* label = info->GetLabel();
697 id ^= StringHasher::HashSequentialString(label,
698 static_cast<int>(strlen(label)),
700 intptr_t element_count = info->GetElementCount();
701 if (element_count != -1)
702 id ^= ComputeIntegerHash(static_cast<uint32_t>(element_count),
703 v8::internal::kZeroHashSeed);
708 size_t HeapObjectsMap::GetUsedMemorySize() const {
711 sizeof(HashMap::Entry) * entries_map_.capacity() +
712 GetMemoryUsedByList(entries_) +
713 GetMemoryUsedByList(time_intervals_);
717 HeapEntriesMap::HeapEntriesMap()
718 : entries_(HashMap::PointersMatch) {
722 int HeapEntriesMap::Map(HeapThing thing) {
723 HashMap::Entry* cache_entry = entries_.Lookup(thing, Hash(thing), false);
724 if (cache_entry == NULL) return HeapEntry::kNoEntry;
725 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
729 void HeapEntriesMap::Pair(HeapThing thing, int entry) {
730 HashMap::Entry* cache_entry = entries_.Lookup(thing, Hash(thing), true);
731 DCHECK(cache_entry->value == NULL);
732 cache_entry->value = reinterpret_cast<void*>(static_cast<intptr_t>(entry));
736 HeapObjectsSet::HeapObjectsSet()
737 : entries_(HashMap::PointersMatch) {
741 void HeapObjectsSet::Clear() {
746 bool HeapObjectsSet::Contains(Object* obj) {
747 if (!obj->IsHeapObject()) return false;
748 HeapObject* object = HeapObject::cast(obj);
749 return entries_.Lookup(object, HeapEntriesMap::Hash(object), false) != NULL;
753 void HeapObjectsSet::Insert(Object* obj) {
754 if (!obj->IsHeapObject()) return;
755 HeapObject* object = HeapObject::cast(obj);
756 entries_.Lookup(object, HeapEntriesMap::Hash(object), true);
760 const char* HeapObjectsSet::GetTag(Object* obj) {
761 HeapObject* object = HeapObject::cast(obj);
762 HashMap::Entry* cache_entry =
763 entries_.Lookup(object, HeapEntriesMap::Hash(object), false);
764 return cache_entry != NULL
765 ? reinterpret_cast<const char*>(cache_entry->value)
770 void HeapObjectsSet::SetTag(Object* obj, const char* tag) {
771 if (!obj->IsHeapObject()) return;
772 HeapObject* object = HeapObject::cast(obj);
773 HashMap::Entry* cache_entry =
774 entries_.Lookup(object, HeapEntriesMap::Hash(object), true);
775 cache_entry->value = const_cast<char*>(tag);
779 V8HeapExplorer::V8HeapExplorer(
780 HeapSnapshot* snapshot,
781 SnapshottingProgressReportingInterface* progress,
782 v8::HeapProfiler::ObjectNameResolver* resolver)
783 : heap_(snapshot->profiler()->heap_object_map()->heap()),
785 names_(snapshot_->profiler()->names()),
786 heap_object_map_(snapshot_->profiler()->heap_object_map()),
789 global_object_name_resolver_(resolver) {
793 V8HeapExplorer::~V8HeapExplorer() {
797 HeapEntry* V8HeapExplorer::AllocateEntry(HeapThing ptr) {
798 return AddEntry(reinterpret_cast<HeapObject*>(ptr));
802 HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object) {
803 if (object->IsJSFunction()) {
804 JSFunction* func = JSFunction::cast(object);
805 SharedFunctionInfo* shared = func->shared();
806 const char* name = shared->bound() ? "native_bind" :
807 names_->GetName(String::cast(shared->name()));
808 return AddEntry(object, HeapEntry::kClosure, name);
809 } else if (object->IsJSRegExp()) {
810 JSRegExp* re = JSRegExp::cast(object);
811 return AddEntry(object,
813 names_->GetName(re->Pattern()));
814 } else if (object->IsJSObject()) {
815 const char* name = names_->GetName(
816 GetConstructorName(JSObject::cast(object)));
817 if (object->IsJSGlobalObject()) {
818 const char* tag = objects_tags_.GetTag(object);
820 name = names_->GetFormatted("%s / %s", name, tag);
823 return AddEntry(object, HeapEntry::kObject, name);
824 } else if (object->IsString()) {
825 String* string = String::cast(object);
826 if (string->IsConsString())
827 return AddEntry(object,
828 HeapEntry::kConsString,
829 "(concatenated string)");
830 if (string->IsSlicedString())
831 return AddEntry(object,
832 HeapEntry::kSlicedString,
834 return AddEntry(object,
836 names_->GetName(String::cast(object)));
837 } else if (object->IsSymbol()) {
838 return AddEntry(object, HeapEntry::kSymbol, "symbol");
839 } else if (object->IsCode()) {
840 return AddEntry(object, HeapEntry::kCode, "");
841 } else if (object->IsSharedFunctionInfo()) {
842 String* name = String::cast(SharedFunctionInfo::cast(object)->name());
843 return AddEntry(object,
845 names_->GetName(name));
846 } else if (object->IsScript()) {
847 Object* name = Script::cast(object)->name();
848 return AddEntry(object,
851 ? names_->GetName(String::cast(name))
853 } else if (object->IsNativeContext()) {
854 return AddEntry(object, HeapEntry::kHidden, "system / NativeContext");
855 } else if (object->IsContext()) {
856 return AddEntry(object, HeapEntry::kObject, "system / Context");
857 } else if (object->IsFixedArray() ||
858 object->IsFixedDoubleArray() ||
859 object->IsByteArray() ||
860 object->IsExternalArray()) {
861 return AddEntry(object, HeapEntry::kArray, "");
862 } else if (object->IsHeapNumber()) {
863 return AddEntry(object, HeapEntry::kHeapNumber, "number");
865 return AddEntry(object, HeapEntry::kHidden, GetSystemEntryName(object));
869 HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object,
870 HeapEntry::Type type,
872 return AddEntry(object->address(), type, name, object->Size());
876 HeapEntry* V8HeapExplorer::AddEntry(Address address,
877 HeapEntry::Type type,
880 SnapshotObjectId object_id = heap_object_map_->FindOrAddEntry(
881 address, static_cast<unsigned int>(size));
882 unsigned trace_node_id = 0;
883 if (AllocationTracker* allocation_tracker =
884 snapshot_->profiler()->allocation_tracker()) {
886 allocation_tracker->address_to_trace()->GetTraceNodeId(address);
888 return snapshot_->AddEntry(type, name, object_id, size, trace_node_id);
892 class SnapshotFiller {
894 explicit SnapshotFiller(HeapSnapshot* snapshot, HeapEntriesMap* entries)
895 : snapshot_(snapshot),
896 names_(snapshot->profiler()->names()),
897 entries_(entries) { }
898 HeapEntry* AddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
899 HeapEntry* entry = allocator->AllocateEntry(ptr);
900 entries_->Pair(ptr, entry->index());
903 HeapEntry* FindEntry(HeapThing ptr) {
904 int index = entries_->Map(ptr);
905 return index != HeapEntry::kNoEntry ? &snapshot_->entries()[index] : NULL;
907 HeapEntry* FindOrAddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
908 HeapEntry* entry = FindEntry(ptr);
909 return entry != NULL ? entry : AddEntry(ptr, allocator);
911 void SetIndexedReference(HeapGraphEdge::Type type,
914 HeapEntry* child_entry) {
915 HeapEntry* parent_entry = &snapshot_->entries()[parent];
916 parent_entry->SetIndexedReference(type, index, child_entry);
918 void SetIndexedAutoIndexReference(HeapGraphEdge::Type type,
920 HeapEntry* child_entry) {
921 HeapEntry* parent_entry = &snapshot_->entries()[parent];
922 int index = parent_entry->children_count() + 1;
923 parent_entry->SetIndexedReference(type, index, child_entry);
925 void SetNamedReference(HeapGraphEdge::Type type,
927 const char* reference_name,
928 HeapEntry* child_entry) {
929 HeapEntry* parent_entry = &snapshot_->entries()[parent];
930 parent_entry->SetNamedReference(type, reference_name, child_entry);
932 void SetNamedAutoIndexReference(HeapGraphEdge::Type type,
934 HeapEntry* child_entry) {
935 HeapEntry* parent_entry = &snapshot_->entries()[parent];
936 int index = parent_entry->children_count() + 1;
937 parent_entry->SetNamedReference(
939 names_->GetName(index),
944 HeapSnapshot* snapshot_;
945 StringsStorage* names_;
946 HeapEntriesMap* entries_;
950 const char* V8HeapExplorer::GetSystemEntryName(HeapObject* object) {
951 switch (object->map()->instance_type()) {
953 switch (Map::cast(object)->instance_type()) {
954 #define MAKE_STRING_MAP_CASE(instance_type, size, name, Name) \
955 case instance_type: return "system / Map (" #Name ")";
956 STRING_TYPE_LIST(MAKE_STRING_MAP_CASE)
957 #undef MAKE_STRING_MAP_CASE
958 default: return "system / Map";
960 case CELL_TYPE: return "system / Cell";
961 case PROPERTY_CELL_TYPE: return "system / PropertyCell";
962 case FOREIGN_TYPE: return "system / Foreign";
963 case ODDBALL_TYPE: return "system / Oddball";
964 #define MAKE_STRUCT_CASE(NAME, Name, name) \
965 case NAME##_TYPE: return "system / "#Name;
966 STRUCT_LIST(MAKE_STRUCT_CASE)
967 #undef MAKE_STRUCT_CASE
968 default: return "system";
973 int V8HeapExplorer::EstimateObjectsCount(HeapIterator* iterator) {
974 int objects_count = 0;
975 for (HeapObject* obj = iterator->next();
977 obj = iterator->next()) {
980 return objects_count;
984 class IndexedReferencesExtractor : public ObjectVisitor {
986 IndexedReferencesExtractor(V8HeapExplorer* generator,
987 HeapObject* parent_obj,
989 : generator_(generator),
990 parent_obj_(parent_obj),
994 void VisitCodeEntry(Address entry_address) {
995 Code* code = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
996 generator_->SetInternalReference(parent_obj_, parent_, "code", code);
997 generator_->TagCodeObject(code);
999 void VisitPointers(Object** start, Object** end) {
1000 for (Object** p = start; p < end; p++) {
1002 if (CheckVisitedAndUnmark(p)) continue;
1003 generator_->SetHiddenReference(parent_obj_, parent_, next_index_, *p);
1006 static void MarkVisitedField(HeapObject* obj, int offset) {
1007 if (offset < 0) return;
1008 Address field = obj->address() + offset;
1009 DCHECK(Memory::Object_at(field)->IsHeapObject());
1010 intptr_t p = reinterpret_cast<intptr_t>(Memory::Object_at(field));
1011 DCHECK(!IsMarked(p));
1012 intptr_t p_tagged = p | kTag;
1013 Memory::Object_at(field) = reinterpret_cast<Object*>(p_tagged);
1017 bool CheckVisitedAndUnmark(Object** field) {
1018 intptr_t p = reinterpret_cast<intptr_t>(*field);
1020 intptr_t p_untagged = (p & ~kTaggingMask) | kHeapObjectTag;
1021 *field = reinterpret_cast<Object*>(p_untagged);
1022 DCHECK((*field)->IsHeapObject());
1028 static const intptr_t kTaggingMask = 3;
1029 static const intptr_t kTag = 3;
1031 static bool IsMarked(intptr_t p) { return (p & kTaggingMask) == kTag; }
1033 V8HeapExplorer* generator_;
1034 HeapObject* parent_obj_;
1040 bool V8HeapExplorer::ExtractReferencesPass1(int entry, HeapObject* obj) {
1041 if (obj->IsFixedArray()) return false; // FixedArrays are processed on pass 2
1043 if (obj->IsJSGlobalProxy()) {
1044 ExtractJSGlobalProxyReferences(entry, JSGlobalProxy::cast(obj));
1045 } else if (obj->IsJSArrayBuffer()) {
1046 ExtractJSArrayBufferReferences(entry, JSArrayBuffer::cast(obj));
1047 } else if (obj->IsJSObject()) {
1048 if (obj->IsJSWeakSet()) {
1049 ExtractJSWeakCollectionReferences(entry, JSWeakSet::cast(obj));
1050 } else if (obj->IsJSWeakMap()) {
1051 ExtractJSWeakCollectionReferences(entry, JSWeakMap::cast(obj));
1052 } else if (obj->IsJSSet()) {
1053 ExtractJSCollectionReferences(entry, JSSet::cast(obj));
1054 } else if (obj->IsJSMap()) {
1055 ExtractJSCollectionReferences(entry, JSMap::cast(obj));
1057 ExtractJSObjectReferences(entry, JSObject::cast(obj));
1058 } else if (obj->IsString()) {
1059 ExtractStringReferences(entry, String::cast(obj));
1060 } else if (obj->IsSymbol()) {
1061 ExtractSymbolReferences(entry, Symbol::cast(obj));
1062 } else if (obj->IsMap()) {
1063 ExtractMapReferences(entry, Map::cast(obj));
1064 } else if (obj->IsSharedFunctionInfo()) {
1065 ExtractSharedFunctionInfoReferences(entry, SharedFunctionInfo::cast(obj));
1066 } else if (obj->IsScript()) {
1067 ExtractScriptReferences(entry, Script::cast(obj));
1068 } else if (obj->IsAccessorInfo()) {
1069 ExtractAccessorInfoReferences(entry, AccessorInfo::cast(obj));
1070 } else if (obj->IsAccessorPair()) {
1071 ExtractAccessorPairReferences(entry, AccessorPair::cast(obj));
1072 } else if (obj->IsCodeCache()) {
1073 ExtractCodeCacheReferences(entry, CodeCache::cast(obj));
1074 } else if (obj->IsCode()) {
1075 ExtractCodeReferences(entry, Code::cast(obj));
1076 } else if (obj->IsBox()) {
1077 ExtractBoxReferences(entry, Box::cast(obj));
1078 } else if (obj->IsCell()) {
1079 ExtractCellReferences(entry, Cell::cast(obj));
1080 } else if (obj->IsPropertyCell()) {
1081 ExtractPropertyCellReferences(entry, PropertyCell::cast(obj));
1082 } else if (obj->IsAllocationSite()) {
1083 ExtractAllocationSiteReferences(entry, AllocationSite::cast(obj));
1089 bool V8HeapExplorer::ExtractReferencesPass2(int entry, HeapObject* obj) {
1090 if (!obj->IsFixedArray()) return false;
1092 if (obj->IsContext()) {
1093 ExtractContextReferences(entry, Context::cast(obj));
1095 ExtractFixedArrayReferences(entry, FixedArray::cast(obj));
1101 void V8HeapExplorer::ExtractJSGlobalProxyReferences(
1102 int entry, JSGlobalProxy* proxy) {
1103 SetInternalReference(proxy, entry,
1104 "native_context", proxy->native_context(),
1105 JSGlobalProxy::kNativeContextOffset);
1109 void V8HeapExplorer::ExtractJSObjectReferences(
1110 int entry, JSObject* js_obj) {
1111 HeapObject* obj = js_obj;
1112 ExtractClosureReferences(js_obj, entry);
1113 ExtractPropertyReferences(js_obj, entry);
1114 ExtractElementReferences(js_obj, entry);
1115 ExtractInternalReferences(js_obj, entry);
1116 PrototypeIterator iter(heap_->isolate(), js_obj);
1117 SetPropertyReference(obj, entry, heap_->proto_string(), iter.GetCurrent());
1118 if (obj->IsJSFunction()) {
1119 JSFunction* js_fun = JSFunction::cast(js_obj);
1120 Object* proto_or_map = js_fun->prototype_or_initial_map();
1121 if (!proto_or_map->IsTheHole()) {
1122 if (!proto_or_map->IsMap()) {
1123 SetPropertyReference(
1125 heap_->prototype_string(), proto_or_map,
1127 JSFunction::kPrototypeOrInitialMapOffset);
1129 SetPropertyReference(
1131 heap_->prototype_string(), js_fun->prototype());
1132 SetInternalReference(
1133 obj, entry, "initial_map", proto_or_map,
1134 JSFunction::kPrototypeOrInitialMapOffset);
1137 SharedFunctionInfo* shared_info = js_fun->shared();
1138 // JSFunction has either bindings or literals and never both.
1139 bool bound = shared_info->bound();
1140 TagObject(js_fun->literals_or_bindings(),
1141 bound ? "(function bindings)" : "(function literals)");
1142 SetInternalReference(js_fun, entry,
1143 bound ? "bindings" : "literals",
1144 js_fun->literals_or_bindings(),
1145 JSFunction::kLiteralsOffset);
1146 TagObject(shared_info, "(shared function info)");
1147 SetInternalReference(js_fun, entry,
1148 "shared", shared_info,
1149 JSFunction::kSharedFunctionInfoOffset);
1150 TagObject(js_fun->context(), "(context)");
1151 SetInternalReference(js_fun, entry,
1152 "context", js_fun->context(),
1153 JSFunction::kContextOffset);
1154 SetWeakReference(js_fun, entry,
1155 "next_function_link", js_fun->next_function_link(),
1156 JSFunction::kNextFunctionLinkOffset);
1157 STATIC_ASSERT(JSFunction::kNextFunctionLinkOffset
1158 == JSFunction::kNonWeakFieldsEndOffset);
1159 STATIC_ASSERT(JSFunction::kNextFunctionLinkOffset + kPointerSize
1160 == JSFunction::kSize);
1161 } else if (obj->IsGlobalObject()) {
1162 GlobalObject* global_obj = GlobalObject::cast(obj);
1163 SetInternalReference(global_obj, entry,
1164 "builtins", global_obj->builtins(),
1165 GlobalObject::kBuiltinsOffset);
1166 SetInternalReference(global_obj, entry,
1167 "native_context", global_obj->native_context(),
1168 GlobalObject::kNativeContextOffset);
1169 SetInternalReference(global_obj, entry,
1170 "global_proxy", global_obj->global_proxy(),
1171 GlobalObject::kGlobalProxyOffset);
1172 STATIC_ASSERT(GlobalObject::kHeaderSize - JSObject::kHeaderSize ==
1174 } else if (obj->IsJSArrayBufferView()) {
1175 JSArrayBufferView* view = JSArrayBufferView::cast(obj);
1176 SetInternalReference(view, entry, "buffer", view->buffer(),
1177 JSArrayBufferView::kBufferOffset);
1178 SetWeakReference(view, entry, "weak_next", view->weak_next(),
1179 JSArrayBufferView::kWeakNextOffset);
1181 TagObject(js_obj->properties(), "(object properties)");
1182 SetInternalReference(obj, entry,
1183 "properties", js_obj->properties(),
1184 JSObject::kPropertiesOffset);
1185 TagObject(js_obj->elements(), "(object elements)");
1186 SetInternalReference(obj, entry,
1187 "elements", js_obj->elements(),
1188 JSObject::kElementsOffset);
1192 void V8HeapExplorer::ExtractStringReferences(int entry, String* string) {
1193 if (string->IsConsString()) {
1194 ConsString* cs = ConsString::cast(string);
1195 SetInternalReference(cs, entry, "first", cs->first(),
1196 ConsString::kFirstOffset);
1197 SetInternalReference(cs, entry, "second", cs->second(),
1198 ConsString::kSecondOffset);
1199 } else if (string->IsSlicedString()) {
1200 SlicedString* ss = SlicedString::cast(string);
1201 SetInternalReference(ss, entry, "parent", ss->parent(),
1202 SlicedString::kParentOffset);
1207 void V8HeapExplorer::ExtractSymbolReferences(int entry, Symbol* symbol) {
1208 SetInternalReference(symbol, entry,
1209 "name", symbol->name(),
1210 Symbol::kNameOffset);
1214 void V8HeapExplorer::ExtractJSCollectionReferences(int entry,
1215 JSCollection* collection) {
1216 SetInternalReference(collection, entry, "table", collection->table(),
1217 JSCollection::kTableOffset);
1221 void V8HeapExplorer::ExtractJSWeakCollectionReferences(
1222 int entry, JSWeakCollection* collection) {
1223 MarkAsWeakContainer(collection->table());
1224 SetInternalReference(collection, entry,
1225 "table", collection->table(),
1226 JSWeakCollection::kTableOffset);
1230 void V8HeapExplorer::ExtractContextReferences(int entry, Context* context) {
1231 if (context == context->declaration_context()) {
1232 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
1233 // Add context allocated locals.
1234 int context_locals = scope_info->ContextLocalCount();
1235 for (int i = 0; i < context_locals; ++i) {
1236 String* local_name = scope_info->ContextLocalName(i);
1237 int idx = Context::MIN_CONTEXT_SLOTS + i;
1238 SetContextReference(context, entry, local_name, context->get(idx),
1239 Context::OffsetOfElementAt(idx));
1241 if (scope_info->HasFunctionName()) {
1242 String* name = scope_info->FunctionName();
1244 int idx = scope_info->FunctionContextSlotIndex(name, &mode);
1246 SetContextReference(context, entry, name, context->get(idx),
1247 Context::OffsetOfElementAt(idx));
1252 #define EXTRACT_CONTEXT_FIELD(index, type, name) \
1253 if (Context::index < Context::FIRST_WEAK_SLOT || \
1254 Context::index == Context::MAP_CACHE_INDEX) { \
1255 SetInternalReference(context, entry, #name, context->get(Context::index), \
1256 FixedArray::OffsetOfElementAt(Context::index)); \
1258 SetWeakReference(context, entry, #name, context->get(Context::index), \
1259 FixedArray::OffsetOfElementAt(Context::index)); \
1261 EXTRACT_CONTEXT_FIELD(CLOSURE_INDEX, JSFunction, closure);
1262 EXTRACT_CONTEXT_FIELD(PREVIOUS_INDEX, Context, previous);
1263 EXTRACT_CONTEXT_FIELD(EXTENSION_INDEX, Object, extension);
1264 EXTRACT_CONTEXT_FIELD(GLOBAL_OBJECT_INDEX, GlobalObject, global);
1265 if (context->IsNativeContext()) {
1266 TagObject(context->jsfunction_result_caches(),
1267 "(context func. result caches)");
1268 TagObject(context->normalized_map_cache(), "(context norm. map cache)");
1269 TagObject(context->runtime_context(), "(runtime context)");
1270 TagObject(context->embedder_data(), "(context data)");
1271 NATIVE_CONTEXT_FIELDS(EXTRACT_CONTEXT_FIELD);
1272 EXTRACT_CONTEXT_FIELD(OPTIMIZED_FUNCTIONS_LIST, unused,
1273 optimized_functions_list);
1274 EXTRACT_CONTEXT_FIELD(OPTIMIZED_CODE_LIST, unused, optimized_code_list);
1275 EXTRACT_CONTEXT_FIELD(DEOPTIMIZED_CODE_LIST, unused, deoptimized_code_list);
1276 EXTRACT_CONTEXT_FIELD(NEXT_CONTEXT_LINK, unused, next_context_link);
1277 #undef EXTRACT_CONTEXT_FIELD
1278 STATIC_ASSERT(Context::OPTIMIZED_FUNCTIONS_LIST ==
1279 Context::FIRST_WEAK_SLOT);
1280 STATIC_ASSERT(Context::NEXT_CONTEXT_LINK + 1 ==
1281 Context::NATIVE_CONTEXT_SLOTS);
1282 STATIC_ASSERT(Context::FIRST_WEAK_SLOT + 4 ==
1283 Context::NATIVE_CONTEXT_SLOTS);
1288 void V8HeapExplorer::ExtractMapReferences(int entry, Map* map) {
1289 if (map->HasTransitionArray()) {
1290 TransitionArray* transitions = map->transitions();
1291 int transitions_entry = GetEntry(transitions)->index();
1292 Object* back_pointer = transitions->back_pointer_storage();
1293 TagObject(back_pointer, "(back pointer)");
1294 SetInternalReference(transitions, transitions_entry,
1295 "back_pointer", back_pointer);
1297 if (FLAG_collect_maps && map->CanTransition()) {
1298 if (!transitions->IsSimpleTransition()) {
1299 if (transitions->HasPrototypeTransitions()) {
1300 FixedArray* prototype_transitions =
1301 transitions->GetPrototypeTransitions();
1302 MarkAsWeakContainer(prototype_transitions);
1303 TagObject(prototype_transitions, "(prototype transitions");
1304 SetInternalReference(transitions, transitions_entry,
1305 "prototype_transitions", prototype_transitions);
1307 // TODO(alph): transitions keys are strong links.
1308 MarkAsWeakContainer(transitions);
1312 TagObject(transitions, "(transition array)");
1313 SetInternalReference(map, entry,
1314 "transitions", transitions,
1315 Map::kTransitionsOrBackPointerOffset);
1317 Object* back_pointer = map->GetBackPointer();
1318 TagObject(back_pointer, "(back pointer)");
1319 SetInternalReference(map, entry,
1320 "back_pointer", back_pointer,
1321 Map::kTransitionsOrBackPointerOffset);
1323 DescriptorArray* descriptors = map->instance_descriptors();
1324 TagObject(descriptors, "(map descriptors)");
1325 SetInternalReference(map, entry,
1326 "descriptors", descriptors,
1327 Map::kDescriptorsOffset);
1329 MarkAsWeakContainer(map->code_cache());
1330 SetInternalReference(map, entry,
1331 "code_cache", map->code_cache(),
1332 Map::kCodeCacheOffset);
1333 SetInternalReference(map, entry,
1334 "prototype", map->prototype(), Map::kPrototypeOffset);
1335 SetInternalReference(map, entry,
1336 "constructor", map->constructor(),
1337 Map::kConstructorOffset);
1338 TagObject(map->dependent_code(), "(dependent code)");
1339 MarkAsWeakContainer(map->dependent_code());
1340 SetInternalReference(map, entry,
1341 "dependent_code", map->dependent_code(),
1342 Map::kDependentCodeOffset);
1346 void V8HeapExplorer::ExtractSharedFunctionInfoReferences(
1347 int entry, SharedFunctionInfo* shared) {
1348 HeapObject* obj = shared;
1349 String* shared_name = shared->DebugName();
1350 const char* name = NULL;
1351 if (shared_name != *heap_->isolate()->factory()->empty_string()) {
1352 name = names_->GetName(shared_name);
1353 TagObject(shared->code(), names_->GetFormatted("(code for %s)", name));
1355 TagObject(shared->code(), names_->GetFormatted("(%s code)",
1356 Code::Kind2String(shared->code()->kind())));
1359 SetInternalReference(obj, entry,
1360 "name", shared->name(),
1361 SharedFunctionInfo::kNameOffset);
1362 SetInternalReference(obj, entry,
1363 "code", shared->code(),
1364 SharedFunctionInfo::kCodeOffset);
1365 TagObject(shared->scope_info(), "(function scope info)");
1366 SetInternalReference(obj, entry,
1367 "scope_info", shared->scope_info(),
1368 SharedFunctionInfo::kScopeInfoOffset);
1369 SetInternalReference(obj, entry,
1370 "instance_class_name", shared->instance_class_name(),
1371 SharedFunctionInfo::kInstanceClassNameOffset);
1372 SetInternalReference(obj, entry,
1373 "script", shared->script(),
1374 SharedFunctionInfo::kScriptOffset);
1375 const char* construct_stub_name = name ?
1376 names_->GetFormatted("(construct stub code for %s)", name) :
1377 "(construct stub code)";
1378 TagObject(shared->construct_stub(), construct_stub_name);
1379 SetInternalReference(obj, entry,
1380 "construct_stub", shared->construct_stub(),
1381 SharedFunctionInfo::kConstructStubOffset);
1382 SetInternalReference(obj, entry,
1383 "function_data", shared->function_data(),
1384 SharedFunctionInfo::kFunctionDataOffset);
1385 SetInternalReference(obj, entry,
1386 "debug_info", shared->debug_info(),
1387 SharedFunctionInfo::kDebugInfoOffset);
1388 SetInternalReference(obj, entry,
1389 "inferred_name", shared->inferred_name(),
1390 SharedFunctionInfo::kInferredNameOffset);
1391 SetInternalReference(obj, entry,
1392 "optimized_code_map", shared->optimized_code_map(),
1393 SharedFunctionInfo::kOptimizedCodeMapOffset);
1394 SetInternalReference(obj, entry,
1395 "feedback_vector", shared->feedback_vector(),
1396 SharedFunctionInfo::kFeedbackVectorOffset);
1400 void V8HeapExplorer::ExtractScriptReferences(int entry, Script* script) {
1401 HeapObject* obj = script;
1402 SetInternalReference(obj, entry,
1403 "source", script->source(),
1404 Script::kSourceOffset);
1405 SetInternalReference(obj, entry,
1406 "name", script->name(),
1407 Script::kNameOffset);
1408 SetInternalReference(obj, entry,
1409 "context_data", script->context_data(),
1410 Script::kContextOffset);
1411 TagObject(script->line_ends(), "(script line ends)");
1412 SetInternalReference(obj, entry,
1413 "line_ends", script->line_ends(),
1414 Script::kLineEndsOffset);
1418 void V8HeapExplorer::ExtractAccessorInfoReferences(
1419 int entry, AccessorInfo* accessor_info) {
1420 SetInternalReference(accessor_info, entry, "name", accessor_info->name(),
1421 AccessorInfo::kNameOffset);
1422 SetInternalReference(accessor_info, entry, "expected_receiver_type",
1423 accessor_info->expected_receiver_type(),
1424 AccessorInfo::kExpectedReceiverTypeOffset);
1425 if (accessor_info->IsExecutableAccessorInfo()) {
1426 ExecutableAccessorInfo* executable_accessor_info =
1427 ExecutableAccessorInfo::cast(accessor_info);
1428 SetInternalReference(executable_accessor_info, entry, "getter",
1429 executable_accessor_info->getter(),
1430 ExecutableAccessorInfo::kGetterOffset);
1431 SetInternalReference(executable_accessor_info, entry, "setter",
1432 executable_accessor_info->setter(),
1433 ExecutableAccessorInfo::kSetterOffset);
1434 SetInternalReference(executable_accessor_info, entry, "data",
1435 executable_accessor_info->data(),
1436 ExecutableAccessorInfo::kDataOffset);
1441 void V8HeapExplorer::ExtractAccessorPairReferences(
1442 int entry, AccessorPair* accessors) {
1443 SetInternalReference(accessors, entry, "getter", accessors->getter(),
1444 AccessorPair::kGetterOffset);
1445 SetInternalReference(accessors, entry, "setter", accessors->setter(),
1446 AccessorPair::kSetterOffset);
1450 void V8HeapExplorer::ExtractCodeCacheReferences(
1451 int entry, CodeCache* code_cache) {
1452 TagObject(code_cache->default_cache(), "(default code cache)");
1453 SetInternalReference(code_cache, entry,
1454 "default_cache", code_cache->default_cache(),
1455 CodeCache::kDefaultCacheOffset);
1456 TagObject(code_cache->normal_type_cache(), "(code type cache)");
1457 SetInternalReference(code_cache, entry,
1458 "type_cache", code_cache->normal_type_cache(),
1459 CodeCache::kNormalTypeCacheOffset);
1463 void V8HeapExplorer::TagBuiltinCodeObject(Code* code, const char* name) {
1464 TagObject(code, names_->GetFormatted("(%s builtin)", name));
1468 void V8HeapExplorer::TagCodeObject(Code* code) {
1469 if (code->kind() == Code::STUB) {
1470 TagObject(code, names_->GetFormatted(
1471 "(%s code)", CodeStub::MajorName(
1472 CodeStub::GetMajorKey(code), true)));
1477 void V8HeapExplorer::ExtractCodeReferences(int entry, Code* code) {
1478 TagCodeObject(code);
1479 TagObject(code->relocation_info(), "(code relocation info)");
1480 SetInternalReference(code, entry,
1481 "relocation_info", code->relocation_info(),
1482 Code::kRelocationInfoOffset);
1483 SetInternalReference(code, entry,
1484 "handler_table", code->handler_table(),
1485 Code::kHandlerTableOffset);
1486 TagObject(code->deoptimization_data(), "(code deopt data)");
1487 SetInternalReference(code, entry,
1488 "deoptimization_data", code->deoptimization_data(),
1489 Code::kDeoptimizationDataOffset);
1490 if (code->kind() == Code::FUNCTION) {
1491 SetInternalReference(code, entry,
1492 "type_feedback_info", code->type_feedback_info(),
1493 Code::kTypeFeedbackInfoOffset);
1495 SetInternalReference(code, entry,
1496 "gc_metadata", code->gc_metadata(),
1497 Code::kGCMetadataOffset);
1498 SetInternalReference(code, entry,
1499 "constant_pool", code->constant_pool(),
1500 Code::kConstantPoolOffset);
1501 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1502 SetWeakReference(code, entry,
1503 "next_code_link", code->next_code_link(),
1504 Code::kNextCodeLinkOffset);
1509 void V8HeapExplorer::ExtractBoxReferences(int entry, Box* box) {
1510 SetInternalReference(box, entry, "value", box->value(), Box::kValueOffset);
1514 void V8HeapExplorer::ExtractCellReferences(int entry, Cell* cell) {
1515 SetInternalReference(cell, entry, "value", cell->value(), Cell::kValueOffset);
1519 void V8HeapExplorer::ExtractPropertyCellReferences(int entry,
1520 PropertyCell* cell) {
1521 ExtractCellReferences(entry, cell);
1522 SetInternalReference(cell, entry, "type", cell->type(),
1523 PropertyCell::kTypeOffset);
1524 MarkAsWeakContainer(cell->dependent_code());
1525 SetInternalReference(cell, entry, "dependent_code", cell->dependent_code(),
1526 PropertyCell::kDependentCodeOffset);
1530 void V8HeapExplorer::ExtractAllocationSiteReferences(int entry,
1531 AllocationSite* site) {
1532 SetInternalReference(site, entry, "transition_info", site->transition_info(),
1533 AllocationSite::kTransitionInfoOffset);
1534 SetInternalReference(site, entry, "nested_site", site->nested_site(),
1535 AllocationSite::kNestedSiteOffset);
1536 MarkAsWeakContainer(site->dependent_code());
1537 SetInternalReference(site, entry, "dependent_code", site->dependent_code(),
1538 AllocationSite::kDependentCodeOffset);
1539 // Do not visit weak_next as it is not visited by the StaticVisitor,
1540 // and we're not very interested in weak_next field here.
1541 STATIC_ASSERT(AllocationSite::kWeakNextOffset >=
1542 AllocationSite::BodyDescriptor::kEndOffset);
1546 class JSArrayBufferDataEntryAllocator : public HeapEntriesAllocator {
1548 JSArrayBufferDataEntryAllocator(size_t size, V8HeapExplorer* explorer)
1550 , explorer_(explorer) {
1552 virtual HeapEntry* AllocateEntry(HeapThing ptr) {
1553 return explorer_->AddEntry(
1554 static_cast<Address>(ptr),
1555 HeapEntry::kNative, "system / JSArrayBufferData", size_);
1559 V8HeapExplorer* explorer_;
1563 void V8HeapExplorer::ExtractJSArrayBufferReferences(
1564 int entry, JSArrayBuffer* buffer) {
1565 SetWeakReference(buffer, entry, "weak_next", buffer->weak_next(),
1566 JSArrayBuffer::kWeakNextOffset);
1567 SetWeakReference(buffer, entry,
1568 "weak_first_view", buffer->weak_first_view(),
1569 JSArrayBuffer::kWeakFirstViewOffset);
1570 // Setup a reference to a native memory backing_store object.
1571 if (!buffer->backing_store())
1573 size_t data_size = NumberToSize(heap_->isolate(), buffer->byte_length());
1574 JSArrayBufferDataEntryAllocator allocator(data_size, this);
1575 HeapEntry* data_entry =
1576 filler_->FindOrAddEntry(buffer->backing_store(), &allocator);
1577 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1578 entry, "backing_store", data_entry);
1582 void V8HeapExplorer::ExtractFixedArrayReferences(int entry, FixedArray* array) {
1583 bool is_weak = weak_containers_.Contains(array);
1584 for (int i = 0, l = array->length(); i < l; ++i) {
1586 SetWeakReference(array, entry,
1587 i, array->get(i), array->OffsetOfElementAt(i));
1589 SetInternalReference(array, entry,
1590 i, array->get(i), array->OffsetOfElementAt(i));
1596 void V8HeapExplorer::ExtractClosureReferences(JSObject* js_obj, int entry) {
1597 if (!js_obj->IsJSFunction()) return;
1599 JSFunction* func = JSFunction::cast(js_obj);
1600 if (func->shared()->bound()) {
1601 FixedArray* bindings = func->function_bindings();
1602 SetNativeBindReference(js_obj, entry, "bound_this",
1603 bindings->get(JSFunction::kBoundThisIndex));
1604 SetNativeBindReference(js_obj, entry, "bound_function",
1605 bindings->get(JSFunction::kBoundFunctionIndex));
1606 for (int i = JSFunction::kBoundArgumentsStartIndex;
1607 i < bindings->length(); i++) {
1608 const char* reference_name = names_->GetFormatted(
1609 "bound_argument_%d",
1610 i - JSFunction::kBoundArgumentsStartIndex);
1611 SetNativeBindReference(js_obj, entry, reference_name,
1618 void V8HeapExplorer::ExtractPropertyReferences(JSObject* js_obj, int entry) {
1619 if (js_obj->HasFastProperties()) {
1620 DescriptorArray* descs = js_obj->map()->instance_descriptors();
1621 int real_size = js_obj->map()->NumberOfOwnDescriptors();
1622 for (int i = 0; i < real_size; i++) {
1623 PropertyDetails details = descs->GetDetails(i);
1624 switch (details.location()) {
1626 Representation r = details.representation();
1627 if (r.IsSmi() || r.IsDouble()) break;
1629 Name* k = descs->GetKey(i);
1630 FieldIndex field_index = FieldIndex::ForDescriptor(js_obj->map(), i);
1631 Object* value = js_obj->RawFastPropertyAt(field_index);
1633 field_index.is_inobject() ? field_index.offset() : -1;
1635 if (k != heap_->hidden_string()) {
1636 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry, k,
1637 value, NULL, field_offset);
1639 TagObject(value, "(hidden properties)");
1640 SetInternalReference(js_obj, entry, "hidden_properties", value,
1646 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1648 descs->GetValue(i));
1653 NameDictionary* dictionary = js_obj->property_dictionary();
1654 int length = dictionary->Capacity();
1655 for (int i = 0; i < length; ++i) {
1656 Object* k = dictionary->KeyAt(i);
1657 if (dictionary->IsKey(k)) {
1658 Object* target = dictionary->ValueAt(i);
1659 // We assume that global objects can only have slow properties.
1660 Object* value = target->IsPropertyCell()
1661 ? PropertyCell::cast(target)->value()
1663 if (k == heap_->hidden_string()) {
1664 TagObject(value, "(hidden properties)");
1665 SetInternalReference(js_obj, entry, "hidden_properties", value);
1668 PropertyDetails details = dictionary->DetailsAt(i);
1669 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1670 Name::cast(k), value);
1677 void V8HeapExplorer::ExtractAccessorPairProperty(JSObject* js_obj, int entry,
1679 Object* callback_obj,
1681 if (!callback_obj->IsAccessorPair()) return;
1682 AccessorPair* accessors = AccessorPair::cast(callback_obj);
1683 SetPropertyReference(js_obj, entry, key, accessors, NULL, field_offset);
1684 Object* getter = accessors->getter();
1685 if (!getter->IsOddball()) {
1686 SetPropertyReference(js_obj, entry, key, getter, "get %s");
1688 Object* setter = accessors->setter();
1689 if (!setter->IsOddball()) {
1690 SetPropertyReference(js_obj, entry, key, setter, "set %s");
1695 void V8HeapExplorer::ExtractElementReferences(JSObject* js_obj, int entry) {
1696 if (js_obj->HasFastObjectElements()) {
1697 FixedArray* elements = FixedArray::cast(js_obj->elements());
1698 int length = js_obj->IsJSArray() ?
1699 Smi::cast(JSArray::cast(js_obj)->length())->value() :
1701 for (int i = 0; i < length; ++i) {
1702 if (!elements->get(i)->IsTheHole()) {
1703 SetElementReference(js_obj, entry, i, elements->get(i));
1706 } else if (js_obj->HasDictionaryElements()) {
1707 SeededNumberDictionary* dictionary = js_obj->element_dictionary();
1708 int length = dictionary->Capacity();
1709 for (int i = 0; i < length; ++i) {
1710 Object* k = dictionary->KeyAt(i);
1711 if (dictionary->IsKey(k)) {
1712 DCHECK(k->IsNumber());
1713 uint32_t index = static_cast<uint32_t>(k->Number());
1714 SetElementReference(js_obj, entry, index, dictionary->ValueAt(i));
1721 void V8HeapExplorer::ExtractInternalReferences(JSObject* js_obj, int entry) {
1722 int length = js_obj->GetInternalFieldCount();
1723 for (int i = 0; i < length; ++i) {
1724 Object* o = js_obj->GetInternalField(i);
1725 SetInternalReference(
1726 js_obj, entry, i, o, js_obj->GetInternalFieldOffset(i));
1731 String* V8HeapExplorer::GetConstructorName(JSObject* object) {
1732 Heap* heap = object->GetHeap();
1733 if (object->IsJSFunction()) return heap->closure_string();
1734 String* constructor_name = object->constructor_name();
1735 if (constructor_name == heap->Object_string()) {
1736 // TODO(verwaest): Try to get object.constructor.name in this case.
1737 // This requires handlification of the V8HeapExplorer.
1739 return object->constructor_name();
1743 HeapEntry* V8HeapExplorer::GetEntry(Object* obj) {
1744 if (!obj->IsHeapObject()) return NULL;
1745 return filler_->FindOrAddEntry(obj, this);
1749 class RootsReferencesExtractor : public ObjectVisitor {
1752 IndexTag(int index, VisitorSynchronization::SyncTag tag)
1753 : index(index), tag(tag) { }
1755 VisitorSynchronization::SyncTag tag;
1759 explicit RootsReferencesExtractor(Heap* heap)
1760 : collecting_all_references_(false),
1761 previous_reference_count_(0),
1765 void VisitPointers(Object** start, Object** end) {
1766 if (collecting_all_references_) {
1767 for (Object** p = start; p < end; p++) all_references_.Add(*p);
1769 for (Object** p = start; p < end; p++) strong_references_.Add(*p);
1773 void SetCollectingAllReferences() { collecting_all_references_ = true; }
1775 void FillReferences(V8HeapExplorer* explorer) {
1776 DCHECK(strong_references_.length() <= all_references_.length());
1777 Builtins* builtins = heap_->isolate()->builtins();
1778 int strong_index = 0, all_index = 0, tags_index = 0, builtin_index = 0;
1779 while (all_index < all_references_.length()) {
1780 bool is_strong = strong_index < strong_references_.length()
1781 && strong_references_[strong_index] == all_references_[all_index];
1782 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1784 all_references_[all_index]);
1785 if (reference_tags_[tags_index].tag ==
1786 VisitorSynchronization::kBuiltins) {
1787 DCHECK(all_references_[all_index]->IsCode());
1788 explorer->TagBuiltinCodeObject(
1789 Code::cast(all_references_[all_index]),
1790 builtins->name(builtin_index++));
1793 if (is_strong) ++strong_index;
1794 if (reference_tags_[tags_index].index == all_index) ++tags_index;
1798 void Synchronize(VisitorSynchronization::SyncTag tag) {
1799 if (collecting_all_references_ &&
1800 previous_reference_count_ != all_references_.length()) {
1801 previous_reference_count_ = all_references_.length();
1802 reference_tags_.Add(IndexTag(previous_reference_count_, tag));
1807 bool collecting_all_references_;
1808 List<Object*> strong_references_;
1809 List<Object*> all_references_;
1810 int previous_reference_count_;
1811 List<IndexTag> reference_tags_;
1816 bool V8HeapExplorer::IterateAndExtractReferences(
1817 SnapshotFiller* filler) {
1820 // Create references to the synthetic roots.
1821 SetRootGcRootsReference();
1822 for (int tag = 0; tag < VisitorSynchronization::kNumberOfSyncTags; tag++) {
1823 SetGcRootsReference(static_cast<VisitorSynchronization::SyncTag>(tag));
1826 // Make sure builtin code objects get their builtin tags
1827 // first. Otherwise a particular JSFunction object could set
1828 // its custom name to a generic builtin.
1829 RootsReferencesExtractor extractor(heap_);
1830 heap_->IterateRoots(&extractor, VISIT_ONLY_STRONG);
1831 extractor.SetCollectingAllReferences();
1832 heap_->IterateRoots(&extractor, VISIT_ALL);
1833 extractor.FillReferences(this);
1835 // We have to do two passes as sometimes FixedArrays are used
1836 // to weakly hold their items, and it's impossible to distinguish
1837 // between these cases without processing the array owner first.
1839 IterateAndExtractSinglePass<&V8HeapExplorer::ExtractReferencesPass1>() ||
1840 IterateAndExtractSinglePass<&V8HeapExplorer::ExtractReferencesPass2>();
1848 return progress_->ProgressReport(true);
1852 template<V8HeapExplorer::ExtractReferencesMethod extractor>
1853 bool V8HeapExplorer::IterateAndExtractSinglePass() {
1854 // Now iterate the whole heap.
1855 bool interrupted = false;
1856 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
1857 // Heap iteration with filtering must be finished in any case.
1858 for (HeapObject* obj = iterator.next();
1860 obj = iterator.next(), progress_->ProgressStep()) {
1861 if (interrupted) continue;
1863 HeapEntry* heap_entry = GetEntry(obj);
1864 int entry = heap_entry->index();
1865 if ((this->*extractor)(entry, obj)) {
1866 SetInternalReference(obj, entry,
1867 "map", obj->map(), HeapObject::kMapOffset);
1868 // Extract unvisited fields as hidden references and restore tags
1869 // of visited fields.
1870 IndexedReferencesExtractor refs_extractor(this, obj, entry);
1871 obj->Iterate(&refs_extractor);
1874 if (!progress_->ProgressReport(false)) interrupted = true;
1880 bool V8HeapExplorer::IsEssentialObject(Object* object) {
1881 return object->IsHeapObject()
1882 && !object->IsOddball()
1883 && object != heap_->empty_byte_array()
1884 && object != heap_->empty_fixed_array()
1885 && object != heap_->empty_descriptor_array()
1886 && object != heap_->fixed_array_map()
1887 && object != heap_->cell_map()
1888 && object != heap_->global_property_cell_map()
1889 && object != heap_->shared_function_info_map()
1890 && object != heap_->free_space_map()
1891 && object != heap_->one_pointer_filler_map()
1892 && object != heap_->two_pointer_filler_map();
1896 void V8HeapExplorer::SetContextReference(HeapObject* parent_obj,
1898 String* reference_name,
1901 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1902 HeapEntry* child_entry = GetEntry(child_obj);
1903 if (child_entry != NULL) {
1904 filler_->SetNamedReference(HeapGraphEdge::kContextVariable,
1906 names_->GetName(reference_name),
1908 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1913 void V8HeapExplorer::SetNativeBindReference(HeapObject* parent_obj,
1915 const char* reference_name,
1916 Object* child_obj) {
1917 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1918 HeapEntry* child_entry = GetEntry(child_obj);
1919 if (child_entry != NULL) {
1920 filler_->SetNamedReference(HeapGraphEdge::kShortcut,
1928 void V8HeapExplorer::SetElementReference(HeapObject* parent_obj,
1931 Object* child_obj) {
1932 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1933 HeapEntry* child_entry = GetEntry(child_obj);
1934 if (child_entry != NULL) {
1935 filler_->SetIndexedReference(HeapGraphEdge::kElement,
1943 void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1945 const char* reference_name,
1948 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1949 HeapEntry* child_entry = GetEntry(child_obj);
1950 if (child_entry == NULL) return;
1951 if (IsEssentialObject(child_obj)) {
1952 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1957 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1961 void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1966 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1967 HeapEntry* child_entry = GetEntry(child_obj);
1968 if (child_entry == NULL) return;
1969 if (IsEssentialObject(child_obj)) {
1970 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1972 names_->GetName(index),
1975 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1979 void V8HeapExplorer::SetHiddenReference(HeapObject* parent_obj,
1982 Object* child_obj) {
1983 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1984 HeapEntry* child_entry = GetEntry(child_obj);
1985 if (child_entry != NULL && IsEssentialObject(child_obj)) {
1986 filler_->SetIndexedReference(HeapGraphEdge::kHidden,
1994 void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
1996 const char* reference_name,
1999 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2000 HeapEntry* child_entry = GetEntry(child_obj);
2001 if (child_entry == NULL) return;
2002 if (IsEssentialObject(child_obj)) {
2003 filler_->SetNamedReference(HeapGraphEdge::kWeak,
2008 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
2012 void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
2017 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2018 HeapEntry* child_entry = GetEntry(child_obj);
2019 if (child_entry == NULL) return;
2020 if (IsEssentialObject(child_obj)) {
2021 filler_->SetNamedReference(HeapGraphEdge::kWeak,
2023 names_->GetFormatted("%d", index),
2026 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
2030 void V8HeapExplorer::SetDataOrAccessorPropertyReference(
2031 PropertyKind kind, JSObject* parent_obj, int parent_entry,
2032 Name* reference_name, Object* child_obj, const char* name_format_string,
2034 if (kind == kAccessor) {
2035 ExtractAccessorPairProperty(parent_obj, parent_entry, reference_name,
2036 child_obj, field_offset);
2038 SetPropertyReference(parent_obj, parent_entry, reference_name, child_obj,
2039 name_format_string, field_offset);
2044 void V8HeapExplorer::SetPropertyReference(HeapObject* parent_obj,
2046 Name* reference_name,
2048 const char* name_format_string,
2050 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2051 HeapEntry* child_entry = GetEntry(child_obj);
2052 if (child_entry != NULL) {
2053 HeapGraphEdge::Type type =
2054 reference_name->IsSymbol() || String::cast(reference_name)->length() > 0
2055 ? HeapGraphEdge::kProperty : HeapGraphEdge::kInternal;
2056 const char* name = name_format_string != NULL && reference_name->IsString()
2057 ? names_->GetFormatted(
2059 String::cast(reference_name)->ToCString(
2060 DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL).get()) :
2061 names_->GetName(reference_name);
2063 filler_->SetNamedReference(type,
2067 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
2072 void V8HeapExplorer::SetRootGcRootsReference() {
2073 filler_->SetIndexedAutoIndexReference(
2074 HeapGraphEdge::kElement,
2075 snapshot_->root()->index(),
2076 snapshot_->gc_roots());
2080 void V8HeapExplorer::SetUserGlobalReference(Object* child_obj) {
2081 HeapEntry* child_entry = GetEntry(child_obj);
2082 DCHECK(child_entry != NULL);
2083 filler_->SetNamedAutoIndexReference(
2084 HeapGraphEdge::kShortcut,
2085 snapshot_->root()->index(),
2090 void V8HeapExplorer::SetGcRootsReference(VisitorSynchronization::SyncTag tag) {
2091 filler_->SetIndexedAutoIndexReference(
2092 HeapGraphEdge::kElement,
2093 snapshot_->gc_roots()->index(),
2094 snapshot_->gc_subroot(tag));
2098 void V8HeapExplorer::SetGcSubrootReference(
2099 VisitorSynchronization::SyncTag tag, bool is_weak, Object* child_obj) {
2100 HeapEntry* child_entry = GetEntry(child_obj);
2101 if (child_entry != NULL) {
2102 const char* name = GetStrongGcSubrootName(child_obj);
2104 filler_->SetNamedReference(
2105 HeapGraphEdge::kInternal,
2106 snapshot_->gc_subroot(tag)->index(),
2111 filler_->SetNamedAutoIndexReference(
2112 HeapGraphEdge::kWeak,
2113 snapshot_->gc_subroot(tag)->index(),
2116 filler_->SetIndexedAutoIndexReference(
2117 HeapGraphEdge::kElement,
2118 snapshot_->gc_subroot(tag)->index(),
2123 // Add a shortcut to JS global object reference at snapshot root.
2124 if (child_obj->IsNativeContext()) {
2125 Context* context = Context::cast(child_obj);
2126 GlobalObject* global = context->global_object();
2127 if (global->IsJSGlobalObject()) {
2128 bool is_debug_object = false;
2129 is_debug_object = heap_->isolate()->debug()->IsDebugGlobal(global);
2130 if (!is_debug_object && !user_roots_.Contains(global)) {
2131 user_roots_.Insert(global);
2132 SetUserGlobalReference(global);
2140 const char* V8HeapExplorer::GetStrongGcSubrootName(Object* object) {
2141 if (strong_gc_subroot_names_.is_empty()) {
2142 #define NAME_ENTRY(name) strong_gc_subroot_names_.SetTag(heap_->name(), #name);
2143 #define ROOT_NAME(type, name, camel_name) NAME_ENTRY(name)
2144 STRONG_ROOT_LIST(ROOT_NAME)
2146 #define STRUCT_MAP_NAME(NAME, Name, name) NAME_ENTRY(name##_map)
2147 STRUCT_LIST(STRUCT_MAP_NAME)
2148 #undef STRUCT_MAP_NAME
2149 #define STRING_NAME(name, str) NAME_ENTRY(name)
2150 INTERNALIZED_STRING_LIST(STRING_NAME)
2152 #define SYMBOL_NAME(name) NAME_ENTRY(name)
2153 PRIVATE_SYMBOL_LIST(SYMBOL_NAME)
2155 #define SYMBOL_NAME(name, varname, description) NAME_ENTRY(name)
2156 PUBLIC_SYMBOL_LIST(SYMBOL_NAME)
2159 CHECK(!strong_gc_subroot_names_.is_empty());
2161 return strong_gc_subroot_names_.GetTag(object);
2165 void V8HeapExplorer::TagObject(Object* obj, const char* tag) {
2166 if (IsEssentialObject(obj)) {
2167 HeapEntry* entry = GetEntry(obj);
2168 if (entry->name()[0] == '\0') {
2169 entry->set_name(tag);
2175 void V8HeapExplorer::MarkAsWeakContainer(Object* object) {
2176 if (IsEssentialObject(object) && object->IsFixedArray()) {
2177 weak_containers_.Insert(object);
2182 class GlobalObjectsEnumerator : public ObjectVisitor {
2184 virtual void VisitPointers(Object** start, Object** end) {
2185 for (Object** p = start; p < end; p++) {
2186 if ((*p)->IsNativeContext()) {
2187 Context* context = Context::cast(*p);
2188 JSObject* proxy = context->global_proxy();
2189 if (proxy->IsJSGlobalProxy()) {
2190 Object* global = proxy->map()->prototype();
2191 if (global->IsJSGlobalObject()) {
2192 objects_.Add(Handle<JSGlobalObject>(JSGlobalObject::cast(global)));
2198 int count() { return objects_.length(); }
2199 Handle<JSGlobalObject>& at(int i) { return objects_[i]; }
2202 List<Handle<JSGlobalObject> > objects_;
2206 // Modifies heap. Must not be run during heap traversal.
2207 void V8HeapExplorer::TagGlobalObjects() {
2208 Isolate* isolate = heap_->isolate();
2209 HandleScope scope(isolate);
2210 GlobalObjectsEnumerator enumerator;
2211 isolate->global_handles()->IterateAllRoots(&enumerator);
2212 const char** urls = NewArray<const char*>(enumerator.count());
2213 for (int i = 0, l = enumerator.count(); i < l; ++i) {
2214 if (global_object_name_resolver_) {
2215 HandleScope scope(isolate);
2216 Handle<JSGlobalObject> global_obj = enumerator.at(i);
2217 urls[i] = global_object_name_resolver_->GetName(
2218 Utils::ToLocal(Handle<JSObject>::cast(global_obj)));
2224 DisallowHeapAllocation no_allocation;
2225 for (int i = 0, l = enumerator.count(); i < l; ++i) {
2226 objects_tags_.SetTag(*enumerator.at(i), urls[i]);
2233 class GlobalHandlesExtractor : public ObjectVisitor {
2235 explicit GlobalHandlesExtractor(NativeObjectsExplorer* explorer)
2236 : explorer_(explorer) {}
2237 virtual ~GlobalHandlesExtractor() {}
2238 virtual void VisitPointers(Object** start, Object** end) {
2241 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {
2242 explorer_->VisitSubtreeWrapper(p, class_id);
2245 NativeObjectsExplorer* explorer_;
2249 class BasicHeapEntriesAllocator : public HeapEntriesAllocator {
2251 BasicHeapEntriesAllocator(
2252 HeapSnapshot* snapshot,
2253 HeapEntry::Type entries_type)
2254 : snapshot_(snapshot),
2255 names_(snapshot_->profiler()->names()),
2256 heap_object_map_(snapshot_->profiler()->heap_object_map()),
2257 entries_type_(entries_type) {
2259 virtual HeapEntry* AllocateEntry(HeapThing ptr);
2261 HeapSnapshot* snapshot_;
2262 StringsStorage* names_;
2263 HeapObjectsMap* heap_object_map_;
2264 HeapEntry::Type entries_type_;
2268 HeapEntry* BasicHeapEntriesAllocator::AllocateEntry(HeapThing ptr) {
2269 v8::RetainedObjectInfo* info = reinterpret_cast<v8::RetainedObjectInfo*>(ptr);
2270 intptr_t elements = info->GetElementCount();
2271 intptr_t size = info->GetSizeInBytes();
2272 const char* name = elements != -1
2273 ? names_->GetFormatted(
2274 "%s / %" V8_PTR_PREFIX "d entries", info->GetLabel(), elements)
2275 : names_->GetCopy(info->GetLabel());
2276 return snapshot_->AddEntry(
2279 heap_object_map_->GenerateId(info),
2280 size != -1 ? static_cast<int>(size) : 0,
2285 NativeObjectsExplorer::NativeObjectsExplorer(
2286 HeapSnapshot* snapshot,
2287 SnapshottingProgressReportingInterface* progress)
2288 : isolate_(snapshot->profiler()->heap_object_map()->heap()->isolate()),
2289 snapshot_(snapshot),
2290 names_(snapshot_->profiler()->names()),
2291 embedder_queried_(false),
2292 objects_by_info_(RetainedInfosMatch),
2293 native_groups_(StringsMatch),
2295 synthetic_entries_allocator_ =
2296 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kSynthetic);
2297 native_entries_allocator_ =
2298 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kNative);
2302 NativeObjectsExplorer::~NativeObjectsExplorer() {
2303 for (HashMap::Entry* p = objects_by_info_.Start();
2305 p = objects_by_info_.Next(p)) {
2306 v8::RetainedObjectInfo* info =
2307 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2309 List<HeapObject*>* objects =
2310 reinterpret_cast<List<HeapObject*>* >(p->value);
2313 for (HashMap::Entry* p = native_groups_.Start();
2315 p = native_groups_.Next(p)) {
2316 v8::RetainedObjectInfo* info =
2317 reinterpret_cast<v8::RetainedObjectInfo*>(p->value);
2320 delete synthetic_entries_allocator_;
2321 delete native_entries_allocator_;
2325 int NativeObjectsExplorer::EstimateObjectsCount() {
2326 FillRetainedObjects();
2327 return objects_by_info_.occupancy();
2331 void NativeObjectsExplorer::FillRetainedObjects() {
2332 if (embedder_queried_) return;
2333 Isolate* isolate = isolate_;
2334 const GCType major_gc_type = kGCTypeMarkSweepCompact;
2335 // Record objects that are joined into ObjectGroups.
2336 isolate->heap()->CallGCPrologueCallbacks(
2337 major_gc_type, kGCCallbackFlagConstructRetainedObjectInfos);
2338 List<ObjectGroup*>* groups = isolate->global_handles()->object_groups();
2339 for (int i = 0; i < groups->length(); ++i) {
2340 ObjectGroup* group = groups->at(i);
2341 if (group->info == NULL) continue;
2342 List<HeapObject*>* list = GetListMaybeDisposeInfo(group->info);
2343 for (size_t j = 0; j < group->length; ++j) {
2344 HeapObject* obj = HeapObject::cast(*group->objects[j]);
2346 in_groups_.Insert(obj);
2348 group->info = NULL; // Acquire info object ownership.
2350 isolate->global_handles()->RemoveObjectGroups();
2351 isolate->heap()->CallGCEpilogueCallbacks(major_gc_type, kNoGCCallbackFlags);
2352 // Record objects that are not in ObjectGroups, but have class ID.
2353 GlobalHandlesExtractor extractor(this);
2354 isolate->global_handles()->IterateAllRootsWithClassIds(&extractor);
2355 embedder_queried_ = true;
2359 void NativeObjectsExplorer::FillImplicitReferences() {
2360 Isolate* isolate = isolate_;
2361 List<ImplicitRefGroup*>* groups =
2362 isolate->global_handles()->implicit_ref_groups();
2363 for (int i = 0; i < groups->length(); ++i) {
2364 ImplicitRefGroup* group = groups->at(i);
2365 HeapObject* parent = *group->parent;
2367 filler_->FindOrAddEntry(parent, native_entries_allocator_)->index();
2368 DCHECK(parent_entry != HeapEntry::kNoEntry);
2369 Object*** children = group->children;
2370 for (size_t j = 0; j < group->length; ++j) {
2371 Object* child = *children[j];
2372 HeapEntry* child_entry =
2373 filler_->FindOrAddEntry(child, native_entries_allocator_);
2374 filler_->SetNamedReference(
2375 HeapGraphEdge::kInternal,
2381 isolate->global_handles()->RemoveImplicitRefGroups();
2384 List<HeapObject*>* NativeObjectsExplorer::GetListMaybeDisposeInfo(
2385 v8::RetainedObjectInfo* info) {
2386 HashMap::Entry* entry =
2387 objects_by_info_.Lookup(info, InfoHash(info), true);
2388 if (entry->value != NULL) {
2391 entry->value = new List<HeapObject*>(4);
2393 return reinterpret_cast<List<HeapObject*>* >(entry->value);
2397 bool NativeObjectsExplorer::IterateAndExtractReferences(
2398 SnapshotFiller* filler) {
2400 FillRetainedObjects();
2401 FillImplicitReferences();
2402 if (EstimateObjectsCount() > 0) {
2403 for (HashMap::Entry* p = objects_by_info_.Start();
2405 p = objects_by_info_.Next(p)) {
2406 v8::RetainedObjectInfo* info =
2407 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2408 SetNativeRootReference(info);
2409 List<HeapObject*>* objects =
2410 reinterpret_cast<List<HeapObject*>* >(p->value);
2411 for (int i = 0; i < objects->length(); ++i) {
2412 SetWrapperNativeReferences(objects->at(i), info);
2415 SetRootNativeRootsReference();
2422 class NativeGroupRetainedObjectInfo : public v8::RetainedObjectInfo {
2424 explicit NativeGroupRetainedObjectInfo(const char* label)
2426 hash_(reinterpret_cast<intptr_t>(label)),
2430 virtual ~NativeGroupRetainedObjectInfo() {}
2431 virtual void Dispose() {
2436 virtual bool IsEquivalent(RetainedObjectInfo* other) {
2437 return hash_ == other->GetHash() && !strcmp(label_, other->GetLabel());
2439 virtual intptr_t GetHash() { return hash_; }
2440 virtual const char* GetLabel() { return label_; }
2449 NativeGroupRetainedObjectInfo* NativeObjectsExplorer::FindOrAddGroupInfo(
2450 const char* label) {
2451 const char* label_copy = names_->GetCopy(label);
2452 uint32_t hash = StringHasher::HashSequentialString(
2454 static_cast<int>(strlen(label_copy)),
2455 isolate_->heap()->HashSeed());
2456 HashMap::Entry* entry = native_groups_.Lookup(const_cast<char*>(label_copy),
2458 if (entry->value == NULL) {
2459 entry->value = new NativeGroupRetainedObjectInfo(label);
2461 return static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2465 void NativeObjectsExplorer::SetNativeRootReference(
2466 v8::RetainedObjectInfo* info) {
2467 HeapEntry* child_entry =
2468 filler_->FindOrAddEntry(info, native_entries_allocator_);
2469 DCHECK(child_entry != NULL);
2470 NativeGroupRetainedObjectInfo* group_info =
2471 FindOrAddGroupInfo(info->GetGroupLabel());
2472 HeapEntry* group_entry =
2473 filler_->FindOrAddEntry(group_info, synthetic_entries_allocator_);
2474 filler_->SetNamedAutoIndexReference(
2475 HeapGraphEdge::kInternal,
2476 group_entry->index(),
2481 void NativeObjectsExplorer::SetWrapperNativeReferences(
2482 HeapObject* wrapper, v8::RetainedObjectInfo* info) {
2483 HeapEntry* wrapper_entry = filler_->FindEntry(wrapper);
2484 DCHECK(wrapper_entry != NULL);
2485 HeapEntry* info_entry =
2486 filler_->FindOrAddEntry(info, native_entries_allocator_);
2487 DCHECK(info_entry != NULL);
2488 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2489 wrapper_entry->index(),
2492 filler_->SetIndexedAutoIndexReference(HeapGraphEdge::kElement,
2493 info_entry->index(),
2498 void NativeObjectsExplorer::SetRootNativeRootsReference() {
2499 for (HashMap::Entry* entry = native_groups_.Start();
2501 entry = native_groups_.Next(entry)) {
2502 NativeGroupRetainedObjectInfo* group_info =
2503 static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2504 HeapEntry* group_entry =
2505 filler_->FindOrAddEntry(group_info, native_entries_allocator_);
2506 DCHECK(group_entry != NULL);
2507 filler_->SetIndexedAutoIndexReference(
2508 HeapGraphEdge::kElement,
2509 snapshot_->root()->index(),
2515 void NativeObjectsExplorer::VisitSubtreeWrapper(Object** p, uint16_t class_id) {
2516 if (in_groups_.Contains(*p)) return;
2517 Isolate* isolate = isolate_;
2518 v8::RetainedObjectInfo* info =
2519 isolate->heap_profiler()->ExecuteWrapperClassCallback(class_id, p);
2520 if (info == NULL) return;
2521 GetListMaybeDisposeInfo(info)->Add(HeapObject::cast(*p));
2525 HeapSnapshotGenerator::HeapSnapshotGenerator(
2526 HeapSnapshot* snapshot,
2527 v8::ActivityControl* control,
2528 v8::HeapProfiler::ObjectNameResolver* resolver,
2530 : snapshot_(snapshot),
2532 v8_heap_explorer_(snapshot_, this, resolver),
2533 dom_explorer_(snapshot_, this),
2538 bool HeapSnapshotGenerator::GenerateSnapshot() {
2539 v8_heap_explorer_.TagGlobalObjects();
2541 // TODO(1562) Profiler assumes that any object that is in the heap after
2542 // full GC is reachable from the root when computing dominators.
2543 // This is not true for weakly reachable objects.
2544 // As a temporary solution we call GC twice.
2545 heap_->CollectAllGarbage(
2546 Heap::kMakeHeapIterableMask,
2547 "HeapSnapshotGenerator::GenerateSnapshot");
2548 heap_->CollectAllGarbage(
2549 Heap::kMakeHeapIterableMask,
2550 "HeapSnapshotGenerator::GenerateSnapshot");
2553 Heap* debug_heap = heap_;
2554 if (FLAG_verify_heap) {
2555 debug_heap->Verify();
2559 SetProgressTotal(2); // 2 passes.
2562 if (FLAG_verify_heap) {
2563 debug_heap->Verify();
2567 snapshot_->AddSyntheticRootEntries();
2569 if (!FillReferences()) return false;
2571 snapshot_->FillChildren();
2572 snapshot_->RememberLastJSObjectId();
2574 progress_counter_ = progress_total_;
2575 if (!ProgressReport(true)) return false;
2580 void HeapSnapshotGenerator::ProgressStep() {
2581 ++progress_counter_;
2585 bool HeapSnapshotGenerator::ProgressReport(bool force) {
2586 const int kProgressReportGranularity = 10000;
2587 if (control_ != NULL
2588 && (force || progress_counter_ % kProgressReportGranularity == 0)) {
2590 control_->ReportProgressValue(progress_counter_, progress_total_) ==
2591 v8::ActivityControl::kContinue;
2597 void HeapSnapshotGenerator::SetProgressTotal(int iterations_count) {
2598 if (control_ == NULL) return;
2599 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
2600 progress_total_ = iterations_count * (
2601 v8_heap_explorer_.EstimateObjectsCount(&iterator) +
2602 dom_explorer_.EstimateObjectsCount());
2603 progress_counter_ = 0;
2607 bool HeapSnapshotGenerator::FillReferences() {
2608 SnapshotFiller filler(snapshot_, &entries_);
2609 return v8_heap_explorer_.IterateAndExtractReferences(&filler)
2610 && dom_explorer_.IterateAndExtractReferences(&filler);
2614 template<int bytes> struct MaxDecimalDigitsIn;
2615 template<> struct MaxDecimalDigitsIn<4> {
2616 static const int kSigned = 11;
2617 static const int kUnsigned = 10;
2619 template<> struct MaxDecimalDigitsIn<8> {
2620 static const int kSigned = 20;
2621 static const int kUnsigned = 20;
2625 class OutputStreamWriter {
2627 explicit OutputStreamWriter(v8::OutputStream* stream)
2629 chunk_size_(stream->GetChunkSize()),
2630 chunk_(chunk_size_),
2633 DCHECK(chunk_size_ > 0);
2635 bool aborted() { return aborted_; }
2636 void AddCharacter(char c) {
2638 DCHECK(chunk_pos_ < chunk_size_);
2639 chunk_[chunk_pos_++] = c;
2642 void AddString(const char* s) {
2643 AddSubstring(s, StrLength(s));
2645 void AddSubstring(const char* s, int n) {
2647 DCHECK(static_cast<size_t>(n) <= strlen(s));
2648 const char* s_end = s + n;
2651 Min(chunk_size_ - chunk_pos_, static_cast<int>(s_end - s));
2652 DCHECK(s_chunk_size > 0);
2653 MemCopy(chunk_.start() + chunk_pos_, s, s_chunk_size);
2655 chunk_pos_ += s_chunk_size;
2659 void AddNumber(unsigned n) { AddNumberImpl<unsigned>(n, "%u"); }
2661 if (aborted_) return;
2662 DCHECK(chunk_pos_ < chunk_size_);
2663 if (chunk_pos_ != 0) {
2666 stream_->EndOfStream();
2670 template<typename T>
2671 void AddNumberImpl(T n, const char* format) {
2672 // Buffer for the longest value plus trailing \0
2673 static const int kMaxNumberSize =
2674 MaxDecimalDigitsIn<sizeof(T)>::kUnsigned + 1;
2675 if (chunk_size_ - chunk_pos_ >= kMaxNumberSize) {
2676 int result = SNPrintF(
2677 chunk_.SubVector(chunk_pos_, chunk_size_), format, n);
2678 DCHECK(result != -1);
2679 chunk_pos_ += result;
2682 EmbeddedVector<char, kMaxNumberSize> buffer;
2683 int result = SNPrintF(buffer, format, n);
2685 DCHECK(result != -1);
2686 AddString(buffer.start());
2689 void MaybeWriteChunk() {
2690 DCHECK(chunk_pos_ <= chunk_size_);
2691 if (chunk_pos_ == chunk_size_) {
2696 if (aborted_) return;
2697 if (stream_->WriteAsciiChunk(chunk_.start(), chunk_pos_) ==
2698 v8::OutputStream::kAbort) aborted_ = true;
2702 v8::OutputStream* stream_;
2704 ScopedVector<char> chunk_;
2710 // type, name|index, to_node.
2711 const int HeapSnapshotJSONSerializer::kEdgeFieldsCount = 3;
2712 // type, name, id, self_size, edge_count, trace_node_id.
2713 const int HeapSnapshotJSONSerializer::kNodeFieldsCount = 6;
2715 void HeapSnapshotJSONSerializer::Serialize(v8::OutputStream* stream) {
2716 if (AllocationTracker* allocation_tracker =
2717 snapshot_->profiler()->allocation_tracker()) {
2718 allocation_tracker->PrepareForSerialization();
2720 DCHECK(writer_ == NULL);
2721 writer_ = new OutputStreamWriter(stream);
2728 void HeapSnapshotJSONSerializer::SerializeImpl() {
2729 DCHECK(0 == snapshot_->root()->index());
2730 writer_->AddCharacter('{');
2731 writer_->AddString("\"snapshot\":{");
2732 SerializeSnapshot();
2733 if (writer_->aborted()) return;
2734 writer_->AddString("},\n");
2735 writer_->AddString("\"nodes\":[");
2737 if (writer_->aborted()) return;
2738 writer_->AddString("],\n");
2739 writer_->AddString("\"edges\":[");
2741 if (writer_->aborted()) return;
2742 writer_->AddString("],\n");
2744 writer_->AddString("\"trace_function_infos\":[");
2745 SerializeTraceNodeInfos();
2746 if (writer_->aborted()) return;
2747 writer_->AddString("],\n");
2748 writer_->AddString("\"trace_tree\":[");
2749 SerializeTraceTree();
2750 if (writer_->aborted()) return;
2751 writer_->AddString("],\n");
2753 writer_->AddString("\"strings\":[");
2755 if (writer_->aborted()) return;
2756 writer_->AddCharacter(']');
2757 writer_->AddCharacter('}');
2758 writer_->Finalize();
2762 int HeapSnapshotJSONSerializer::GetStringId(const char* s) {
2763 HashMap::Entry* cache_entry = strings_.Lookup(
2764 const_cast<char*>(s), StringHash(s), true);
2765 if (cache_entry->value == NULL) {
2766 cache_entry->value = reinterpret_cast<void*>(next_string_id_++);
2768 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2774 template<size_t size> struct ToUnsigned;
2776 template<> struct ToUnsigned<4> {
2777 typedef uint32_t Type;
2780 template<> struct ToUnsigned<8> {
2781 typedef uint64_t Type;
2787 template<typename T>
2788 static int utoa_impl(T value, const Vector<char>& buffer, int buffer_pos) {
2789 STATIC_ASSERT(static_cast<T>(-1) > 0); // Check that T is unsigned
2790 int number_of_digits = 0;
2796 buffer_pos += number_of_digits;
2797 int result = buffer_pos;
2799 int last_digit = static_cast<int>(value % 10);
2800 buffer[--buffer_pos] = '0' + last_digit;
2807 template<typename T>
2808 static int utoa(T value, const Vector<char>& buffer, int buffer_pos) {
2809 typename ToUnsigned<sizeof(value)>::Type unsigned_value = value;
2810 STATIC_ASSERT(sizeof(value) == sizeof(unsigned_value));
2811 return utoa_impl(unsigned_value, buffer, buffer_pos);
2815 void HeapSnapshotJSONSerializer::SerializeEdge(HeapGraphEdge* edge,
2817 // The buffer needs space for 3 unsigned ints, 3 commas, \n and \0
2818 static const int kBufferSize =
2819 MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned * 3 + 3 + 2; // NOLINT
2820 EmbeddedVector<char, kBufferSize> buffer;
2821 int edge_name_or_index = edge->type() == HeapGraphEdge::kElement
2822 || edge->type() == HeapGraphEdge::kHidden
2823 ? edge->index() : GetStringId(edge->name());
2826 buffer[buffer_pos++] = ',';
2828 buffer_pos = utoa(edge->type(), buffer, buffer_pos);
2829 buffer[buffer_pos++] = ',';
2830 buffer_pos = utoa(edge_name_or_index, buffer, buffer_pos);
2831 buffer[buffer_pos++] = ',';
2832 buffer_pos = utoa(entry_index(edge->to()), buffer, buffer_pos);
2833 buffer[buffer_pos++] = '\n';
2834 buffer[buffer_pos++] = '\0';
2835 writer_->AddString(buffer.start());
2839 void HeapSnapshotJSONSerializer::SerializeEdges() {
2840 List<HeapGraphEdge*>& edges = snapshot_->children();
2841 for (int i = 0; i < edges.length(); ++i) {
2843 edges[i - 1]->from()->index() <= edges[i]->from()->index());
2844 SerializeEdge(edges[i], i == 0);
2845 if (writer_->aborted()) return;
2850 void HeapSnapshotJSONSerializer::SerializeNode(HeapEntry* entry) {
2851 // The buffer needs space for 4 unsigned ints, 1 size_t, 5 commas, \n and \0
2852 static const int kBufferSize =
2853 5 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2854 + MaxDecimalDigitsIn<sizeof(size_t)>::kUnsigned // NOLINT
2856 EmbeddedVector<char, kBufferSize> buffer;
2858 if (entry_index(entry) != 0) {
2859 buffer[buffer_pos++] = ',';
2861 buffer_pos = utoa(entry->type(), buffer, buffer_pos);
2862 buffer[buffer_pos++] = ',';
2863 buffer_pos = utoa(GetStringId(entry->name()), buffer, buffer_pos);
2864 buffer[buffer_pos++] = ',';
2865 buffer_pos = utoa(entry->id(), buffer, buffer_pos);
2866 buffer[buffer_pos++] = ',';
2867 buffer_pos = utoa(entry->self_size(), buffer, buffer_pos);
2868 buffer[buffer_pos++] = ',';
2869 buffer_pos = utoa(entry->children_count(), buffer, buffer_pos);
2870 buffer[buffer_pos++] = ',';
2871 buffer_pos = utoa(entry->trace_node_id(), buffer, buffer_pos);
2872 buffer[buffer_pos++] = '\n';
2873 buffer[buffer_pos++] = '\0';
2874 writer_->AddString(buffer.start());
2878 void HeapSnapshotJSONSerializer::SerializeNodes() {
2879 List<HeapEntry>& entries = snapshot_->entries();
2880 for (int i = 0; i < entries.length(); ++i) {
2881 SerializeNode(&entries[i]);
2882 if (writer_->aborted()) return;
2887 void HeapSnapshotJSONSerializer::SerializeSnapshot() {
2888 writer_->AddString("\"title\":\"");
2889 writer_->AddString(snapshot_->title());
2890 writer_->AddString("\"");
2891 writer_->AddString(",\"uid\":");
2892 writer_->AddNumber(snapshot_->uid());
2893 writer_->AddString(",\"meta\":");
2894 // The object describing node serialization layout.
2895 // We use a set of macros to improve readability.
2896 #define JSON_A(s) "[" s "]"
2897 #define JSON_O(s) "{" s "}"
2898 #define JSON_S(s) "\"" s "\""
2899 writer_->AddString(JSON_O(
2900 JSON_S("node_fields") ":" JSON_A(
2904 JSON_S("self_size") ","
2905 JSON_S("edge_count") ","
2906 JSON_S("trace_node_id")) ","
2907 JSON_S("node_types") ":" JSON_A(
2909 JSON_S("hidden") ","
2911 JSON_S("string") ","
2912 JSON_S("object") ","
2914 JSON_S("closure") ","
2915 JSON_S("regexp") ","
2916 JSON_S("number") ","
2917 JSON_S("native") ","
2918 JSON_S("synthetic") ","
2919 JSON_S("concatenated string") ","
2920 JSON_S("sliced string")) ","
2921 JSON_S("string") ","
2922 JSON_S("number") ","
2923 JSON_S("number") ","
2924 JSON_S("number") ","
2925 JSON_S("number") ","
2926 JSON_S("number")) ","
2927 JSON_S("edge_fields") ":" JSON_A(
2929 JSON_S("name_or_index") ","
2930 JSON_S("to_node")) ","
2931 JSON_S("edge_types") ":" JSON_A(
2933 JSON_S("context") ","
2934 JSON_S("element") ","
2935 JSON_S("property") ","
2936 JSON_S("internal") ","
2937 JSON_S("hidden") ","
2938 JSON_S("shortcut") ","
2940 JSON_S("string_or_number") ","
2942 JSON_S("trace_function_info_fields") ":" JSON_A(
2943 JSON_S("function_id") ","
2945 JSON_S("script_name") ","
2946 JSON_S("script_id") ","
2948 JSON_S("column")) ","
2949 JSON_S("trace_node_fields") ":" JSON_A(
2951 JSON_S("function_info_index") ","
2954 JSON_S("children"))));
2958 writer_->AddString(",\"node_count\":");
2959 writer_->AddNumber(snapshot_->entries().length());
2960 writer_->AddString(",\"edge_count\":");
2961 writer_->AddNumber(snapshot_->edges().length());
2962 writer_->AddString(",\"trace_function_count\":");
2964 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
2966 count = tracker->function_info_list().length();
2968 writer_->AddNumber(count);
2972 static void WriteUChar(OutputStreamWriter* w, unibrow::uchar u) {
2973 static const char hex_chars[] = "0123456789ABCDEF";
2974 w->AddString("\\u");
2975 w->AddCharacter(hex_chars[(u >> 12) & 0xf]);
2976 w->AddCharacter(hex_chars[(u >> 8) & 0xf]);
2977 w->AddCharacter(hex_chars[(u >> 4) & 0xf]);
2978 w->AddCharacter(hex_chars[u & 0xf]);
2982 void HeapSnapshotJSONSerializer::SerializeTraceTree() {
2983 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
2984 if (!tracker) return;
2985 AllocationTraceTree* traces = tracker->trace_tree();
2986 SerializeTraceNode(traces->root());
2990 void HeapSnapshotJSONSerializer::SerializeTraceNode(AllocationTraceNode* node) {
2991 // The buffer needs space for 4 unsigned ints, 4 commas, [ and \0
2992 const int kBufferSize =
2993 4 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2995 EmbeddedVector<char, kBufferSize> buffer;
2997 buffer_pos = utoa(node->id(), buffer, buffer_pos);
2998 buffer[buffer_pos++] = ',';
2999 buffer_pos = utoa(node->function_info_index(), buffer, buffer_pos);
3000 buffer[buffer_pos++] = ',';
3001 buffer_pos = utoa(node->allocation_count(), buffer, buffer_pos);
3002 buffer[buffer_pos++] = ',';
3003 buffer_pos = utoa(node->allocation_size(), buffer, buffer_pos);
3004 buffer[buffer_pos++] = ',';
3005 buffer[buffer_pos++] = '[';
3006 buffer[buffer_pos++] = '\0';
3007 writer_->AddString(buffer.start());
3009 Vector<AllocationTraceNode*> children = node->children();
3010 for (int i = 0; i < children.length(); i++) {
3012 writer_->AddCharacter(',');
3014 SerializeTraceNode(children[i]);
3016 writer_->AddCharacter(']');
3020 // 0-based position is converted to 1-based during the serialization.
3021 static int SerializePosition(int position, const Vector<char>& buffer,
3023 if (position == -1) {
3024 buffer[buffer_pos++] = '0';
3026 DCHECK(position >= 0);
3027 buffer_pos = utoa(static_cast<unsigned>(position + 1), buffer, buffer_pos);
3033 void HeapSnapshotJSONSerializer::SerializeTraceNodeInfos() {
3034 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
3035 if (!tracker) return;
3036 // The buffer needs space for 6 unsigned ints, 6 commas, \n and \0
3037 const int kBufferSize =
3038 6 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
3040 EmbeddedVector<char, kBufferSize> buffer;
3041 const List<AllocationTracker::FunctionInfo*>& list =
3042 tracker->function_info_list();
3043 bool first_entry = true;
3044 for (int i = 0; i < list.length(); i++) {
3045 AllocationTracker::FunctionInfo* info = list[i];
3048 first_entry = false;
3050 buffer[buffer_pos++] = ',';
3052 buffer_pos = utoa(info->function_id, buffer, buffer_pos);
3053 buffer[buffer_pos++] = ',';
3054 buffer_pos = utoa(GetStringId(info->name), buffer, buffer_pos);
3055 buffer[buffer_pos++] = ',';
3056 buffer_pos = utoa(GetStringId(info->script_name), buffer, buffer_pos);
3057 buffer[buffer_pos++] = ',';
3058 // The cast is safe because script id is a non-negative Smi.
3059 buffer_pos = utoa(static_cast<unsigned>(info->script_id), buffer,
3061 buffer[buffer_pos++] = ',';
3062 buffer_pos = SerializePosition(info->line, buffer, buffer_pos);
3063 buffer[buffer_pos++] = ',';
3064 buffer_pos = SerializePosition(info->column, buffer, buffer_pos);
3065 buffer[buffer_pos++] = '\n';
3066 buffer[buffer_pos++] = '\0';
3067 writer_->AddString(buffer.start());
3072 void HeapSnapshotJSONSerializer::SerializeString(const unsigned char* s) {
3073 writer_->AddCharacter('\n');
3074 writer_->AddCharacter('\"');
3075 for ( ; *s != '\0'; ++s) {
3078 writer_->AddString("\\b");
3081 writer_->AddString("\\f");
3084 writer_->AddString("\\n");
3087 writer_->AddString("\\r");
3090 writer_->AddString("\\t");
3094 writer_->AddCharacter('\\');
3095 writer_->AddCharacter(*s);
3098 if (*s > 31 && *s < 128) {
3099 writer_->AddCharacter(*s);
3100 } else if (*s <= 31) {
3101 // Special character with no dedicated literal.
3102 WriteUChar(writer_, *s);
3104 // Convert UTF-8 into \u UTF-16 literal.
3105 size_t length = 1, cursor = 0;
3106 for ( ; length <= 4 && *(s + length) != '\0'; ++length) { }
3107 unibrow::uchar c = unibrow::Utf8::CalculateValue(s, length, &cursor);
3108 if (c != unibrow::Utf8::kBadChar) {
3109 WriteUChar(writer_, c);
3110 DCHECK(cursor != 0);
3113 writer_->AddCharacter('?');
3118 writer_->AddCharacter('\"');
3122 void HeapSnapshotJSONSerializer::SerializeStrings() {
3123 ScopedVector<const unsigned char*> sorted_strings(
3124 strings_.occupancy() + 1);
3125 for (HashMap::Entry* entry = strings_.Start();
3127 entry = strings_.Next(entry)) {
3128 int index = static_cast<int>(reinterpret_cast<uintptr_t>(entry->value));
3129 sorted_strings[index] = reinterpret_cast<const unsigned char*>(entry->key);
3131 writer_->AddString("\"<dummy>\"");
3132 for (int i = 1; i < sorted_strings.length(); ++i) {
3133 writer_->AddCharacter(',');
3134 SerializeString(sorted_strings[i]);
3135 if (writer_->aborted()) return;
3140 } } // namespace v8::internal