blob: 5f4667820e37ddd0871938815e19ea09db56e753 [file] [log] [blame]
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001// Copyright 2013 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "heap-snapshot-generator-inl.h"
31
32#include "heap-profiler.h"
33#include "debug.h"
34
35namespace v8 {
36namespace internal {
37
38
39HeapGraphEdge::HeapGraphEdge(Type type, const char* name, int from, int to)
40 : type_(type),
41 from_index_(from),
42 to_index_(to),
43 name_(name) {
44 ASSERT(type == kContextVariable
45 || type == kProperty
46 || type == kInternal
47 || type == kShortcut);
48}
49
50
51HeapGraphEdge::HeapGraphEdge(Type type, int index, int from, int to)
52 : type_(type),
53 from_index_(from),
54 to_index_(to),
55 index_(index) {
56 ASSERT(type == kElement || type == kHidden || type == kWeak);
57}
58
59
60void HeapGraphEdge::ReplaceToIndexWithEntry(HeapSnapshot* snapshot) {
61 to_entry_ = &snapshot->entries()[to_index_];
62}
63
64
65const int HeapEntry::kNoEntry = -1;
66
67HeapEntry::HeapEntry(HeapSnapshot* snapshot,
68 Type type,
69 const char* name,
70 SnapshotObjectId id,
71 int self_size)
72 : type_(type),
73 children_count_(0),
74 children_index_(-1),
75 self_size_(self_size),
76 id_(id),
77 snapshot_(snapshot),
78 name_(name) { }
79
80
81void HeapEntry::SetNamedReference(HeapGraphEdge::Type type,
82 const char* name,
83 HeapEntry* entry) {
84 HeapGraphEdge edge(type, name, this->index(), entry->index());
85 snapshot_->edges().Add(edge);
86 ++children_count_;
87}
88
89
90void HeapEntry::SetIndexedReference(HeapGraphEdge::Type type,
91 int index,
92 HeapEntry* entry) {
93 HeapGraphEdge edge(type, index, this->index(), entry->index());
94 snapshot_->edges().Add(edge);
95 ++children_count_;
96}
97
98
99Handle<HeapObject> HeapEntry::GetHeapObject() {
100 return snapshot_->collection()->FindHeapObjectById(id());
101}
102
103
104void HeapEntry::Print(
105 const char* prefix, const char* edge_name, int max_depth, int indent) {
106 STATIC_CHECK(sizeof(unsigned) == sizeof(id()));
107 OS::Print("%6d @%6u %*c %s%s: ",
108 self_size(), id(), indent, ' ', prefix, edge_name);
109 if (type() != kString) {
110 OS::Print("%s %.40s\n", TypeAsString(), name_);
111 } else {
112 OS::Print("\"");
113 const char* c = name_;
114 while (*c && (c - name_) <= 40) {
115 if (*c != '\n')
116 OS::Print("%c", *c);
117 else
118 OS::Print("\\n");
119 ++c;
120 }
121 OS::Print("\"\n");
122 }
123 if (--max_depth == 0) return;
124 Vector<HeapGraphEdge*> ch = children();
125 for (int i = 0; i < ch.length(); ++i) {
126 HeapGraphEdge& edge = *ch[i];
127 const char* edge_prefix = "";
128 EmbeddedVector<char, 64> index;
129 const char* edge_name = index.start();
130 switch (edge.type()) {
131 case HeapGraphEdge::kContextVariable:
132 edge_prefix = "#";
133 edge_name = edge.name();
134 break;
135 case HeapGraphEdge::kElement:
136 OS::SNPrintF(index, "%d", edge.index());
137 break;
138 case HeapGraphEdge::kInternal:
139 edge_prefix = "$";
140 edge_name = edge.name();
141 break;
142 case HeapGraphEdge::kProperty:
143 edge_name = edge.name();
144 break;
145 case HeapGraphEdge::kHidden:
146 edge_prefix = "$";
147 OS::SNPrintF(index, "%d", edge.index());
148 break;
149 case HeapGraphEdge::kShortcut:
150 edge_prefix = "^";
151 edge_name = edge.name();
152 break;
153 case HeapGraphEdge::kWeak:
154 edge_prefix = "w";
155 OS::SNPrintF(index, "%d", edge.index());
156 break;
157 default:
158 OS::SNPrintF(index, "!!! unknown edge type: %d ", edge.type());
159 }
160 edge.to()->Print(edge_prefix, edge_name, max_depth, indent + 2);
161 }
162}
163
164
165const char* HeapEntry::TypeAsString() {
166 switch (type()) {
167 case kHidden: return "/hidden/";
168 case kObject: return "/object/";
169 case kClosure: return "/closure/";
170 case kString: return "/string/";
171 case kCode: return "/code/";
172 case kArray: return "/array/";
173 case kRegExp: return "/regexp/";
174 case kHeapNumber: return "/number/";
175 case kNative: return "/native/";
176 case kSynthetic: return "/synthetic/";
177 default: return "???";
178 }
179}
180
181
182// It is very important to keep objects that form a heap snapshot
183// as small as possible.
184namespace { // Avoid littering the global namespace.
185
186template <size_t ptr_size> struct SnapshotSizeConstants;
187
188template <> struct SnapshotSizeConstants<4> {
189 static const int kExpectedHeapGraphEdgeSize = 12;
190 static const int kExpectedHeapEntrySize = 24;
191 static const int kExpectedHeapSnapshotsCollectionSize = 100;
192 static const int kExpectedHeapSnapshotSize = 136;
193 static const size_t kMaxSerializableSnapshotRawSize = 256 * MB;
194};
195
196template <> struct SnapshotSizeConstants<8> {
197 static const int kExpectedHeapGraphEdgeSize = 24;
198 static const int kExpectedHeapEntrySize = 32;
199 static const int kExpectedHeapSnapshotsCollectionSize = 152;
200 static const int kExpectedHeapSnapshotSize = 168;
201 static const uint64_t kMaxSerializableSnapshotRawSize =
202 static_cast<uint64_t>(6000) * MB;
203};
204
205} // namespace
206
207HeapSnapshot::HeapSnapshot(HeapSnapshotsCollection* collection,
208 HeapSnapshot::Type type,
209 const char* title,
210 unsigned uid)
211 : collection_(collection),
212 type_(type),
213 title_(title),
214 uid_(uid),
215 root_index_(HeapEntry::kNoEntry),
216 gc_roots_index_(HeapEntry::kNoEntry),
217 natives_root_index_(HeapEntry::kNoEntry),
218 max_snapshot_js_object_id_(0) {
219 STATIC_CHECK(
220 sizeof(HeapGraphEdge) ==
221 SnapshotSizeConstants<kPointerSize>::kExpectedHeapGraphEdgeSize);
222 STATIC_CHECK(
223 sizeof(HeapEntry) ==
224 SnapshotSizeConstants<kPointerSize>::kExpectedHeapEntrySize);
225 for (int i = 0; i < VisitorSynchronization::kNumberOfSyncTags; ++i) {
226 gc_subroot_indexes_[i] = HeapEntry::kNoEntry;
227 }
228}
229
230
231void HeapSnapshot::Delete() {
232 collection_->RemoveSnapshot(this);
233 delete this;
234}
235
236
237void HeapSnapshot::RememberLastJSObjectId() {
238 max_snapshot_js_object_id_ = collection_->last_assigned_id();
239}
240
241
242HeapEntry* HeapSnapshot::AddRootEntry() {
243 ASSERT(root_index_ == HeapEntry::kNoEntry);
244 ASSERT(entries_.is_empty()); // Root entry must be the first one.
245 HeapEntry* entry = AddEntry(HeapEntry::kObject,
246 "",
247 HeapObjectsMap::kInternalRootObjectId,
248 0);
249 root_index_ = entry->index();
250 ASSERT(root_index_ == 0);
251 return entry;
252}
253
254
255HeapEntry* HeapSnapshot::AddGcRootsEntry() {
256 ASSERT(gc_roots_index_ == HeapEntry::kNoEntry);
257 HeapEntry* entry = AddEntry(HeapEntry::kObject,
258 "(GC roots)",
259 HeapObjectsMap::kGcRootsObjectId,
260 0);
261 gc_roots_index_ = entry->index();
262 return entry;
263}
264
265
266HeapEntry* HeapSnapshot::AddGcSubrootEntry(int tag) {
267 ASSERT(gc_subroot_indexes_[tag] == HeapEntry::kNoEntry);
268 ASSERT(0 <= tag && tag < VisitorSynchronization::kNumberOfSyncTags);
269 HeapEntry* entry = AddEntry(
270 HeapEntry::kObject,
271 VisitorSynchronization::kTagNames[tag],
272 HeapObjectsMap::GetNthGcSubrootId(tag),
273 0);
274 gc_subroot_indexes_[tag] = entry->index();
275 return entry;
276}
277
278
279HeapEntry* HeapSnapshot::AddEntry(HeapEntry::Type type,
280 const char* name,
281 SnapshotObjectId id,
282 int size) {
283 HeapEntry entry(this, type, name, id, size);
284 entries_.Add(entry);
285 return &entries_.last();
286}
287
288
289void HeapSnapshot::FillChildren() {
290 ASSERT(children().is_empty());
291 children().Allocate(edges().length());
292 int children_index = 0;
293 for (int i = 0; i < entries().length(); ++i) {
294 HeapEntry* entry = &entries()[i];
295 children_index = entry->set_children_index(children_index);
296 }
297 ASSERT(edges().length() == children_index);
298 for (int i = 0; i < edges().length(); ++i) {
299 HeapGraphEdge* edge = &edges()[i];
300 edge->ReplaceToIndexWithEntry(this);
301 edge->from()->add_child(edge);
302 }
303}
304
305
306class FindEntryById {
307 public:
308 explicit FindEntryById(SnapshotObjectId id) : id_(id) { }
309 int operator()(HeapEntry* const* entry) {
310 if ((*entry)->id() == id_) return 0;
311 return (*entry)->id() < id_ ? -1 : 1;
312 }
313 private:
314 SnapshotObjectId id_;
315};
316
317
318HeapEntry* HeapSnapshot::GetEntryById(SnapshotObjectId id) {
319 List<HeapEntry*>* entries_by_id = GetSortedEntriesList();
320 // Perform a binary search by id.
321 int index = SortedListBSearch(*entries_by_id, FindEntryById(id));
322 if (index == -1)
323 return NULL;
324 return entries_by_id->at(index);
325}
326
327
328template<class T>
329static int SortByIds(const T* entry1_ptr,
330 const T* entry2_ptr) {
331 if ((*entry1_ptr)->id() == (*entry2_ptr)->id()) return 0;
332 return (*entry1_ptr)->id() < (*entry2_ptr)->id() ? -1 : 1;
333}
334
335
336List<HeapEntry*>* HeapSnapshot::GetSortedEntriesList() {
337 if (sorted_entries_.is_empty()) {
338 sorted_entries_.Allocate(entries_.length());
339 for (int i = 0; i < entries_.length(); ++i) {
340 sorted_entries_[i] = &entries_[i];
341 }
342 sorted_entries_.Sort(SortByIds);
343 }
344 return &sorted_entries_;
345}
346
347
348void HeapSnapshot::Print(int max_depth) {
349 root()->Print("", "", max_depth, 0);
350}
351
352
353template<typename T, class P>
354static size_t GetMemoryUsedByList(const List<T, P>& list) {
355 return list.length() * sizeof(T) + sizeof(list);
356}
357
358
359size_t HeapSnapshot::RawSnapshotSize() const {
360 STATIC_CHECK(SnapshotSizeConstants<kPointerSize>::kExpectedHeapSnapshotSize ==
361 sizeof(HeapSnapshot)); // NOLINT
362 return
363 sizeof(*this) +
364 GetMemoryUsedByList(entries_) +
365 GetMemoryUsedByList(edges_) +
366 GetMemoryUsedByList(children_) +
367 GetMemoryUsedByList(sorted_entries_);
368}
369
370
371// We split IDs on evens for embedder objects (see
372// HeapObjectsMap::GenerateId) and odds for native objects.
373const SnapshotObjectId HeapObjectsMap::kInternalRootObjectId = 1;
374const SnapshotObjectId HeapObjectsMap::kGcRootsObjectId =
375 HeapObjectsMap::kInternalRootObjectId + HeapObjectsMap::kObjectIdStep;
376const SnapshotObjectId HeapObjectsMap::kGcRootsFirstSubrootId =
377 HeapObjectsMap::kGcRootsObjectId + HeapObjectsMap::kObjectIdStep;
378const SnapshotObjectId HeapObjectsMap::kFirstAvailableObjectId =
379 HeapObjectsMap::kGcRootsFirstSubrootId +
380 VisitorSynchronization::kNumberOfSyncTags * HeapObjectsMap::kObjectIdStep;
381
382HeapObjectsMap::HeapObjectsMap(Heap* heap)
383 : next_id_(kFirstAvailableObjectId),
384 entries_map_(AddressesMatch),
385 heap_(heap) {
386 // This dummy element solves a problem with entries_map_.
387 // When we do lookup in HashMap we see no difference between two cases:
388 // it has an entry with NULL as the value or it has created
389 // a new entry on the fly with NULL as the default value.
390 // With such dummy element we have a guaranty that all entries_map_ entries
391 // will have the value field grater than 0.
392 // This fact is using in MoveObject method.
393 entries_.Add(EntryInfo(0, NULL, 0));
394}
395
396
397void HeapObjectsMap::SnapshotGenerationFinished() {
398 RemoveDeadEntries();
399}
400
401
402void HeapObjectsMap::MoveObject(Address from, Address to) {
403 ASSERT(to != NULL);
404 ASSERT(from != NULL);
405 if (from == to) return;
406 void* from_value = entries_map_.Remove(from, AddressHash(from));
mstarzinger@chromium.org71fc3462013-02-27 09:34:27 +0000407 if (from_value == NULL) {
408 // It may occur that some untracked object moves to an address X and there
409 // is a tracked object at that address. In this case we should remove the
410 // entry as we know that the object has died.
411 void* to_value = entries_map_.Remove(to, AddressHash(to));
412 if (to_value != NULL) {
413 int to_entry_info_index =
414 static_cast<int>(reinterpret_cast<intptr_t>(to_value));
415 entries_.at(to_entry_info_index).addr = NULL;
416 }
417 } else {
418 HashMap::Entry* to_entry = entries_map_.Lookup(to, AddressHash(to), true);
419 if (to_entry->value != NULL) {
420 // We found the existing entry with to address for an old object.
421 // Without this operation we will have two EntryInfo's with the same
422 // value in addr field. It is bad because later at RemoveDeadEntries
423 // one of this entry will be removed with the corresponding entries_map_
424 // entry.
425 int to_entry_info_index =
426 static_cast<int>(reinterpret_cast<intptr_t>(to_entry->value));
427 entries_.at(to_entry_info_index).addr = NULL;
428 }
429 int from_entry_info_index =
430 static_cast<int>(reinterpret_cast<intptr_t>(from_value));
431 entries_.at(from_entry_info_index).addr = to;
432 to_entry->value = from_value;
ulan@chromium.org2e04b582013-02-21 14:06:02 +0000433 }
ulan@chromium.org2e04b582013-02-21 14:06:02 +0000434}
435
436
437SnapshotObjectId HeapObjectsMap::FindEntry(Address addr) {
438 HashMap::Entry* entry = entries_map_.Lookup(addr, AddressHash(addr), false);
439 if (entry == NULL) return 0;
440 int entry_index = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
441 EntryInfo& entry_info = entries_.at(entry_index);
442 ASSERT(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
443 return entry_info.id;
444}
445
446
447SnapshotObjectId HeapObjectsMap::FindOrAddEntry(Address addr,
448 unsigned int size) {
449 ASSERT(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
450 HashMap::Entry* entry = entries_map_.Lookup(addr, AddressHash(addr), true);
451 if (entry->value != NULL) {
452 int entry_index =
453 static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
454 EntryInfo& entry_info = entries_.at(entry_index);
455 entry_info.accessed = true;
456 entry_info.size = size;
457 return entry_info.id;
458 }
459 entry->value = reinterpret_cast<void*>(entries_.length());
460 SnapshotObjectId id = next_id_;
461 next_id_ += kObjectIdStep;
462 entries_.Add(EntryInfo(id, addr, size));
463 ASSERT(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
464 return id;
465}
466
467
468void HeapObjectsMap::StopHeapObjectsTracking() {
469 time_intervals_.Clear();
470}
471
472void HeapObjectsMap::UpdateHeapObjectsMap() {
473 HEAP->CollectAllGarbage(Heap::kMakeHeapIterableMask,
474 "HeapSnapshotsCollection::UpdateHeapObjectsMap");
475 HeapIterator iterator(heap_);
476 for (HeapObject* obj = iterator.next();
477 obj != NULL;
478 obj = iterator.next()) {
479 FindOrAddEntry(obj->address(), obj->Size());
480 }
481 RemoveDeadEntries();
482}
483
484
485SnapshotObjectId HeapObjectsMap::PushHeapObjectsStats(OutputStream* stream) {
486 UpdateHeapObjectsMap();
487 time_intervals_.Add(TimeInterval(next_id_));
488 int prefered_chunk_size = stream->GetChunkSize();
489 List<v8::HeapStatsUpdate> stats_buffer;
490 ASSERT(!entries_.is_empty());
491 EntryInfo* entry_info = &entries_.first();
492 EntryInfo* end_entry_info = &entries_.last() + 1;
493 for (int time_interval_index = 0;
494 time_interval_index < time_intervals_.length();
495 ++time_interval_index) {
496 TimeInterval& time_interval = time_intervals_[time_interval_index];
497 SnapshotObjectId time_interval_id = time_interval.id;
498 uint32_t entries_size = 0;
499 EntryInfo* start_entry_info = entry_info;
500 while (entry_info < end_entry_info && entry_info->id < time_interval_id) {
501 entries_size += entry_info->size;
502 ++entry_info;
503 }
504 uint32_t entries_count =
505 static_cast<uint32_t>(entry_info - start_entry_info);
506 if (time_interval.count != entries_count ||
507 time_interval.size != entries_size) {
508 stats_buffer.Add(v8::HeapStatsUpdate(
509 time_interval_index,
510 time_interval.count = entries_count,
511 time_interval.size = entries_size));
512 if (stats_buffer.length() >= prefered_chunk_size) {
513 OutputStream::WriteResult result = stream->WriteHeapStatsChunk(
514 &stats_buffer.first(), stats_buffer.length());
515 if (result == OutputStream::kAbort) return last_assigned_id();
516 stats_buffer.Clear();
517 }
518 }
519 }
520 ASSERT(entry_info == end_entry_info);
521 if (!stats_buffer.is_empty()) {
522 OutputStream::WriteResult result = stream->WriteHeapStatsChunk(
523 &stats_buffer.first(), stats_buffer.length());
524 if (result == OutputStream::kAbort) return last_assigned_id();
525 }
526 stream->EndOfStream();
527 return last_assigned_id();
528}
529
530
531void HeapObjectsMap::RemoveDeadEntries() {
532 ASSERT(entries_.length() > 0 &&
533 entries_.at(0).id == 0 &&
534 entries_.at(0).addr == NULL);
535 int first_free_entry = 1;
536 for (int i = 1; i < entries_.length(); ++i) {
537 EntryInfo& entry_info = entries_.at(i);
538 if (entry_info.accessed) {
539 if (first_free_entry != i) {
540 entries_.at(first_free_entry) = entry_info;
541 }
542 entries_.at(first_free_entry).accessed = false;
543 HashMap::Entry* entry = entries_map_.Lookup(
544 entry_info.addr, AddressHash(entry_info.addr), false);
545 ASSERT(entry);
546 entry->value = reinterpret_cast<void*>(first_free_entry);
547 ++first_free_entry;
548 } else {
549 if (entry_info.addr) {
550 entries_map_.Remove(entry_info.addr, AddressHash(entry_info.addr));
551 }
552 }
553 }
554 entries_.Rewind(first_free_entry);
555 ASSERT(static_cast<uint32_t>(entries_.length()) - 1 ==
556 entries_map_.occupancy());
557}
558
559
560SnapshotObjectId HeapObjectsMap::GenerateId(v8::RetainedObjectInfo* info) {
561 SnapshotObjectId id = static_cast<SnapshotObjectId>(info->GetHash());
562 const char* label = info->GetLabel();
563 id ^= StringHasher::HashSequentialString(label,
564 static_cast<int>(strlen(label)),
565 HEAP->HashSeed());
566 intptr_t element_count = info->GetElementCount();
567 if (element_count != -1)
568 id ^= ComputeIntegerHash(static_cast<uint32_t>(element_count),
569 v8::internal::kZeroHashSeed);
570 return id << 1;
571}
572
573
574size_t HeapObjectsMap::GetUsedMemorySize() const {
575 return
576 sizeof(*this) +
577 sizeof(HashMap::Entry) * entries_map_.capacity() +
578 GetMemoryUsedByList(entries_) +
579 GetMemoryUsedByList(time_intervals_);
580}
581
582
583HeapSnapshotsCollection::HeapSnapshotsCollection(Heap* heap)
584 : is_tracking_objects_(false),
585 snapshots_uids_(HeapSnapshotsMatch),
586 token_enumerator_(new TokenEnumerator()),
587 ids_(heap) {
588}
589
590
591static void DeleteHeapSnapshot(HeapSnapshot** snapshot_ptr) {
592 delete *snapshot_ptr;
593}
594
595
596HeapSnapshotsCollection::~HeapSnapshotsCollection() {
597 delete token_enumerator_;
598 snapshots_.Iterate(DeleteHeapSnapshot);
599}
600
601
602HeapSnapshot* HeapSnapshotsCollection::NewSnapshot(HeapSnapshot::Type type,
603 const char* name,
604 unsigned uid) {
605 is_tracking_objects_ = true; // Start watching for heap objects moves.
606 return new HeapSnapshot(this, type, name, uid);
607}
608
609
610void HeapSnapshotsCollection::SnapshotGenerationFinished(
611 HeapSnapshot* snapshot) {
612 ids_.SnapshotGenerationFinished();
613 if (snapshot != NULL) {
614 snapshots_.Add(snapshot);
615 HashMap::Entry* entry =
616 snapshots_uids_.Lookup(reinterpret_cast<void*>(snapshot->uid()),
617 static_cast<uint32_t>(snapshot->uid()),
618 true);
619 ASSERT(entry->value == NULL);
620 entry->value = snapshot;
621 }
622}
623
624
625HeapSnapshot* HeapSnapshotsCollection::GetSnapshot(unsigned uid) {
626 HashMap::Entry* entry = snapshots_uids_.Lookup(reinterpret_cast<void*>(uid),
627 static_cast<uint32_t>(uid),
628 false);
629 return entry != NULL ? reinterpret_cast<HeapSnapshot*>(entry->value) : NULL;
630}
631
632
633void HeapSnapshotsCollection::RemoveSnapshot(HeapSnapshot* snapshot) {
634 snapshots_.RemoveElement(snapshot);
635 unsigned uid = snapshot->uid();
636 snapshots_uids_.Remove(reinterpret_cast<void*>(uid),
637 static_cast<uint32_t>(uid));
638}
639
640
641Handle<HeapObject> HeapSnapshotsCollection::FindHeapObjectById(
642 SnapshotObjectId id) {
643 // First perform a full GC in order to avoid dead objects.
644 HEAP->CollectAllGarbage(Heap::kMakeHeapIterableMask,
645 "HeapSnapshotsCollection::FindHeapObjectById");
646 AssertNoAllocation no_allocation;
647 HeapObject* object = NULL;
648 HeapIterator iterator(heap(), HeapIterator::kFilterUnreachable);
649 // Make sure that object with the given id is still reachable.
650 for (HeapObject* obj = iterator.next();
651 obj != NULL;
652 obj = iterator.next()) {
653 if (ids_.FindEntry(obj->address()) == id) {
654 ASSERT(object == NULL);
655 object = obj;
656 // Can't break -- kFilterUnreachable requires full heap traversal.
657 }
658 }
659 return object != NULL ? Handle<HeapObject>(object) : Handle<HeapObject>();
660}
661
662
663size_t HeapSnapshotsCollection::GetUsedMemorySize() const {
664 STATIC_CHECK(SnapshotSizeConstants<kPointerSize>::
665 kExpectedHeapSnapshotsCollectionSize ==
666 sizeof(HeapSnapshotsCollection)); // NOLINT
667 size_t size = sizeof(*this);
668 size += names_.GetUsedMemorySize();
669 size += ids_.GetUsedMemorySize();
670 size += sizeof(HashMap::Entry) * snapshots_uids_.capacity();
671 size += GetMemoryUsedByList(snapshots_);
672 for (int i = 0; i < snapshots_.length(); ++i) {
673 size += snapshots_[i]->RawSnapshotSize();
674 }
675 return size;
676}
677
678
679HeapEntriesMap::HeapEntriesMap()
680 : entries_(HeapThingsMatch) {
681}
682
683
684int HeapEntriesMap::Map(HeapThing thing) {
685 HashMap::Entry* cache_entry = entries_.Lookup(thing, Hash(thing), false);
686 if (cache_entry == NULL) return HeapEntry::kNoEntry;
687 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
688}
689
690
691void HeapEntriesMap::Pair(HeapThing thing, int entry) {
692 HashMap::Entry* cache_entry = entries_.Lookup(thing, Hash(thing), true);
693 ASSERT(cache_entry->value == NULL);
694 cache_entry->value = reinterpret_cast<void*>(static_cast<intptr_t>(entry));
695}
696
697
698HeapObjectsSet::HeapObjectsSet()
699 : entries_(HeapEntriesMap::HeapThingsMatch) {
700}
701
702
703void HeapObjectsSet::Clear() {
704 entries_.Clear();
705}
706
707
708bool HeapObjectsSet::Contains(Object* obj) {
709 if (!obj->IsHeapObject()) return false;
710 HeapObject* object = HeapObject::cast(obj);
711 return entries_.Lookup(object, HeapEntriesMap::Hash(object), false) != NULL;
712}
713
714
715void HeapObjectsSet::Insert(Object* obj) {
716 if (!obj->IsHeapObject()) return;
717 HeapObject* object = HeapObject::cast(obj);
718 entries_.Lookup(object, HeapEntriesMap::Hash(object), true);
719}
720
721
722const char* HeapObjectsSet::GetTag(Object* obj) {
723 HeapObject* object = HeapObject::cast(obj);
724 HashMap::Entry* cache_entry =
725 entries_.Lookup(object, HeapEntriesMap::Hash(object), false);
726 return cache_entry != NULL
727 ? reinterpret_cast<const char*>(cache_entry->value)
728 : NULL;
729}
730
731
732void HeapObjectsSet::SetTag(Object* obj, const char* tag) {
733 if (!obj->IsHeapObject()) return;
734 HeapObject* object = HeapObject::cast(obj);
735 HashMap::Entry* cache_entry =
736 entries_.Lookup(object, HeapEntriesMap::Hash(object), true);
737 cache_entry->value = const_cast<char*>(tag);
738}
739
740
741HeapObject* const V8HeapExplorer::kInternalRootObject =
742 reinterpret_cast<HeapObject*>(
743 static_cast<intptr_t>(HeapObjectsMap::kInternalRootObjectId));
744HeapObject* const V8HeapExplorer::kGcRootsObject =
745 reinterpret_cast<HeapObject*>(
746 static_cast<intptr_t>(HeapObjectsMap::kGcRootsObjectId));
747HeapObject* const V8HeapExplorer::kFirstGcSubrootObject =
748 reinterpret_cast<HeapObject*>(
749 static_cast<intptr_t>(HeapObjectsMap::kGcRootsFirstSubrootId));
750HeapObject* const V8HeapExplorer::kLastGcSubrootObject =
751 reinterpret_cast<HeapObject*>(
752 static_cast<intptr_t>(HeapObjectsMap::kFirstAvailableObjectId));
753
754
755V8HeapExplorer::V8HeapExplorer(
756 HeapSnapshot* snapshot,
757 SnapshottingProgressReportingInterface* progress,
758 v8::HeapProfiler::ObjectNameResolver* resolver)
759 : heap_(Isolate::Current()->heap()),
760 snapshot_(snapshot),
761 collection_(snapshot_->collection()),
762 progress_(progress),
763 filler_(NULL),
764 global_object_name_resolver_(resolver) {
765}
766
767
768V8HeapExplorer::~V8HeapExplorer() {
769}
770
771
772HeapEntry* V8HeapExplorer::AllocateEntry(HeapThing ptr) {
773 return AddEntry(reinterpret_cast<HeapObject*>(ptr));
774}
775
776
777HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object) {
778 if (object == kInternalRootObject) {
779 snapshot_->AddRootEntry();
780 return snapshot_->root();
781 } else if (object == kGcRootsObject) {
782 HeapEntry* entry = snapshot_->AddGcRootsEntry();
783 return entry;
784 } else if (object >= kFirstGcSubrootObject && object < kLastGcSubrootObject) {
785 HeapEntry* entry = snapshot_->AddGcSubrootEntry(GetGcSubrootOrder(object));
786 return entry;
787 } else if (object->IsJSFunction()) {
788 JSFunction* func = JSFunction::cast(object);
789 SharedFunctionInfo* shared = func->shared();
790 const char* name = shared->bound() ? "native_bind" :
791 collection_->names()->GetName(String::cast(shared->name()));
792 return AddEntry(object, HeapEntry::kClosure, name);
793 } else if (object->IsJSRegExp()) {
794 JSRegExp* re = JSRegExp::cast(object);
795 return AddEntry(object,
796 HeapEntry::kRegExp,
797 collection_->names()->GetName(re->Pattern()));
798 } else if (object->IsJSObject()) {
799 const char* name = collection_->names()->GetName(
800 GetConstructorName(JSObject::cast(object)));
801 if (object->IsJSGlobalObject()) {
802 const char* tag = objects_tags_.GetTag(object);
803 if (tag != NULL) {
804 name = collection_->names()->GetFormatted("%s / %s", name, tag);
805 }
806 }
807 return AddEntry(object, HeapEntry::kObject, name);
808 } else if (object->IsString()) {
809 return AddEntry(object,
810 HeapEntry::kString,
811 collection_->names()->GetName(String::cast(object)));
812 } else if (object->IsCode()) {
813 return AddEntry(object, HeapEntry::kCode, "");
814 } else if (object->IsSharedFunctionInfo()) {
815 String* name = String::cast(SharedFunctionInfo::cast(object)->name());
816 return AddEntry(object,
817 HeapEntry::kCode,
818 collection_->names()->GetName(name));
819 } else if (object->IsScript()) {
820 Object* name = Script::cast(object)->name();
821 return AddEntry(object,
822 HeapEntry::kCode,
823 name->IsString()
824 ? collection_->names()->GetName(String::cast(name))
825 : "");
826 } else if (object->IsNativeContext()) {
827 return AddEntry(object, HeapEntry::kHidden, "system / NativeContext");
828 } else if (object->IsContext()) {
829 return AddEntry(object, HeapEntry::kHidden, "system / Context");
830 } else if (object->IsFixedArray() ||
831 object->IsFixedDoubleArray() ||
832 object->IsByteArray() ||
833 object->IsExternalArray()) {
834 return AddEntry(object, HeapEntry::kArray, "");
835 } else if (object->IsHeapNumber()) {
836 return AddEntry(object, HeapEntry::kHeapNumber, "number");
837 }
838 return AddEntry(object, HeapEntry::kHidden, GetSystemEntryName(object));
839}
840
841
842HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object,
843 HeapEntry::Type type,
844 const char* name) {
845 int object_size = object->Size();
846 SnapshotObjectId object_id =
847 collection_->GetObjectId(object->address(), object_size);
848 return snapshot_->AddEntry(type, name, object_id, object_size);
849}
850
851
852class GcSubrootsEnumerator : public ObjectVisitor {
853 public:
854 GcSubrootsEnumerator(
855 SnapshotFillerInterface* filler, V8HeapExplorer* explorer)
856 : filler_(filler),
857 explorer_(explorer),
858 previous_object_count_(0),
859 object_count_(0) {
860 }
861 void VisitPointers(Object** start, Object** end) {
862 object_count_ += end - start;
863 }
864 void Synchronize(VisitorSynchronization::SyncTag tag) {
865 // Skip empty subroots.
866 if (previous_object_count_ != object_count_) {
867 previous_object_count_ = object_count_;
868 filler_->AddEntry(V8HeapExplorer::GetNthGcSubrootObject(tag), explorer_);
869 }
870 }
871 private:
872 SnapshotFillerInterface* filler_;
873 V8HeapExplorer* explorer_;
874 intptr_t previous_object_count_;
875 intptr_t object_count_;
876};
877
878
879void V8HeapExplorer::AddRootEntries(SnapshotFillerInterface* filler) {
880 filler->AddEntry(kInternalRootObject, this);
881 filler->AddEntry(kGcRootsObject, this);
882 GcSubrootsEnumerator enumerator(filler, this);
883 heap_->IterateRoots(&enumerator, VISIT_ALL);
884}
885
886
887const char* V8HeapExplorer::GetSystemEntryName(HeapObject* object) {
888 switch (object->map()->instance_type()) {
889 case MAP_TYPE:
890 switch (Map::cast(object)->instance_type()) {
891#define MAKE_STRING_MAP_CASE(instance_type, size, name, Name) \
892 case instance_type: return "system / Map (" #Name ")";
893 STRING_TYPE_LIST(MAKE_STRING_MAP_CASE)
894#undef MAKE_STRING_MAP_CASE
895 default: return "system / Map";
896 }
897 case JS_GLOBAL_PROPERTY_CELL_TYPE: return "system / JSGlobalPropertyCell";
898 case FOREIGN_TYPE: return "system / Foreign";
899 case ODDBALL_TYPE: return "system / Oddball";
900#define MAKE_STRUCT_CASE(NAME, Name, name) \
901 case NAME##_TYPE: return "system / "#Name;
902 STRUCT_LIST(MAKE_STRUCT_CASE)
903#undef MAKE_STRUCT_CASE
904 default: return "system";
905 }
906}
907
908
909int V8HeapExplorer::EstimateObjectsCount(HeapIterator* iterator) {
910 int objects_count = 0;
911 for (HeapObject* obj = iterator->next();
912 obj != NULL;
913 obj = iterator->next()) {
914 objects_count++;
915 }
916 return objects_count;
917}
918
919
920class IndexedReferencesExtractor : public ObjectVisitor {
921 public:
922 IndexedReferencesExtractor(V8HeapExplorer* generator,
923 HeapObject* parent_obj,
924 int parent)
925 : generator_(generator),
926 parent_obj_(parent_obj),
927 parent_(parent),
928 next_index_(1) {
929 }
930 void VisitPointers(Object** start, Object** end) {
931 for (Object** p = start; p < end; p++) {
932 if (CheckVisitedAndUnmark(p)) continue;
933 generator_->SetHiddenReference(parent_obj_, parent_, next_index_++, *p);
934 }
935 }
936 static void MarkVisitedField(HeapObject* obj, int offset) {
937 if (offset < 0) return;
938 Address field = obj->address() + offset;
939 ASSERT(!Memory::Object_at(field)->IsFailure());
940 ASSERT(Memory::Object_at(field)->IsHeapObject());
941 *field |= kFailureTag;
942 }
943
944 private:
945 bool CheckVisitedAndUnmark(Object** field) {
946 if ((*field)->IsFailure()) {
947 intptr_t untagged = reinterpret_cast<intptr_t>(*field) & ~kFailureTagMask;
948 *field = reinterpret_cast<Object*>(untagged | kHeapObjectTag);
949 ASSERT((*field)->IsHeapObject());
950 return true;
951 }
952 return false;
953 }
954 V8HeapExplorer* generator_;
955 HeapObject* parent_obj_;
956 int parent_;
957 int next_index_;
958};
959
960
961void V8HeapExplorer::ExtractReferences(HeapObject* obj) {
962 HeapEntry* heap_entry = GetEntry(obj);
963 if (heap_entry == NULL) return; // No interest in this object.
964 int entry = heap_entry->index();
965
966 bool extract_indexed_refs = true;
967 if (obj->IsJSGlobalProxy()) {
968 ExtractJSGlobalProxyReferences(JSGlobalProxy::cast(obj));
969 } else if (obj->IsJSObject()) {
970 ExtractJSObjectReferences(entry, JSObject::cast(obj));
971 } else if (obj->IsString()) {
972 ExtractStringReferences(entry, String::cast(obj));
973 } else if (obj->IsContext()) {
974 ExtractContextReferences(entry, Context::cast(obj));
975 } else if (obj->IsMap()) {
976 ExtractMapReferences(entry, Map::cast(obj));
977 } else if (obj->IsSharedFunctionInfo()) {
978 ExtractSharedFunctionInfoReferences(entry, SharedFunctionInfo::cast(obj));
979 } else if (obj->IsScript()) {
980 ExtractScriptReferences(entry, Script::cast(obj));
981 } else if (obj->IsCodeCache()) {
982 ExtractCodeCacheReferences(entry, CodeCache::cast(obj));
983 } else if (obj->IsCode()) {
984 ExtractCodeReferences(entry, Code::cast(obj));
985 } else if (obj->IsJSGlobalPropertyCell()) {
986 ExtractJSGlobalPropertyCellReferences(
987 entry, JSGlobalPropertyCell::cast(obj));
988 extract_indexed_refs = false;
989 }
990 if (extract_indexed_refs) {
991 SetInternalReference(obj, entry, "map", obj->map(), HeapObject::kMapOffset);
992 IndexedReferencesExtractor refs_extractor(this, obj, entry);
993 obj->Iterate(&refs_extractor);
994 }
995}
996
997
998void V8HeapExplorer::ExtractJSGlobalProxyReferences(JSGlobalProxy* proxy) {
999 // We need to reference JS global objects from snapshot's root.
1000 // We use JSGlobalProxy because this is what embedder (e.g. browser)
1001 // uses for the global object.
1002 Object* object = proxy->map()->prototype();
1003 bool is_debug_object = false;
1004#ifdef ENABLE_DEBUGGER_SUPPORT
1005 is_debug_object = object->IsGlobalObject() &&
1006 Isolate::Current()->debug()->IsDebugGlobal(GlobalObject::cast(object));
1007#endif
1008 if (!is_debug_object) {
1009 SetUserGlobalReference(object);
1010 }
1011}
1012
1013
1014void V8HeapExplorer::ExtractJSObjectReferences(
1015 int entry, JSObject* js_obj) {
1016 HeapObject* obj = js_obj;
1017 ExtractClosureReferences(js_obj, entry);
1018 ExtractPropertyReferences(js_obj, entry);
1019 ExtractElementReferences(js_obj, entry);
1020 ExtractInternalReferences(js_obj, entry);
1021 SetPropertyReference(
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001022 obj, entry, heap_->proto_string(), js_obj->GetPrototype());
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001023 if (obj->IsJSFunction()) {
1024 JSFunction* js_fun = JSFunction::cast(js_obj);
1025 Object* proto_or_map = js_fun->prototype_or_initial_map();
1026 if (!proto_or_map->IsTheHole()) {
1027 if (!proto_or_map->IsMap()) {
1028 SetPropertyReference(
1029 obj, entry,
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001030 heap_->prototype_string(), proto_or_map,
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001031 NULL,
1032 JSFunction::kPrototypeOrInitialMapOffset);
1033 } else {
1034 SetPropertyReference(
1035 obj, entry,
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001036 heap_->prototype_string(), js_fun->prototype());
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001037 }
1038 }
1039 SharedFunctionInfo* shared_info = js_fun->shared();
1040 // JSFunction has either bindings or literals and never both.
1041 bool bound = shared_info->bound();
1042 TagObject(js_fun->literals_or_bindings(),
1043 bound ? "(function bindings)" : "(function literals)");
1044 SetInternalReference(js_fun, entry,
1045 bound ? "bindings" : "literals",
1046 js_fun->literals_or_bindings(),
1047 JSFunction::kLiteralsOffset);
1048 TagObject(shared_info, "(shared function info)");
1049 SetInternalReference(js_fun, entry,
1050 "shared", shared_info,
1051 JSFunction::kSharedFunctionInfoOffset);
1052 TagObject(js_fun->unchecked_context(), "(context)");
1053 SetInternalReference(js_fun, entry,
1054 "context", js_fun->unchecked_context(),
1055 JSFunction::kContextOffset);
1056 for (int i = JSFunction::kNonWeakFieldsEndOffset;
1057 i < JSFunction::kSize;
1058 i += kPointerSize) {
1059 SetWeakReference(js_fun, entry, i, *HeapObject::RawField(js_fun, i), i);
1060 }
1061 } else if (obj->IsGlobalObject()) {
1062 GlobalObject* global_obj = GlobalObject::cast(obj);
1063 SetInternalReference(global_obj, entry,
1064 "builtins", global_obj->builtins(),
1065 GlobalObject::kBuiltinsOffset);
1066 SetInternalReference(global_obj, entry,
1067 "native_context", global_obj->native_context(),
1068 GlobalObject::kNativeContextOffset);
1069 SetInternalReference(global_obj, entry,
1070 "global_receiver", global_obj->global_receiver(),
1071 GlobalObject::kGlobalReceiverOffset);
1072 }
1073 TagObject(js_obj->properties(), "(object properties)");
1074 SetInternalReference(obj, entry,
1075 "properties", js_obj->properties(),
1076 JSObject::kPropertiesOffset);
1077 TagObject(js_obj->elements(), "(object elements)");
1078 SetInternalReference(obj, entry,
1079 "elements", js_obj->elements(),
1080 JSObject::kElementsOffset);
1081}
1082
1083
1084void V8HeapExplorer::ExtractStringReferences(int entry, String* string) {
1085 if (string->IsConsString()) {
1086 ConsString* cs = ConsString::cast(string);
1087 SetInternalReference(cs, entry, "first", cs->first(),
1088 ConsString::kFirstOffset);
1089 SetInternalReference(cs, entry, "second", cs->second(),
1090 ConsString::kSecondOffset);
1091 } else if (string->IsSlicedString()) {
1092 SlicedString* ss = SlicedString::cast(string);
1093 SetInternalReference(ss, entry, "parent", ss->parent(),
1094 SlicedString::kParentOffset);
1095 }
1096}
1097
1098
1099void V8HeapExplorer::ExtractContextReferences(int entry, Context* context) {
1100#define EXTRACT_CONTEXT_FIELD(index, type, name) \
1101 SetInternalReference(context, entry, #name, context->get(Context::index), \
1102 FixedArray::OffsetOfElementAt(Context::index));
1103 EXTRACT_CONTEXT_FIELD(CLOSURE_INDEX, JSFunction, closure);
1104 EXTRACT_CONTEXT_FIELD(PREVIOUS_INDEX, Context, previous);
1105 EXTRACT_CONTEXT_FIELD(EXTENSION_INDEX, Object, extension);
1106 EXTRACT_CONTEXT_FIELD(GLOBAL_OBJECT_INDEX, GlobalObject, global);
1107 if (context->IsNativeContext()) {
1108 TagObject(context->jsfunction_result_caches(),
1109 "(context func. result caches)");
1110 TagObject(context->normalized_map_cache(), "(context norm. map cache)");
1111 TagObject(context->runtime_context(), "(runtime context)");
1112 TagObject(context->embedder_data(), "(context data)");
1113 NATIVE_CONTEXT_FIELDS(EXTRACT_CONTEXT_FIELD);
1114#undef EXTRACT_CONTEXT_FIELD
1115 for (int i = Context::FIRST_WEAK_SLOT;
1116 i < Context::NATIVE_CONTEXT_SLOTS;
1117 ++i) {
1118 SetWeakReference(context, entry, i, context->get(i),
1119 FixedArray::OffsetOfElementAt(i));
1120 }
1121 }
1122}
1123
1124
1125void V8HeapExplorer::ExtractMapReferences(int entry, Map* map) {
1126 SetInternalReference(map, entry,
1127 "prototype", map->prototype(), Map::kPrototypeOffset);
1128 SetInternalReference(map, entry,
1129 "constructor", map->constructor(),
1130 Map::kConstructorOffset);
1131 if (map->HasTransitionArray()) {
1132 TransitionArray* transitions = map->transitions();
1133
1134 Object* back_pointer = transitions->back_pointer_storage();
1135 TagObject(transitions->back_pointer_storage(), "(back pointer)");
1136 SetInternalReference(transitions, entry,
1137 "backpointer", back_pointer,
1138 TransitionArray::kBackPointerStorageOffset);
1139 IndexedReferencesExtractor transitions_refs(this, transitions, entry);
1140 transitions->Iterate(&transitions_refs);
1141
1142 TagObject(transitions, "(transition array)");
1143 SetInternalReference(map, entry,
1144 "transitions", transitions,
1145 Map::kTransitionsOrBackPointerOffset);
1146 } else {
1147 Object* back_pointer = map->GetBackPointer();
1148 TagObject(back_pointer, "(back pointer)");
1149 SetInternalReference(map, entry,
1150 "backpointer", back_pointer,
1151 Map::kTransitionsOrBackPointerOffset);
1152 }
1153 DescriptorArray* descriptors = map->instance_descriptors();
1154 TagObject(descriptors, "(map descriptors)");
1155 SetInternalReference(map, entry,
1156 "descriptors", descriptors,
1157 Map::kDescriptorsOffset);
1158
1159 SetInternalReference(map, entry,
1160 "code_cache", map->code_cache(),
1161 Map::kCodeCacheOffset);
1162}
1163
1164
1165void V8HeapExplorer::ExtractSharedFunctionInfoReferences(
1166 int entry, SharedFunctionInfo* shared) {
1167 HeapObject* obj = shared;
1168 SetInternalReference(obj, entry,
1169 "name", shared->name(),
1170 SharedFunctionInfo::kNameOffset);
1171 TagObject(shared->code(), "(code)");
1172 SetInternalReference(obj, entry,
1173 "code", shared->code(),
1174 SharedFunctionInfo::kCodeOffset);
1175 TagObject(shared->scope_info(), "(function scope info)");
1176 SetInternalReference(obj, entry,
1177 "scope_info", shared->scope_info(),
1178 SharedFunctionInfo::kScopeInfoOffset);
1179 SetInternalReference(obj, entry,
1180 "instance_class_name", shared->instance_class_name(),
1181 SharedFunctionInfo::kInstanceClassNameOffset);
1182 SetInternalReference(obj, entry,
1183 "script", shared->script(),
1184 SharedFunctionInfo::kScriptOffset);
1185 TagObject(shared->construct_stub(), "(code)");
1186 SetInternalReference(obj, entry,
1187 "construct_stub", shared->construct_stub(),
1188 SharedFunctionInfo::kConstructStubOffset);
1189 SetInternalReference(obj, entry,
1190 "function_data", shared->function_data(),
1191 SharedFunctionInfo::kFunctionDataOffset);
1192 SetInternalReference(obj, entry,
1193 "debug_info", shared->debug_info(),
1194 SharedFunctionInfo::kDebugInfoOffset);
1195 SetInternalReference(obj, entry,
1196 "inferred_name", shared->inferred_name(),
1197 SharedFunctionInfo::kInferredNameOffset);
1198 SetInternalReference(obj, entry,
1199 "this_property_assignments",
1200 shared->this_property_assignments(),
1201 SharedFunctionInfo::kThisPropertyAssignmentsOffset);
1202 SetWeakReference(obj, entry,
1203 1, shared->initial_map(),
1204 SharedFunctionInfo::kInitialMapOffset);
1205}
1206
1207
1208void V8HeapExplorer::ExtractScriptReferences(int entry, Script* script) {
1209 HeapObject* obj = script;
1210 SetInternalReference(obj, entry,
1211 "source", script->source(),
1212 Script::kSourceOffset);
1213 SetInternalReference(obj, entry,
1214 "name", script->name(),
1215 Script::kNameOffset);
1216 SetInternalReference(obj, entry,
1217 "data", script->data(),
1218 Script::kDataOffset);
1219 SetInternalReference(obj, entry,
1220 "context_data", script->context_data(),
1221 Script::kContextOffset);
1222 TagObject(script->line_ends(), "(script line ends)");
1223 SetInternalReference(obj, entry,
1224 "line_ends", script->line_ends(),
1225 Script::kLineEndsOffset);
1226}
1227
1228
1229void V8HeapExplorer::ExtractCodeCacheReferences(
1230 int entry, CodeCache* code_cache) {
1231 TagObject(code_cache->default_cache(), "(default code cache)");
1232 SetInternalReference(code_cache, entry,
1233 "default_cache", code_cache->default_cache(),
1234 CodeCache::kDefaultCacheOffset);
1235 TagObject(code_cache->normal_type_cache(), "(code type cache)");
1236 SetInternalReference(code_cache, entry,
1237 "type_cache", code_cache->normal_type_cache(),
1238 CodeCache::kNormalTypeCacheOffset);
1239}
1240
1241
1242void V8HeapExplorer::ExtractCodeReferences(int entry, Code* code) {
1243 TagObject(code->relocation_info(), "(code relocation info)");
1244 SetInternalReference(code, entry,
1245 "relocation_info", code->relocation_info(),
1246 Code::kRelocationInfoOffset);
1247 SetInternalReference(code, entry,
1248 "handler_table", code->handler_table(),
1249 Code::kHandlerTableOffset);
1250 TagObject(code->deoptimization_data(), "(code deopt data)");
1251 SetInternalReference(code, entry,
1252 "deoptimization_data", code->deoptimization_data(),
1253 Code::kDeoptimizationDataOffset);
1254 if (code->kind() == Code::FUNCTION) {
1255 SetInternalReference(code, entry,
1256 "type_feedback_info", code->type_feedback_info(),
1257 Code::kTypeFeedbackInfoOffset);
1258 }
1259 SetInternalReference(code, entry,
1260 "gc_metadata", code->gc_metadata(),
1261 Code::kGCMetadataOffset);
1262}
1263
1264
1265void V8HeapExplorer::ExtractJSGlobalPropertyCellReferences(
1266 int entry, JSGlobalPropertyCell* cell) {
1267 SetInternalReference(cell, entry, "value", cell->value());
1268}
1269
1270
1271void V8HeapExplorer::ExtractClosureReferences(JSObject* js_obj, int entry) {
1272 if (!js_obj->IsJSFunction()) return;
1273
1274 JSFunction* func = JSFunction::cast(js_obj);
1275 if (func->shared()->bound()) {
1276 FixedArray* bindings = func->function_bindings();
1277 SetNativeBindReference(js_obj, entry, "bound_this",
1278 bindings->get(JSFunction::kBoundThisIndex));
1279 SetNativeBindReference(js_obj, entry, "bound_function",
1280 bindings->get(JSFunction::kBoundFunctionIndex));
1281 for (int i = JSFunction::kBoundArgumentsStartIndex;
1282 i < bindings->length(); i++) {
1283 const char* reference_name = collection_->names()->GetFormatted(
1284 "bound_argument_%d",
1285 i - JSFunction::kBoundArgumentsStartIndex);
1286 SetNativeBindReference(js_obj, entry, reference_name,
1287 bindings->get(i));
1288 }
1289 } else {
1290 Context* context = func->context()->declaration_context();
1291 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
1292 // Add context allocated locals.
1293 int context_locals = scope_info->ContextLocalCount();
1294 for (int i = 0; i < context_locals; ++i) {
1295 String* local_name = scope_info->ContextLocalName(i);
1296 int idx = Context::MIN_CONTEXT_SLOTS + i;
1297 SetClosureReference(js_obj, entry, local_name, context->get(idx));
1298 }
1299
1300 // Add function variable.
1301 if (scope_info->HasFunctionName()) {
1302 String* name = scope_info->FunctionName();
1303 VariableMode mode;
1304 int idx = scope_info->FunctionContextSlotIndex(name, &mode);
1305 if (idx >= 0) {
1306 SetClosureReference(js_obj, entry, name, context->get(idx));
1307 }
1308 }
1309 }
1310}
1311
1312
1313void V8HeapExplorer::ExtractPropertyReferences(JSObject* js_obj, int entry) {
1314 if (js_obj->HasFastProperties()) {
1315 DescriptorArray* descs = js_obj->map()->instance_descriptors();
1316 int real_size = js_obj->map()->NumberOfOwnDescriptors();
1317 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1318 if (descs->GetDetails(i).descriptor_index() > real_size) continue;
1319 switch (descs->GetType(i)) {
1320 case FIELD: {
1321 int index = descs->GetFieldIndex(i);
1322
ulan@chromium.org750145a2013-03-07 15:14:13 +00001323 Name* k = descs->GetKey(i);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001324 if (index < js_obj->map()->inobject_properties()) {
1325 Object* value = js_obj->InObjectPropertyAt(index);
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001326 if (k != heap_->hidden_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001327 SetPropertyReference(
1328 js_obj, entry,
1329 k, value,
1330 NULL,
1331 js_obj->GetInObjectPropertyOffset(index));
1332 } else {
1333 TagObject(value, "(hidden properties)");
1334 SetInternalReference(
1335 js_obj, entry,
1336 "hidden_properties", value,
1337 js_obj->GetInObjectPropertyOffset(index));
1338 }
1339 } else {
1340 Object* value = js_obj->FastPropertyAt(index);
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001341 if (k != heap_->hidden_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001342 SetPropertyReference(js_obj, entry, k, value);
1343 } else {
1344 TagObject(value, "(hidden properties)");
1345 SetInternalReference(js_obj, entry, "hidden_properties", value);
1346 }
1347 }
1348 break;
1349 }
1350 case CONSTANT_FUNCTION:
1351 SetPropertyReference(
1352 js_obj, entry,
1353 descs->GetKey(i), descs->GetConstantFunction(i));
1354 break;
1355 case CALLBACKS: {
1356 Object* callback_obj = descs->GetValue(i);
1357 if (callback_obj->IsAccessorPair()) {
1358 AccessorPair* accessors = AccessorPair::cast(callback_obj);
1359 if (Object* getter = accessors->getter()) {
1360 SetPropertyReference(js_obj, entry, descs->GetKey(i),
1361 getter, "get-%s");
1362 }
1363 if (Object* setter = accessors->setter()) {
1364 SetPropertyReference(js_obj, entry, descs->GetKey(i),
1365 setter, "set-%s");
1366 }
1367 }
1368 break;
1369 }
1370 case NORMAL: // only in slow mode
1371 case HANDLER: // only in lookup results, not in descriptors
1372 case INTERCEPTOR: // only in lookup results, not in descriptors
1373 break;
1374 case TRANSITION:
1375 case NONEXISTENT:
1376 UNREACHABLE();
1377 break;
1378 }
1379 }
1380 } else {
ulan@chromium.org750145a2013-03-07 15:14:13 +00001381 NameDictionary* dictionary = js_obj->property_dictionary();
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001382 int length = dictionary->Capacity();
1383 for (int i = 0; i < length; ++i) {
1384 Object* k = dictionary->KeyAt(i);
1385 if (dictionary->IsKey(k)) {
1386 Object* target = dictionary->ValueAt(i);
1387 // We assume that global objects can only have slow properties.
1388 Object* value = target->IsJSGlobalPropertyCell()
1389 ? JSGlobalPropertyCell::cast(target)->value()
1390 : target;
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001391 if (k != heap_->hidden_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001392 SetPropertyReference(js_obj, entry, String::cast(k), value);
1393 } else {
1394 TagObject(value, "(hidden properties)");
1395 SetInternalReference(js_obj, entry, "hidden_properties", value);
1396 }
1397 }
1398 }
1399 }
1400}
1401
1402
1403void V8HeapExplorer::ExtractElementReferences(JSObject* js_obj, int entry) {
1404 if (js_obj->HasFastObjectElements()) {
1405 FixedArray* elements = FixedArray::cast(js_obj->elements());
1406 int length = js_obj->IsJSArray() ?
1407 Smi::cast(JSArray::cast(js_obj)->length())->value() :
1408 elements->length();
1409 for (int i = 0; i < length; ++i) {
1410 if (!elements->get(i)->IsTheHole()) {
1411 SetElementReference(js_obj, entry, i, elements->get(i));
1412 }
1413 }
1414 } else if (js_obj->HasDictionaryElements()) {
1415 SeededNumberDictionary* dictionary = js_obj->element_dictionary();
1416 int length = dictionary->Capacity();
1417 for (int i = 0; i < length; ++i) {
1418 Object* k = dictionary->KeyAt(i);
1419 if (dictionary->IsKey(k)) {
1420 ASSERT(k->IsNumber());
1421 uint32_t index = static_cast<uint32_t>(k->Number());
1422 SetElementReference(js_obj, entry, index, dictionary->ValueAt(i));
1423 }
1424 }
1425 }
1426}
1427
1428
1429void V8HeapExplorer::ExtractInternalReferences(JSObject* js_obj, int entry) {
1430 int length = js_obj->GetInternalFieldCount();
1431 for (int i = 0; i < length; ++i) {
1432 Object* o = js_obj->GetInternalField(i);
1433 SetInternalReference(
1434 js_obj, entry, i, o, js_obj->GetInternalFieldOffset(i));
1435 }
1436}
1437
1438
1439String* V8HeapExplorer::GetConstructorName(JSObject* object) {
1440 Heap* heap = object->GetHeap();
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001441 if (object->IsJSFunction()) return heap->closure_string();
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001442 String* constructor_name = object->constructor_name();
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001443 if (constructor_name == heap->Object_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001444 // Look up an immediate "constructor" property, if it is a function,
1445 // return its name. This is for instances of binding objects, which
1446 // have prototype constructor type "Object".
1447 Object* constructor_prop = NULL;
1448 LookupResult result(heap->isolate());
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001449 object->LocalLookupRealNamedProperty(heap->constructor_string(), &result);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001450 if (!result.IsFound()) return object->constructor_name();
1451
1452 constructor_prop = result.GetLazyValue();
1453 if (constructor_prop->IsJSFunction()) {
1454 Object* maybe_name =
1455 JSFunction::cast(constructor_prop)->shared()->name();
1456 if (maybe_name->IsString()) {
1457 String* name = String::cast(maybe_name);
1458 if (name->length() > 0) return name;
1459 }
1460 }
1461 }
1462 return object->constructor_name();
1463}
1464
1465
1466HeapEntry* V8HeapExplorer::GetEntry(Object* obj) {
1467 if (!obj->IsHeapObject()) return NULL;
1468 return filler_->FindOrAddEntry(obj, this);
1469}
1470
1471
1472class RootsReferencesExtractor : public ObjectVisitor {
1473 private:
1474 struct IndexTag {
1475 IndexTag(int index, VisitorSynchronization::SyncTag tag)
1476 : index(index), tag(tag) { }
1477 int index;
1478 VisitorSynchronization::SyncTag tag;
1479 };
1480
1481 public:
1482 RootsReferencesExtractor()
1483 : collecting_all_references_(false),
1484 previous_reference_count_(0) {
1485 }
1486
1487 void VisitPointers(Object** start, Object** end) {
1488 if (collecting_all_references_) {
1489 for (Object** p = start; p < end; p++) all_references_.Add(*p);
1490 } else {
1491 for (Object** p = start; p < end; p++) strong_references_.Add(*p);
1492 }
1493 }
1494
1495 void SetCollectingAllReferences() { collecting_all_references_ = true; }
1496
1497 void FillReferences(V8HeapExplorer* explorer) {
1498 ASSERT(strong_references_.length() <= all_references_.length());
1499 for (int i = 0; i < reference_tags_.length(); ++i) {
1500 explorer->SetGcRootsReference(reference_tags_[i].tag);
1501 }
1502 int strong_index = 0, all_index = 0, tags_index = 0;
1503 while (all_index < all_references_.length()) {
1504 if (strong_index < strong_references_.length() &&
1505 strong_references_[strong_index] == all_references_[all_index]) {
1506 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1507 false,
1508 all_references_[all_index++]);
1509 ++strong_index;
1510 } else {
1511 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1512 true,
1513 all_references_[all_index++]);
1514 }
1515 if (reference_tags_[tags_index].index == all_index) ++tags_index;
1516 }
1517 }
1518
1519 void Synchronize(VisitorSynchronization::SyncTag tag) {
1520 if (collecting_all_references_ &&
1521 previous_reference_count_ != all_references_.length()) {
1522 previous_reference_count_ = all_references_.length();
1523 reference_tags_.Add(IndexTag(previous_reference_count_, tag));
1524 }
1525 }
1526
1527 private:
1528 bool collecting_all_references_;
1529 List<Object*> strong_references_;
1530 List<Object*> all_references_;
1531 int previous_reference_count_;
1532 List<IndexTag> reference_tags_;
1533};
1534
1535
1536bool V8HeapExplorer::IterateAndExtractReferences(
1537 SnapshotFillerInterface* filler) {
1538 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
1539
1540 filler_ = filler;
1541 bool interrupted = false;
1542
1543 // Heap iteration with filtering must be finished in any case.
1544 for (HeapObject* obj = iterator.next();
1545 obj != NULL;
1546 obj = iterator.next(), progress_->ProgressStep()) {
1547 if (!interrupted) {
1548 ExtractReferences(obj);
1549 if (!progress_->ProgressReport(false)) interrupted = true;
1550 }
1551 }
1552 if (interrupted) {
1553 filler_ = NULL;
1554 return false;
1555 }
1556
1557 SetRootGcRootsReference();
1558 RootsReferencesExtractor extractor;
1559 heap_->IterateRoots(&extractor, VISIT_ONLY_STRONG);
1560 extractor.SetCollectingAllReferences();
1561 heap_->IterateRoots(&extractor, VISIT_ALL);
1562 extractor.FillReferences(this);
1563 filler_ = NULL;
1564 return progress_->ProgressReport(true);
1565}
1566
1567
1568bool V8HeapExplorer::IsEssentialObject(Object* object) {
1569 return object->IsHeapObject()
1570 && !object->IsOddball()
1571 && object != heap_->empty_byte_array()
1572 && object != heap_->empty_fixed_array()
1573 && object != heap_->empty_descriptor_array()
1574 && object != heap_->fixed_array_map()
1575 && object != heap_->global_property_cell_map()
1576 && object != heap_->shared_function_info_map()
1577 && object != heap_->free_space_map()
1578 && object != heap_->one_pointer_filler_map()
1579 && object != heap_->two_pointer_filler_map();
1580}
1581
1582
1583void V8HeapExplorer::SetClosureReference(HeapObject* parent_obj,
1584 int parent_entry,
1585 String* reference_name,
1586 Object* child_obj) {
1587 HeapEntry* child_entry = GetEntry(child_obj);
1588 if (child_entry != NULL) {
1589 filler_->SetNamedReference(HeapGraphEdge::kContextVariable,
1590 parent_entry,
1591 collection_->names()->GetName(reference_name),
1592 child_entry);
1593 }
1594}
1595
1596
1597void V8HeapExplorer::SetNativeBindReference(HeapObject* parent_obj,
1598 int parent_entry,
1599 const char* reference_name,
1600 Object* child_obj) {
1601 HeapEntry* child_entry = GetEntry(child_obj);
1602 if (child_entry != NULL) {
1603 filler_->SetNamedReference(HeapGraphEdge::kShortcut,
1604 parent_entry,
1605 reference_name,
1606 child_entry);
1607 }
1608}
1609
1610
1611void V8HeapExplorer::SetElementReference(HeapObject* parent_obj,
1612 int parent_entry,
1613 int index,
1614 Object* child_obj) {
1615 HeapEntry* child_entry = GetEntry(child_obj);
1616 if (child_entry != NULL) {
1617 filler_->SetIndexedReference(HeapGraphEdge::kElement,
1618 parent_entry,
1619 index,
1620 child_entry);
1621 }
1622}
1623
1624
1625void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1626 int parent_entry,
1627 const char* reference_name,
1628 Object* child_obj,
1629 int field_offset) {
1630 HeapEntry* child_entry = GetEntry(child_obj);
1631 if (child_entry == NULL) return;
1632 if (IsEssentialObject(child_obj)) {
1633 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1634 parent_entry,
1635 reference_name,
1636 child_entry);
1637 }
1638 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1639}
1640
1641
1642void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1643 int parent_entry,
1644 int index,
1645 Object* child_obj,
1646 int field_offset) {
1647 HeapEntry* child_entry = GetEntry(child_obj);
1648 if (child_entry == NULL) return;
1649 if (IsEssentialObject(child_obj)) {
1650 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1651 parent_entry,
1652 collection_->names()->GetName(index),
1653 child_entry);
1654 }
1655 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1656}
1657
1658
1659void V8HeapExplorer::SetHiddenReference(HeapObject* parent_obj,
1660 int parent_entry,
1661 int index,
1662 Object* child_obj) {
1663 HeapEntry* child_entry = GetEntry(child_obj);
1664 if (child_entry != NULL && IsEssentialObject(child_obj)) {
1665 filler_->SetIndexedReference(HeapGraphEdge::kHidden,
1666 parent_entry,
1667 index,
1668 child_entry);
1669 }
1670}
1671
1672
1673void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
1674 int parent_entry,
1675 int index,
1676 Object* child_obj,
1677 int field_offset) {
1678 HeapEntry* child_entry = GetEntry(child_obj);
1679 if (child_entry != NULL) {
1680 filler_->SetIndexedReference(HeapGraphEdge::kWeak,
1681 parent_entry,
1682 index,
1683 child_entry);
1684 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1685 }
1686}
1687
1688
1689void V8HeapExplorer::SetPropertyReference(HeapObject* parent_obj,
1690 int parent_entry,
ulan@chromium.org750145a2013-03-07 15:14:13 +00001691 Name* reference_name,
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001692 Object* child_obj,
1693 const char* name_format_string,
1694 int field_offset) {
1695 HeapEntry* child_entry = GetEntry(child_obj);
1696 if (child_entry != NULL) {
ulan@chromium.org750145a2013-03-07 15:14:13 +00001697 HeapGraphEdge::Type type =
1698 reference_name->IsSymbol() || String::cast(reference_name)->length() > 0
1699 ? HeapGraphEdge::kProperty : HeapGraphEdge::kInternal;
1700 const char* name = name_format_string != NULL && reference_name->IsString()
1701 ? collection_->names()->GetFormatted(
1702 name_format_string,
1703 *String::cast(reference_name)->ToCString(
1704 DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL)) :
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001705 collection_->names()->GetName(reference_name);
1706
1707 filler_->SetNamedReference(type,
1708 parent_entry,
1709 name,
1710 child_entry);
1711 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1712 }
1713}
1714
1715
1716void V8HeapExplorer::SetRootGcRootsReference() {
1717 filler_->SetIndexedAutoIndexReference(
1718 HeapGraphEdge::kElement,
1719 snapshot_->root()->index(),
1720 snapshot_->gc_roots());
1721}
1722
1723
1724void V8HeapExplorer::SetUserGlobalReference(Object* child_obj) {
1725 HeapEntry* child_entry = GetEntry(child_obj);
1726 ASSERT(child_entry != NULL);
1727 filler_->SetNamedAutoIndexReference(
1728 HeapGraphEdge::kShortcut,
1729 snapshot_->root()->index(),
1730 child_entry);
1731}
1732
1733
1734void V8HeapExplorer::SetGcRootsReference(VisitorSynchronization::SyncTag tag) {
1735 filler_->SetIndexedAutoIndexReference(
1736 HeapGraphEdge::kElement,
1737 snapshot_->gc_roots()->index(),
1738 snapshot_->gc_subroot(tag));
1739}
1740
1741
1742void V8HeapExplorer::SetGcSubrootReference(
1743 VisitorSynchronization::SyncTag tag, bool is_weak, Object* child_obj) {
1744 HeapEntry* child_entry = GetEntry(child_obj);
1745 if (child_entry != NULL) {
1746 const char* name = GetStrongGcSubrootName(child_obj);
1747 if (name != NULL) {
1748 filler_->SetNamedReference(
1749 HeapGraphEdge::kInternal,
1750 snapshot_->gc_subroot(tag)->index(),
1751 name,
1752 child_entry);
1753 } else {
1754 filler_->SetIndexedAutoIndexReference(
1755 is_weak ? HeapGraphEdge::kWeak : HeapGraphEdge::kElement,
1756 snapshot_->gc_subroot(tag)->index(),
1757 child_entry);
1758 }
1759 }
1760}
1761
1762
1763const char* V8HeapExplorer::GetStrongGcSubrootName(Object* object) {
1764 if (strong_gc_subroot_names_.is_empty()) {
1765#define NAME_ENTRY(name) strong_gc_subroot_names_.SetTag(heap_->name(), #name);
1766#define ROOT_NAME(type, name, camel_name) NAME_ENTRY(name)
1767 STRONG_ROOT_LIST(ROOT_NAME)
1768#undef ROOT_NAME
1769#define STRUCT_MAP_NAME(NAME, Name, name) NAME_ENTRY(name##_map)
1770 STRUCT_LIST(STRUCT_MAP_NAME)
1771#undef STRUCT_MAP_NAME
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001772#define STRING_NAME(name, str) NAME_ENTRY(name)
1773 INTERNALIZED_STRING_LIST(STRING_NAME)
1774#undef STRING_NAME
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001775#undef NAME_ENTRY
1776 CHECK(!strong_gc_subroot_names_.is_empty());
1777 }
1778 return strong_gc_subroot_names_.GetTag(object);
1779}
1780
1781
1782void V8HeapExplorer::TagObject(Object* obj, const char* tag) {
1783 if (IsEssentialObject(obj)) {
1784 HeapEntry* entry = GetEntry(obj);
1785 if (entry->name()[0] == '\0') {
1786 entry->set_name(tag);
1787 }
1788 }
1789}
1790
1791
1792class GlobalObjectsEnumerator : public ObjectVisitor {
1793 public:
1794 virtual void VisitPointers(Object** start, Object** end) {
1795 for (Object** p = start; p < end; p++) {
1796 if ((*p)->IsNativeContext()) {
1797 Context* context = Context::cast(*p);
1798 JSObject* proxy = context->global_proxy();
1799 if (proxy->IsJSGlobalProxy()) {
1800 Object* global = proxy->map()->prototype();
1801 if (global->IsJSGlobalObject()) {
1802 objects_.Add(Handle<JSGlobalObject>(JSGlobalObject::cast(global)));
1803 }
1804 }
1805 }
1806 }
1807 }
1808 int count() { return objects_.length(); }
1809 Handle<JSGlobalObject>& at(int i) { return objects_[i]; }
1810
1811 private:
1812 List<Handle<JSGlobalObject> > objects_;
1813};
1814
1815
1816// Modifies heap. Must not be run during heap traversal.
1817void V8HeapExplorer::TagGlobalObjects() {
1818 Isolate* isolate = Isolate::Current();
1819 HandleScope scope(isolate);
1820 GlobalObjectsEnumerator enumerator;
1821 isolate->global_handles()->IterateAllRoots(&enumerator);
1822 const char** urls = NewArray<const char*>(enumerator.count());
1823 for (int i = 0, l = enumerator.count(); i < l; ++i) {
1824 if (global_object_name_resolver_) {
1825 HandleScope scope(isolate);
1826 Handle<JSGlobalObject> global_obj = enumerator.at(i);
1827 urls[i] = global_object_name_resolver_->GetName(
1828 Utils::ToLocal(Handle<JSObject>::cast(global_obj)));
1829 } else {
1830 urls[i] = NULL;
1831 }
1832 }
1833
1834 AssertNoAllocation no_allocation;
1835 for (int i = 0, l = enumerator.count(); i < l; ++i) {
1836 objects_tags_.SetTag(*enumerator.at(i), urls[i]);
1837 }
1838
1839 DeleteArray(urls);
1840}
1841
1842
1843class GlobalHandlesExtractor : public ObjectVisitor {
1844 public:
1845 explicit GlobalHandlesExtractor(NativeObjectsExplorer* explorer)
1846 : explorer_(explorer) {}
1847 virtual ~GlobalHandlesExtractor() {}
1848 virtual void VisitPointers(Object** start, Object** end) {
1849 UNREACHABLE();
1850 }
1851 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {
1852 explorer_->VisitSubtreeWrapper(p, class_id);
1853 }
1854 private:
1855 NativeObjectsExplorer* explorer_;
1856};
1857
1858
1859class BasicHeapEntriesAllocator : public HeapEntriesAllocator {
1860 public:
1861 BasicHeapEntriesAllocator(
1862 HeapSnapshot* snapshot,
1863 HeapEntry::Type entries_type)
1864 : snapshot_(snapshot),
1865 collection_(snapshot_->collection()),
1866 entries_type_(entries_type) {
1867 }
1868 virtual HeapEntry* AllocateEntry(HeapThing ptr);
1869 private:
1870 HeapSnapshot* snapshot_;
1871 HeapSnapshotsCollection* collection_;
1872 HeapEntry::Type entries_type_;
1873};
1874
1875
1876HeapEntry* BasicHeapEntriesAllocator::AllocateEntry(HeapThing ptr) {
1877 v8::RetainedObjectInfo* info = reinterpret_cast<v8::RetainedObjectInfo*>(ptr);
1878 intptr_t elements = info->GetElementCount();
1879 intptr_t size = info->GetSizeInBytes();
1880 const char* name = elements != -1
1881 ? collection_->names()->GetFormatted(
1882 "%s / %" V8_PTR_PREFIX "d entries", info->GetLabel(), elements)
1883 : collection_->names()->GetCopy(info->GetLabel());
1884 return snapshot_->AddEntry(
1885 entries_type_,
1886 name,
1887 HeapObjectsMap::GenerateId(info),
1888 size != -1 ? static_cast<int>(size) : 0);
1889}
1890
1891
1892NativeObjectsExplorer::NativeObjectsExplorer(
1893 HeapSnapshot* snapshot, SnapshottingProgressReportingInterface* progress)
1894 : snapshot_(snapshot),
1895 collection_(snapshot_->collection()),
1896 progress_(progress),
1897 embedder_queried_(false),
1898 objects_by_info_(RetainedInfosMatch),
1899 native_groups_(StringsMatch),
1900 filler_(NULL) {
1901 synthetic_entries_allocator_ =
1902 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kSynthetic);
1903 native_entries_allocator_ =
1904 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kNative);
1905}
1906
1907
1908NativeObjectsExplorer::~NativeObjectsExplorer() {
1909 for (HashMap::Entry* p = objects_by_info_.Start();
1910 p != NULL;
1911 p = objects_by_info_.Next(p)) {
1912 v8::RetainedObjectInfo* info =
1913 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
1914 info->Dispose();
1915 List<HeapObject*>* objects =
1916 reinterpret_cast<List<HeapObject*>* >(p->value);
1917 delete objects;
1918 }
1919 for (HashMap::Entry* p = native_groups_.Start();
1920 p != NULL;
1921 p = native_groups_.Next(p)) {
1922 v8::RetainedObjectInfo* info =
1923 reinterpret_cast<v8::RetainedObjectInfo*>(p->value);
1924 info->Dispose();
1925 }
1926 delete synthetic_entries_allocator_;
1927 delete native_entries_allocator_;
1928}
1929
1930
1931int NativeObjectsExplorer::EstimateObjectsCount() {
1932 FillRetainedObjects();
1933 return objects_by_info_.occupancy();
1934}
1935
1936
1937void NativeObjectsExplorer::FillRetainedObjects() {
1938 if (embedder_queried_) return;
1939 Isolate* isolate = Isolate::Current();
1940 const GCType major_gc_type = kGCTypeMarkSweepCompact;
1941 // Record objects that are joined into ObjectGroups.
1942 isolate->heap()->CallGCPrologueCallbacks(major_gc_type);
1943 List<ObjectGroup*>* groups = isolate->global_handles()->object_groups();
1944 for (int i = 0; i < groups->length(); ++i) {
1945 ObjectGroup* group = groups->at(i);
1946 if (group->info_ == NULL) continue;
1947 List<HeapObject*>* list = GetListMaybeDisposeInfo(group->info_);
1948 for (size_t j = 0; j < group->length_; ++j) {
1949 HeapObject* obj = HeapObject::cast(*group->objects_[j]);
1950 list->Add(obj);
1951 in_groups_.Insert(obj);
1952 }
1953 group->info_ = NULL; // Acquire info object ownership.
1954 }
1955 isolate->global_handles()->RemoveObjectGroups();
1956 isolate->heap()->CallGCEpilogueCallbacks(major_gc_type);
1957 // Record objects that are not in ObjectGroups, but have class ID.
1958 GlobalHandlesExtractor extractor(this);
1959 isolate->global_handles()->IterateAllRootsWithClassIds(&extractor);
1960 embedder_queried_ = true;
1961}
1962
1963void NativeObjectsExplorer::FillImplicitReferences() {
1964 Isolate* isolate = Isolate::Current();
1965 List<ImplicitRefGroup*>* groups =
1966 isolate->global_handles()->implicit_ref_groups();
1967 for (int i = 0; i < groups->length(); ++i) {
1968 ImplicitRefGroup* group = groups->at(i);
1969 HeapObject* parent = *group->parent_;
1970 int parent_entry =
1971 filler_->FindOrAddEntry(parent, native_entries_allocator_)->index();
1972 ASSERT(parent_entry != HeapEntry::kNoEntry);
1973 Object*** children = group->children_;
1974 for (size_t j = 0; j < group->length_; ++j) {
1975 Object* child = *children[j];
1976 HeapEntry* child_entry =
1977 filler_->FindOrAddEntry(child, native_entries_allocator_);
1978 filler_->SetNamedReference(
1979 HeapGraphEdge::kInternal,
1980 parent_entry,
1981 "native",
1982 child_entry);
1983 }
1984 }
1985 isolate->global_handles()->RemoveImplicitRefGroups();
1986}
1987
1988List<HeapObject*>* NativeObjectsExplorer::GetListMaybeDisposeInfo(
1989 v8::RetainedObjectInfo* info) {
1990 HashMap::Entry* entry =
1991 objects_by_info_.Lookup(info, InfoHash(info), true);
1992 if (entry->value != NULL) {
1993 info->Dispose();
1994 } else {
1995 entry->value = new List<HeapObject*>(4);
1996 }
1997 return reinterpret_cast<List<HeapObject*>* >(entry->value);
1998}
1999
2000
2001bool NativeObjectsExplorer::IterateAndExtractReferences(
2002 SnapshotFillerInterface* filler) {
2003 filler_ = filler;
2004 FillRetainedObjects();
2005 FillImplicitReferences();
2006 if (EstimateObjectsCount() > 0) {
2007 for (HashMap::Entry* p = objects_by_info_.Start();
2008 p != NULL;
2009 p = objects_by_info_.Next(p)) {
2010 v8::RetainedObjectInfo* info =
2011 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2012 SetNativeRootReference(info);
2013 List<HeapObject*>* objects =
2014 reinterpret_cast<List<HeapObject*>* >(p->value);
2015 for (int i = 0; i < objects->length(); ++i) {
2016 SetWrapperNativeReferences(objects->at(i), info);
2017 }
2018 }
2019 SetRootNativeRootsReference();
2020 }
2021 filler_ = NULL;
2022 return true;
2023}
2024
2025
2026class NativeGroupRetainedObjectInfo : public v8::RetainedObjectInfo {
2027 public:
2028 explicit NativeGroupRetainedObjectInfo(const char* label)
2029 : disposed_(false),
2030 hash_(reinterpret_cast<intptr_t>(label)),
2031 label_(label) {
2032 }
2033
2034 virtual ~NativeGroupRetainedObjectInfo() {}
2035 virtual void Dispose() {
2036 CHECK(!disposed_);
2037 disposed_ = true;
2038 delete this;
2039 }
2040 virtual bool IsEquivalent(RetainedObjectInfo* other) {
2041 return hash_ == other->GetHash() && !strcmp(label_, other->GetLabel());
2042 }
2043 virtual intptr_t GetHash() { return hash_; }
2044 virtual const char* GetLabel() { return label_; }
2045
2046 private:
2047 bool disposed_;
2048 intptr_t hash_;
2049 const char* label_;
2050};
2051
2052
2053NativeGroupRetainedObjectInfo* NativeObjectsExplorer::FindOrAddGroupInfo(
2054 const char* label) {
2055 const char* label_copy = collection_->names()->GetCopy(label);
2056 uint32_t hash = StringHasher::HashSequentialString(
2057 label_copy,
2058 static_cast<int>(strlen(label_copy)),
2059 HEAP->HashSeed());
2060 HashMap::Entry* entry = native_groups_.Lookup(const_cast<char*>(label_copy),
2061 hash, true);
2062 if (entry->value == NULL) {
2063 entry->value = new NativeGroupRetainedObjectInfo(label);
2064 }
2065 return static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2066}
2067
2068
2069void NativeObjectsExplorer::SetNativeRootReference(
2070 v8::RetainedObjectInfo* info) {
2071 HeapEntry* child_entry =
2072 filler_->FindOrAddEntry(info, native_entries_allocator_);
2073 ASSERT(child_entry != NULL);
2074 NativeGroupRetainedObjectInfo* group_info =
2075 FindOrAddGroupInfo(info->GetGroupLabel());
2076 HeapEntry* group_entry =
2077 filler_->FindOrAddEntry(group_info, synthetic_entries_allocator_);
2078 filler_->SetNamedAutoIndexReference(
2079 HeapGraphEdge::kInternal,
2080 group_entry->index(),
2081 child_entry);
2082}
2083
2084
2085void NativeObjectsExplorer::SetWrapperNativeReferences(
2086 HeapObject* wrapper, v8::RetainedObjectInfo* info) {
2087 HeapEntry* wrapper_entry = filler_->FindEntry(wrapper);
2088 ASSERT(wrapper_entry != NULL);
2089 HeapEntry* info_entry =
2090 filler_->FindOrAddEntry(info, native_entries_allocator_);
2091 ASSERT(info_entry != NULL);
2092 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2093 wrapper_entry->index(),
2094 "native",
2095 info_entry);
2096 filler_->SetIndexedAutoIndexReference(HeapGraphEdge::kElement,
2097 info_entry->index(),
2098 wrapper_entry);
2099}
2100
2101
2102void NativeObjectsExplorer::SetRootNativeRootsReference() {
2103 for (HashMap::Entry* entry = native_groups_.Start();
2104 entry;
2105 entry = native_groups_.Next(entry)) {
2106 NativeGroupRetainedObjectInfo* group_info =
2107 static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2108 HeapEntry* group_entry =
2109 filler_->FindOrAddEntry(group_info, native_entries_allocator_);
2110 ASSERT(group_entry != NULL);
2111 filler_->SetIndexedAutoIndexReference(
2112 HeapGraphEdge::kElement,
2113 snapshot_->root()->index(),
2114 group_entry);
2115 }
2116}
2117
2118
2119void NativeObjectsExplorer::VisitSubtreeWrapper(Object** p, uint16_t class_id) {
2120 if (in_groups_.Contains(*p)) return;
2121 Isolate* isolate = Isolate::Current();
2122 v8::RetainedObjectInfo* info =
2123 isolate->heap_profiler()->ExecuteWrapperClassCallback(class_id, p);
2124 if (info == NULL) return;
2125 GetListMaybeDisposeInfo(info)->Add(HeapObject::cast(*p));
2126}
2127
2128
2129class SnapshotFiller : public SnapshotFillerInterface {
2130 public:
2131 explicit SnapshotFiller(HeapSnapshot* snapshot, HeapEntriesMap* entries)
2132 : snapshot_(snapshot),
2133 collection_(snapshot->collection()),
2134 entries_(entries) { }
2135 HeapEntry* AddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
2136 HeapEntry* entry = allocator->AllocateEntry(ptr);
2137 entries_->Pair(ptr, entry->index());
2138 return entry;
2139 }
2140 HeapEntry* FindEntry(HeapThing ptr) {
2141 int index = entries_->Map(ptr);
2142 return index != HeapEntry::kNoEntry ? &snapshot_->entries()[index] : NULL;
2143 }
2144 HeapEntry* FindOrAddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
2145 HeapEntry* entry = FindEntry(ptr);
2146 return entry != NULL ? entry : AddEntry(ptr, allocator);
2147 }
2148 void SetIndexedReference(HeapGraphEdge::Type type,
2149 int parent,
2150 int index,
2151 HeapEntry* child_entry) {
2152 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2153 parent_entry->SetIndexedReference(type, index, child_entry);
2154 }
2155 void SetIndexedAutoIndexReference(HeapGraphEdge::Type type,
2156 int parent,
2157 HeapEntry* child_entry) {
2158 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2159 int index = parent_entry->children_count() + 1;
2160 parent_entry->SetIndexedReference(type, index, child_entry);
2161 }
2162 void SetNamedReference(HeapGraphEdge::Type type,
2163 int parent,
2164 const char* reference_name,
2165 HeapEntry* child_entry) {
2166 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2167 parent_entry->SetNamedReference(type, reference_name, child_entry);
2168 }
2169 void SetNamedAutoIndexReference(HeapGraphEdge::Type type,
2170 int parent,
2171 HeapEntry* child_entry) {
2172 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2173 int index = parent_entry->children_count() + 1;
2174 parent_entry->SetNamedReference(
2175 type,
2176 collection_->names()->GetName(index),
2177 child_entry);
2178 }
2179
2180 private:
2181 HeapSnapshot* snapshot_;
2182 HeapSnapshotsCollection* collection_;
2183 HeapEntriesMap* entries_;
2184};
2185
2186
2187HeapSnapshotGenerator::HeapSnapshotGenerator(
2188 HeapSnapshot* snapshot,
2189 v8::ActivityControl* control,
2190 v8::HeapProfiler::ObjectNameResolver* resolver,
2191 Heap* heap)
2192 : snapshot_(snapshot),
2193 control_(control),
2194 v8_heap_explorer_(snapshot_, this, resolver),
2195 dom_explorer_(snapshot_, this),
2196 heap_(heap) {
2197}
2198
2199
2200bool HeapSnapshotGenerator::GenerateSnapshot() {
2201 v8_heap_explorer_.TagGlobalObjects();
2202
2203 // TODO(1562) Profiler assumes that any object that is in the heap after
2204 // full GC is reachable from the root when computing dominators.
2205 // This is not true for weakly reachable objects.
2206 // As a temporary solution we call GC twice.
2207 Isolate::Current()->heap()->CollectAllGarbage(
2208 Heap::kMakeHeapIterableMask,
2209 "HeapSnapshotGenerator::GenerateSnapshot");
2210 Isolate::Current()->heap()->CollectAllGarbage(
2211 Heap::kMakeHeapIterableMask,
2212 "HeapSnapshotGenerator::GenerateSnapshot");
2213
2214#ifdef VERIFY_HEAP
2215 Heap* debug_heap = Isolate::Current()->heap();
2216 CHECK(!debug_heap->old_data_space()->was_swept_conservatively());
2217 CHECK(!debug_heap->old_pointer_space()->was_swept_conservatively());
2218 CHECK(!debug_heap->code_space()->was_swept_conservatively());
2219 CHECK(!debug_heap->cell_space()->was_swept_conservatively());
2220 CHECK(!debug_heap->map_space()->was_swept_conservatively());
2221#endif
2222
2223 // The following code uses heap iterators, so we want the heap to be
2224 // stable. It should follow TagGlobalObjects as that can allocate.
2225 AssertNoAllocation no_alloc;
2226
2227#ifdef VERIFY_HEAP
2228 debug_heap->Verify();
2229#endif
2230
2231 SetProgressTotal(1); // 1 pass.
2232
2233#ifdef VERIFY_HEAP
2234 debug_heap->Verify();
2235#endif
2236
2237 if (!FillReferences()) return false;
2238
2239 snapshot_->FillChildren();
2240 snapshot_->RememberLastJSObjectId();
2241
2242 progress_counter_ = progress_total_;
2243 if (!ProgressReport(true)) return false;
2244 return true;
2245}
2246
2247
2248void HeapSnapshotGenerator::ProgressStep() {
2249 ++progress_counter_;
2250}
2251
2252
2253bool HeapSnapshotGenerator::ProgressReport(bool force) {
2254 const int kProgressReportGranularity = 10000;
2255 if (control_ != NULL
2256 && (force || progress_counter_ % kProgressReportGranularity == 0)) {
2257 return
2258 control_->ReportProgressValue(progress_counter_, progress_total_) ==
2259 v8::ActivityControl::kContinue;
2260 }
2261 return true;
2262}
2263
2264
2265void HeapSnapshotGenerator::SetProgressTotal(int iterations_count) {
2266 if (control_ == NULL) return;
2267 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
2268 progress_total_ = iterations_count * (
2269 v8_heap_explorer_.EstimateObjectsCount(&iterator) +
2270 dom_explorer_.EstimateObjectsCount());
2271 progress_counter_ = 0;
2272}
2273
2274
2275bool HeapSnapshotGenerator::FillReferences() {
2276 SnapshotFiller filler(snapshot_, &entries_);
2277 v8_heap_explorer_.AddRootEntries(&filler);
2278 return v8_heap_explorer_.IterateAndExtractReferences(&filler)
2279 && dom_explorer_.IterateAndExtractReferences(&filler);
2280}
2281
2282
2283template<int bytes> struct MaxDecimalDigitsIn;
2284template<> struct MaxDecimalDigitsIn<4> {
2285 static const int kSigned = 11;
2286 static const int kUnsigned = 10;
2287};
2288template<> struct MaxDecimalDigitsIn<8> {
2289 static const int kSigned = 20;
2290 static const int kUnsigned = 20;
2291};
2292
2293
2294class OutputStreamWriter {
2295 public:
2296 explicit OutputStreamWriter(v8::OutputStream* stream)
2297 : stream_(stream),
2298 chunk_size_(stream->GetChunkSize()),
2299 chunk_(chunk_size_),
2300 chunk_pos_(0),
2301 aborted_(false) {
2302 ASSERT(chunk_size_ > 0);
2303 }
2304 bool aborted() { return aborted_; }
2305 void AddCharacter(char c) {
2306 ASSERT(c != '\0');
2307 ASSERT(chunk_pos_ < chunk_size_);
2308 chunk_[chunk_pos_++] = c;
2309 MaybeWriteChunk();
2310 }
2311 void AddString(const char* s) {
2312 AddSubstring(s, StrLength(s));
2313 }
2314 void AddSubstring(const char* s, int n) {
2315 if (n <= 0) return;
2316 ASSERT(static_cast<size_t>(n) <= strlen(s));
2317 const char* s_end = s + n;
2318 while (s < s_end) {
2319 int s_chunk_size = Min(
2320 chunk_size_ - chunk_pos_, static_cast<int>(s_end - s));
2321 ASSERT(s_chunk_size > 0);
2322 memcpy(chunk_.start() + chunk_pos_, s, s_chunk_size);
2323 s += s_chunk_size;
2324 chunk_pos_ += s_chunk_size;
2325 MaybeWriteChunk();
2326 }
2327 }
2328 void AddNumber(unsigned n) { AddNumberImpl<unsigned>(n, "%u"); }
2329 void Finalize() {
2330 if (aborted_) return;
2331 ASSERT(chunk_pos_ < chunk_size_);
2332 if (chunk_pos_ != 0) {
2333 WriteChunk();
2334 }
2335 stream_->EndOfStream();
2336 }
2337
2338 private:
2339 template<typename T>
2340 void AddNumberImpl(T n, const char* format) {
2341 // Buffer for the longest value plus trailing \0
2342 static const int kMaxNumberSize =
2343 MaxDecimalDigitsIn<sizeof(T)>::kUnsigned + 1;
2344 if (chunk_size_ - chunk_pos_ >= kMaxNumberSize) {
2345 int result = OS::SNPrintF(
2346 chunk_.SubVector(chunk_pos_, chunk_size_), format, n);
2347 ASSERT(result != -1);
2348 chunk_pos_ += result;
2349 MaybeWriteChunk();
2350 } else {
2351 EmbeddedVector<char, kMaxNumberSize> buffer;
2352 int result = OS::SNPrintF(buffer, format, n);
2353 USE(result);
2354 ASSERT(result != -1);
2355 AddString(buffer.start());
2356 }
2357 }
2358 void MaybeWriteChunk() {
2359 ASSERT(chunk_pos_ <= chunk_size_);
2360 if (chunk_pos_ == chunk_size_) {
2361 WriteChunk();
2362 }
2363 }
2364 void WriteChunk() {
2365 if (aborted_) return;
2366 if (stream_->WriteAsciiChunk(chunk_.start(), chunk_pos_) ==
2367 v8::OutputStream::kAbort) aborted_ = true;
2368 chunk_pos_ = 0;
2369 }
2370
2371 v8::OutputStream* stream_;
2372 int chunk_size_;
2373 ScopedVector<char> chunk_;
2374 int chunk_pos_;
2375 bool aborted_;
2376};
2377
2378
2379// type, name|index, to_node.
2380const int HeapSnapshotJSONSerializer::kEdgeFieldsCount = 3;
2381// type, name, id, self_size, children_index.
2382const int HeapSnapshotJSONSerializer::kNodeFieldsCount = 5;
2383
2384void HeapSnapshotJSONSerializer::Serialize(v8::OutputStream* stream) {
2385 ASSERT(writer_ == NULL);
2386 writer_ = new OutputStreamWriter(stream);
2387
2388 HeapSnapshot* original_snapshot = NULL;
2389 if (snapshot_->RawSnapshotSize() >=
2390 SnapshotSizeConstants<kPointerSize>::kMaxSerializableSnapshotRawSize) {
2391 // The snapshot is too big. Serialize a fake snapshot.
2392 original_snapshot = snapshot_;
2393 snapshot_ = CreateFakeSnapshot();
2394 }
2395
2396 SerializeImpl();
2397
2398 delete writer_;
2399 writer_ = NULL;
2400
2401 if (original_snapshot != NULL) {
2402 delete snapshot_;
2403 snapshot_ = original_snapshot;
2404 }
2405}
2406
2407
2408HeapSnapshot* HeapSnapshotJSONSerializer::CreateFakeSnapshot() {
2409 HeapSnapshot* result = new HeapSnapshot(snapshot_->collection(),
2410 HeapSnapshot::kFull,
2411 snapshot_->title(),
2412 snapshot_->uid());
2413 result->AddRootEntry();
2414 const char* text = snapshot_->collection()->names()->GetFormatted(
2415 "The snapshot is too big. "
2416 "Maximum snapshot size is %" V8_PTR_PREFIX "u MB. "
2417 "Actual snapshot size is %" V8_PTR_PREFIX "u MB.",
2418 SnapshotSizeConstants<kPointerSize>::kMaxSerializableSnapshotRawSize / MB,
2419 (snapshot_->RawSnapshotSize() + MB - 1) / MB);
2420 HeapEntry* message = result->AddEntry(HeapEntry::kString, text, 0, 4);
2421 result->root()->SetIndexedReference(HeapGraphEdge::kElement, 1, message);
2422 result->FillChildren();
2423 return result;
2424}
2425
2426
2427void HeapSnapshotJSONSerializer::SerializeImpl() {
2428 ASSERT(0 == snapshot_->root()->index());
2429 writer_->AddCharacter('{');
2430 writer_->AddString("\"snapshot\":{");
2431 SerializeSnapshot();
2432 if (writer_->aborted()) return;
2433 writer_->AddString("},\n");
2434 writer_->AddString("\"nodes\":[");
2435 SerializeNodes();
2436 if (writer_->aborted()) return;
2437 writer_->AddString("],\n");
2438 writer_->AddString("\"edges\":[");
2439 SerializeEdges();
2440 if (writer_->aborted()) return;
2441 writer_->AddString("],\n");
2442 writer_->AddString("\"strings\":[");
2443 SerializeStrings();
2444 if (writer_->aborted()) return;
2445 writer_->AddCharacter(']');
2446 writer_->AddCharacter('}');
2447 writer_->Finalize();
2448}
2449
2450
2451int HeapSnapshotJSONSerializer::GetStringId(const char* s) {
2452 HashMap::Entry* cache_entry = strings_.Lookup(
2453 const_cast<char*>(s), ObjectHash(s), true);
2454 if (cache_entry->value == NULL) {
2455 cache_entry->value = reinterpret_cast<void*>(next_string_id_++);
2456 }
2457 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2458}
2459
2460
2461static int utoa(unsigned value, const Vector<char>& buffer, int buffer_pos) {
2462 int number_of_digits = 0;
2463 unsigned t = value;
2464 do {
2465 ++number_of_digits;
2466 } while (t /= 10);
2467
2468 buffer_pos += number_of_digits;
2469 int result = buffer_pos;
2470 do {
2471 int last_digit = value % 10;
2472 buffer[--buffer_pos] = '0' + last_digit;
2473 value /= 10;
2474 } while (value);
2475 return result;
2476}
2477
2478
2479void HeapSnapshotJSONSerializer::SerializeEdge(HeapGraphEdge* edge,
2480 bool first_edge) {
2481 // The buffer needs space for 3 unsigned ints, 3 commas, \n and \0
2482 static const int kBufferSize =
2483 MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned * 3 + 3 + 2; // NOLINT
2484 EmbeddedVector<char, kBufferSize> buffer;
2485 int edge_name_or_index = edge->type() == HeapGraphEdge::kElement
2486 || edge->type() == HeapGraphEdge::kHidden
2487 || edge->type() == HeapGraphEdge::kWeak
2488 ? edge->index() : GetStringId(edge->name());
2489 int buffer_pos = 0;
2490 if (!first_edge) {
2491 buffer[buffer_pos++] = ',';
2492 }
2493 buffer_pos = utoa(edge->type(), buffer, buffer_pos);
2494 buffer[buffer_pos++] = ',';
2495 buffer_pos = utoa(edge_name_or_index, buffer, buffer_pos);
2496 buffer[buffer_pos++] = ',';
2497 buffer_pos = utoa(entry_index(edge->to()), buffer, buffer_pos);
2498 buffer[buffer_pos++] = '\n';
2499 buffer[buffer_pos++] = '\0';
2500 writer_->AddString(buffer.start());
2501}
2502
2503
2504void HeapSnapshotJSONSerializer::SerializeEdges() {
2505 List<HeapGraphEdge*>& edges = snapshot_->children();
2506 for (int i = 0; i < edges.length(); ++i) {
2507 ASSERT(i == 0 ||
2508 edges[i - 1]->from()->index() <= edges[i]->from()->index());
2509 SerializeEdge(edges[i], i == 0);
2510 if (writer_->aborted()) return;
2511 }
2512}
2513
2514
2515void HeapSnapshotJSONSerializer::SerializeNode(HeapEntry* entry) {
2516 // The buffer needs space for 5 unsigned ints, 5 commas, \n and \0
2517 static const int kBufferSize =
2518 5 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2519 + 5 + 1 + 1;
2520 EmbeddedVector<char, kBufferSize> buffer;
2521 int buffer_pos = 0;
2522 if (entry_index(entry) != 0) {
2523 buffer[buffer_pos++] = ',';
2524 }
2525 buffer_pos = utoa(entry->type(), buffer, buffer_pos);
2526 buffer[buffer_pos++] = ',';
2527 buffer_pos = utoa(GetStringId(entry->name()), buffer, buffer_pos);
2528 buffer[buffer_pos++] = ',';
2529 buffer_pos = utoa(entry->id(), buffer, buffer_pos);
2530 buffer[buffer_pos++] = ',';
2531 buffer_pos = utoa(entry->self_size(), buffer, buffer_pos);
2532 buffer[buffer_pos++] = ',';
2533 buffer_pos = utoa(entry->children_count(), buffer, buffer_pos);
2534 buffer[buffer_pos++] = '\n';
2535 buffer[buffer_pos++] = '\0';
2536 writer_->AddString(buffer.start());
2537}
2538
2539
2540void HeapSnapshotJSONSerializer::SerializeNodes() {
2541 List<HeapEntry>& entries = snapshot_->entries();
2542 for (int i = 0; i < entries.length(); ++i) {
2543 SerializeNode(&entries[i]);
2544 if (writer_->aborted()) return;
2545 }
2546}
2547
2548
2549void HeapSnapshotJSONSerializer::SerializeSnapshot() {
2550 writer_->AddString("\"title\":\"");
2551 writer_->AddString(snapshot_->title());
2552 writer_->AddString("\"");
2553 writer_->AddString(",\"uid\":");
2554 writer_->AddNumber(snapshot_->uid());
2555 writer_->AddString(",\"meta\":");
2556 // The object describing node serialization layout.
2557 // We use a set of macros to improve readability.
2558#define JSON_A(s) "[" s "]"
2559#define JSON_O(s) "{" s "}"
2560#define JSON_S(s) "\"" s "\""
2561 writer_->AddString(JSON_O(
2562 JSON_S("node_fields") ":" JSON_A(
2563 JSON_S("type") ","
2564 JSON_S("name") ","
2565 JSON_S("id") ","
2566 JSON_S("self_size") ","
2567 JSON_S("edge_count")) ","
2568 JSON_S("node_types") ":" JSON_A(
2569 JSON_A(
2570 JSON_S("hidden") ","
2571 JSON_S("array") ","
2572 JSON_S("string") ","
2573 JSON_S("object") ","
2574 JSON_S("code") ","
2575 JSON_S("closure") ","
2576 JSON_S("regexp") ","
2577 JSON_S("number") ","
2578 JSON_S("native") ","
2579 JSON_S("synthetic")) ","
2580 JSON_S("string") ","
2581 JSON_S("number") ","
2582 JSON_S("number") ","
2583 JSON_S("number") ","
2584 JSON_S("number") ","
2585 JSON_S("number")) ","
2586 JSON_S("edge_fields") ":" JSON_A(
2587 JSON_S("type") ","
2588 JSON_S("name_or_index") ","
2589 JSON_S("to_node")) ","
2590 JSON_S("edge_types") ":" JSON_A(
2591 JSON_A(
2592 JSON_S("context") ","
2593 JSON_S("element") ","
2594 JSON_S("property") ","
2595 JSON_S("internal") ","
2596 JSON_S("hidden") ","
2597 JSON_S("shortcut") ","
2598 JSON_S("weak")) ","
2599 JSON_S("string_or_number") ","
2600 JSON_S("node"))));
2601#undef JSON_S
2602#undef JSON_O
2603#undef JSON_A
2604 writer_->AddString(",\"node_count\":");
2605 writer_->AddNumber(snapshot_->entries().length());
2606 writer_->AddString(",\"edge_count\":");
2607 writer_->AddNumber(snapshot_->edges().length());
2608}
2609
2610
2611static void WriteUChar(OutputStreamWriter* w, unibrow::uchar u) {
2612 static const char hex_chars[] = "0123456789ABCDEF";
2613 w->AddString("\\u");
2614 w->AddCharacter(hex_chars[(u >> 12) & 0xf]);
2615 w->AddCharacter(hex_chars[(u >> 8) & 0xf]);
2616 w->AddCharacter(hex_chars[(u >> 4) & 0xf]);
2617 w->AddCharacter(hex_chars[u & 0xf]);
2618}
2619
2620void HeapSnapshotJSONSerializer::SerializeString(const unsigned char* s) {
2621 writer_->AddCharacter('\n');
2622 writer_->AddCharacter('\"');
2623 for ( ; *s != '\0'; ++s) {
2624 switch (*s) {
2625 case '\b':
2626 writer_->AddString("\\b");
2627 continue;
2628 case '\f':
2629 writer_->AddString("\\f");
2630 continue;
2631 case '\n':
2632 writer_->AddString("\\n");
2633 continue;
2634 case '\r':
2635 writer_->AddString("\\r");
2636 continue;
2637 case '\t':
2638 writer_->AddString("\\t");
2639 continue;
2640 case '\"':
2641 case '\\':
2642 writer_->AddCharacter('\\');
2643 writer_->AddCharacter(*s);
2644 continue;
2645 default:
2646 if (*s > 31 && *s < 128) {
2647 writer_->AddCharacter(*s);
2648 } else if (*s <= 31) {
2649 // Special character with no dedicated literal.
2650 WriteUChar(writer_, *s);
2651 } else {
2652 // Convert UTF-8 into \u UTF-16 literal.
2653 unsigned length = 1, cursor = 0;
2654 for ( ; length <= 4 && *(s + length) != '\0'; ++length) { }
2655 unibrow::uchar c = unibrow::Utf8::CalculateValue(s, length, &cursor);
2656 if (c != unibrow::Utf8::kBadChar) {
2657 WriteUChar(writer_, c);
2658 ASSERT(cursor != 0);
2659 s += cursor - 1;
2660 } else {
2661 writer_->AddCharacter('?');
2662 }
2663 }
2664 }
2665 }
2666 writer_->AddCharacter('\"');
2667}
2668
2669
2670void HeapSnapshotJSONSerializer::SerializeStrings() {
2671 List<HashMap::Entry*> sorted_strings;
2672 SortHashMap(&strings_, &sorted_strings);
2673 writer_->AddString("\"<dummy>\"");
2674 for (int i = 0; i < sorted_strings.length(); ++i) {
2675 writer_->AddCharacter(',');
2676 SerializeString(
2677 reinterpret_cast<const unsigned char*>(sorted_strings[i]->key));
2678 if (writer_->aborted()) return;
2679 }
2680}
2681
2682
2683template<typename T>
2684inline static int SortUsingEntryValue(const T* x, const T* y) {
2685 uintptr_t x_uint = reinterpret_cast<uintptr_t>((*x)->value);
2686 uintptr_t y_uint = reinterpret_cast<uintptr_t>((*y)->value);
2687 if (x_uint > y_uint) {
2688 return 1;
2689 } else if (x_uint == y_uint) {
2690 return 0;
2691 } else {
2692 return -1;
2693 }
2694}
2695
2696
2697void HeapSnapshotJSONSerializer::SortHashMap(
2698 HashMap* map, List<HashMap::Entry*>* sorted_entries) {
2699 for (HashMap::Entry* p = map->Start(); p != NULL; p = map->Next(p))
2700 sorted_entries->Add(p);
2701 sorted_entries->Sort(SortUsingEntryValue);
2702}
2703
2704} } // namespace v8::internal