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