blob: f488304f43b3dda9889ad438bc3ddaf953acf14e [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();
ulan@chromium.org57ff8812013-05-10 08:16:55 +00001312 for (int i = 0; i < real_size; i++) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001313 switch (descs->GetType(i)) {
1314 case FIELD: {
1315 int index = descs->GetFieldIndex(i);
1316
ulan@chromium.org750145a2013-03-07 15:14:13 +00001317 Name* k = descs->GetKey(i);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001318 if (index < js_obj->map()->inobject_properties()) {
1319 Object* value = js_obj->InObjectPropertyAt(index);
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001320 if (k != heap_->hidden_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001321 SetPropertyReference(
1322 js_obj, entry,
1323 k, value,
1324 NULL,
1325 js_obj->GetInObjectPropertyOffset(index));
1326 } else {
1327 TagObject(value, "(hidden properties)");
1328 SetInternalReference(
1329 js_obj, entry,
1330 "hidden_properties", value,
1331 js_obj->GetInObjectPropertyOffset(index));
1332 }
1333 } else {
ulan@chromium.org57ff8812013-05-10 08:16:55 +00001334 Object* value = js_obj->RawFastPropertyAt(index);
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001335 if (k != heap_->hidden_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001336 SetPropertyReference(js_obj, entry, k, value);
1337 } else {
1338 TagObject(value, "(hidden properties)");
1339 SetInternalReference(js_obj, entry, "hidden_properties", value);
1340 }
1341 }
1342 break;
1343 }
1344 case CONSTANT_FUNCTION:
1345 SetPropertyReference(
1346 js_obj, entry,
1347 descs->GetKey(i), descs->GetConstantFunction(i));
1348 break;
1349 case CALLBACKS: {
1350 Object* callback_obj = descs->GetValue(i);
1351 if (callback_obj->IsAccessorPair()) {
1352 AccessorPair* accessors = AccessorPair::cast(callback_obj);
1353 if (Object* getter = accessors->getter()) {
1354 SetPropertyReference(js_obj, entry, descs->GetKey(i),
1355 getter, "get-%s");
1356 }
1357 if (Object* setter = accessors->setter()) {
1358 SetPropertyReference(js_obj, entry, descs->GetKey(i),
1359 setter, "set-%s");
1360 }
1361 }
1362 break;
1363 }
1364 case NORMAL: // only in slow mode
1365 case HANDLER: // only in lookup results, not in descriptors
1366 case INTERCEPTOR: // only in lookup results, not in descriptors
1367 break;
1368 case TRANSITION:
1369 case NONEXISTENT:
1370 UNREACHABLE();
1371 break;
1372 }
1373 }
1374 } else {
ulan@chromium.org750145a2013-03-07 15:14:13 +00001375 NameDictionary* dictionary = js_obj->property_dictionary();
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001376 int length = dictionary->Capacity();
1377 for (int i = 0; i < length; ++i) {
1378 Object* k = dictionary->KeyAt(i);
1379 if (dictionary->IsKey(k)) {
1380 Object* target = dictionary->ValueAt(i);
1381 // We assume that global objects can only have slow properties.
1382 Object* value = target->IsJSGlobalPropertyCell()
1383 ? JSGlobalPropertyCell::cast(target)->value()
1384 : target;
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001385 if (k != heap_->hidden_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001386 SetPropertyReference(js_obj, entry, String::cast(k), value);
1387 } else {
1388 TagObject(value, "(hidden properties)");
1389 SetInternalReference(js_obj, entry, "hidden_properties", value);
1390 }
1391 }
1392 }
1393 }
1394}
1395
1396
1397void V8HeapExplorer::ExtractElementReferences(JSObject* js_obj, int entry) {
1398 if (js_obj->HasFastObjectElements()) {
1399 FixedArray* elements = FixedArray::cast(js_obj->elements());
1400 int length = js_obj->IsJSArray() ?
1401 Smi::cast(JSArray::cast(js_obj)->length())->value() :
1402 elements->length();
1403 for (int i = 0; i < length; ++i) {
1404 if (!elements->get(i)->IsTheHole()) {
1405 SetElementReference(js_obj, entry, i, elements->get(i));
1406 }
1407 }
1408 } else if (js_obj->HasDictionaryElements()) {
1409 SeededNumberDictionary* dictionary = js_obj->element_dictionary();
1410 int length = dictionary->Capacity();
1411 for (int i = 0; i < length; ++i) {
1412 Object* k = dictionary->KeyAt(i);
1413 if (dictionary->IsKey(k)) {
1414 ASSERT(k->IsNumber());
1415 uint32_t index = static_cast<uint32_t>(k->Number());
1416 SetElementReference(js_obj, entry, index, dictionary->ValueAt(i));
1417 }
1418 }
1419 }
1420}
1421
1422
1423void V8HeapExplorer::ExtractInternalReferences(JSObject* js_obj, int entry) {
1424 int length = js_obj->GetInternalFieldCount();
1425 for (int i = 0; i < length; ++i) {
1426 Object* o = js_obj->GetInternalField(i);
1427 SetInternalReference(
1428 js_obj, entry, i, o, js_obj->GetInternalFieldOffset(i));
1429 }
1430}
1431
1432
1433String* V8HeapExplorer::GetConstructorName(JSObject* object) {
1434 Heap* heap = object->GetHeap();
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001435 if (object->IsJSFunction()) return heap->closure_string();
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001436 String* constructor_name = object->constructor_name();
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001437 if (constructor_name == heap->Object_string()) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001438 // Look up an immediate "constructor" property, if it is a function,
1439 // return its name. This is for instances of binding objects, which
1440 // have prototype constructor type "Object".
1441 Object* constructor_prop = NULL;
1442 LookupResult result(heap->isolate());
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001443 object->LocalLookupRealNamedProperty(heap->constructor_string(), &result);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001444 if (!result.IsFound()) return object->constructor_name();
1445
1446 constructor_prop = result.GetLazyValue();
1447 if (constructor_prop->IsJSFunction()) {
1448 Object* maybe_name =
1449 JSFunction::cast(constructor_prop)->shared()->name();
1450 if (maybe_name->IsString()) {
1451 String* name = String::cast(maybe_name);
1452 if (name->length() > 0) return name;
1453 }
1454 }
1455 }
1456 return object->constructor_name();
1457}
1458
1459
1460HeapEntry* V8HeapExplorer::GetEntry(Object* obj) {
1461 if (!obj->IsHeapObject()) return NULL;
1462 return filler_->FindOrAddEntry(obj, this);
1463}
1464
1465
1466class RootsReferencesExtractor : public ObjectVisitor {
1467 private:
1468 struct IndexTag {
1469 IndexTag(int index, VisitorSynchronization::SyncTag tag)
1470 : index(index), tag(tag) { }
1471 int index;
1472 VisitorSynchronization::SyncTag tag;
1473 };
1474
1475 public:
1476 RootsReferencesExtractor()
1477 : collecting_all_references_(false),
1478 previous_reference_count_(0) {
1479 }
1480
1481 void VisitPointers(Object** start, Object** end) {
1482 if (collecting_all_references_) {
1483 for (Object** p = start; p < end; p++) all_references_.Add(*p);
1484 } else {
1485 for (Object** p = start; p < end; p++) strong_references_.Add(*p);
1486 }
1487 }
1488
1489 void SetCollectingAllReferences() { collecting_all_references_ = true; }
1490
1491 void FillReferences(V8HeapExplorer* explorer) {
1492 ASSERT(strong_references_.length() <= all_references_.length());
1493 for (int i = 0; i < reference_tags_.length(); ++i) {
1494 explorer->SetGcRootsReference(reference_tags_[i].tag);
1495 }
1496 int strong_index = 0, all_index = 0, tags_index = 0;
1497 while (all_index < all_references_.length()) {
1498 if (strong_index < strong_references_.length() &&
1499 strong_references_[strong_index] == all_references_[all_index]) {
1500 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1501 false,
1502 all_references_[all_index++]);
1503 ++strong_index;
1504 } else {
1505 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1506 true,
1507 all_references_[all_index++]);
1508 }
1509 if (reference_tags_[tags_index].index == all_index) ++tags_index;
1510 }
1511 }
1512
1513 void Synchronize(VisitorSynchronization::SyncTag tag) {
1514 if (collecting_all_references_ &&
1515 previous_reference_count_ != all_references_.length()) {
1516 previous_reference_count_ = all_references_.length();
1517 reference_tags_.Add(IndexTag(previous_reference_count_, tag));
1518 }
1519 }
1520
1521 private:
1522 bool collecting_all_references_;
1523 List<Object*> strong_references_;
1524 List<Object*> all_references_;
1525 int previous_reference_count_;
1526 List<IndexTag> reference_tags_;
1527};
1528
1529
1530bool V8HeapExplorer::IterateAndExtractReferences(
1531 SnapshotFillerInterface* filler) {
1532 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
1533
1534 filler_ = filler;
1535 bool interrupted = false;
1536
1537 // Heap iteration with filtering must be finished in any case.
1538 for (HeapObject* obj = iterator.next();
1539 obj != NULL;
1540 obj = iterator.next(), progress_->ProgressStep()) {
1541 if (!interrupted) {
1542 ExtractReferences(obj);
1543 if (!progress_->ProgressReport(false)) interrupted = true;
1544 }
1545 }
1546 if (interrupted) {
1547 filler_ = NULL;
1548 return false;
1549 }
1550
1551 SetRootGcRootsReference();
1552 RootsReferencesExtractor extractor;
1553 heap_->IterateRoots(&extractor, VISIT_ONLY_STRONG);
1554 extractor.SetCollectingAllReferences();
1555 heap_->IterateRoots(&extractor, VISIT_ALL);
1556 extractor.FillReferences(this);
1557 filler_ = NULL;
1558 return progress_->ProgressReport(true);
1559}
1560
1561
1562bool V8HeapExplorer::IsEssentialObject(Object* object) {
1563 return object->IsHeapObject()
1564 && !object->IsOddball()
1565 && object != heap_->empty_byte_array()
1566 && object != heap_->empty_fixed_array()
1567 && object != heap_->empty_descriptor_array()
1568 && object != heap_->fixed_array_map()
1569 && object != heap_->global_property_cell_map()
1570 && object != heap_->shared_function_info_map()
1571 && object != heap_->free_space_map()
1572 && object != heap_->one_pointer_filler_map()
1573 && object != heap_->two_pointer_filler_map();
1574}
1575
1576
svenpanne@chromium.org2bda5432013-03-15 12:39:50 +00001577void V8HeapExplorer::SetContextReference(HeapObject* parent_obj,
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001578 int parent_entry,
1579 String* reference_name,
svenpanne@chromium.org2bda5432013-03-15 12:39:50 +00001580 Object* child_obj,
1581 int field_offset) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001582 HeapEntry* child_entry = GetEntry(child_obj);
1583 if (child_entry != NULL) {
1584 filler_->SetNamedReference(HeapGraphEdge::kContextVariable,
1585 parent_entry,
1586 collection_->names()->GetName(reference_name),
1587 child_entry);
svenpanne@chromium.org2bda5432013-03-15 12:39:50 +00001588 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001589 }
1590}
1591
1592
1593void V8HeapExplorer::SetNativeBindReference(HeapObject* parent_obj,
1594 int parent_entry,
1595 const char* reference_name,
1596 Object* child_obj) {
1597 HeapEntry* child_entry = GetEntry(child_obj);
1598 if (child_entry != NULL) {
1599 filler_->SetNamedReference(HeapGraphEdge::kShortcut,
1600 parent_entry,
1601 reference_name,
1602 child_entry);
1603 }
1604}
1605
1606
1607void V8HeapExplorer::SetElementReference(HeapObject* parent_obj,
1608 int parent_entry,
1609 int index,
1610 Object* child_obj) {
1611 HeapEntry* child_entry = GetEntry(child_obj);
1612 if (child_entry != NULL) {
1613 filler_->SetIndexedReference(HeapGraphEdge::kElement,
1614 parent_entry,
1615 index,
1616 child_entry);
1617 }
1618}
1619
1620
1621void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1622 int parent_entry,
1623 const char* reference_name,
1624 Object* child_obj,
1625 int field_offset) {
1626 HeapEntry* child_entry = GetEntry(child_obj);
1627 if (child_entry == NULL) return;
1628 if (IsEssentialObject(child_obj)) {
1629 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1630 parent_entry,
1631 reference_name,
1632 child_entry);
1633 }
1634 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1635}
1636
1637
1638void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1639 int parent_entry,
1640 int index,
1641 Object* child_obj,
1642 int field_offset) {
1643 HeapEntry* child_entry = GetEntry(child_obj);
1644 if (child_entry == NULL) return;
1645 if (IsEssentialObject(child_obj)) {
1646 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1647 parent_entry,
1648 collection_->names()->GetName(index),
1649 child_entry);
1650 }
1651 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1652}
1653
1654
1655void V8HeapExplorer::SetHiddenReference(HeapObject* parent_obj,
1656 int parent_entry,
1657 int index,
1658 Object* child_obj) {
1659 HeapEntry* child_entry = GetEntry(child_obj);
1660 if (child_entry != NULL && IsEssentialObject(child_obj)) {
1661 filler_->SetIndexedReference(HeapGraphEdge::kHidden,
1662 parent_entry,
1663 index,
1664 child_entry);
1665 }
1666}
1667
1668
1669void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
1670 int parent_entry,
1671 int index,
1672 Object* child_obj,
1673 int field_offset) {
1674 HeapEntry* child_entry = GetEntry(child_obj);
1675 if (child_entry != NULL) {
1676 filler_->SetIndexedReference(HeapGraphEdge::kWeak,
1677 parent_entry,
1678 index,
1679 child_entry);
1680 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1681 }
1682}
1683
1684
1685void V8HeapExplorer::SetPropertyReference(HeapObject* parent_obj,
1686 int parent_entry,
ulan@chromium.org750145a2013-03-07 15:14:13 +00001687 Name* reference_name,
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001688 Object* child_obj,
1689 const char* name_format_string,
1690 int field_offset) {
1691 HeapEntry* child_entry = GetEntry(child_obj);
1692 if (child_entry != NULL) {
ulan@chromium.org750145a2013-03-07 15:14:13 +00001693 HeapGraphEdge::Type type =
1694 reference_name->IsSymbol() || String::cast(reference_name)->length() > 0
1695 ? HeapGraphEdge::kProperty : HeapGraphEdge::kInternal;
1696 const char* name = name_format_string != NULL && reference_name->IsString()
1697 ? collection_->names()->GetFormatted(
1698 name_format_string,
1699 *String::cast(reference_name)->ToCString(
1700 DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL)) :
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001701 collection_->names()->GetName(reference_name);
1702
1703 filler_->SetNamedReference(type,
1704 parent_entry,
1705 name,
1706 child_entry);
1707 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1708 }
1709}
1710
1711
1712void V8HeapExplorer::SetRootGcRootsReference() {
1713 filler_->SetIndexedAutoIndexReference(
1714 HeapGraphEdge::kElement,
1715 snapshot_->root()->index(),
1716 snapshot_->gc_roots());
1717}
1718
1719
1720void V8HeapExplorer::SetUserGlobalReference(Object* child_obj) {
1721 HeapEntry* child_entry = GetEntry(child_obj);
1722 ASSERT(child_entry != NULL);
1723 filler_->SetNamedAutoIndexReference(
1724 HeapGraphEdge::kShortcut,
1725 snapshot_->root()->index(),
1726 child_entry);
1727}
1728
1729
1730void V8HeapExplorer::SetGcRootsReference(VisitorSynchronization::SyncTag tag) {
1731 filler_->SetIndexedAutoIndexReference(
1732 HeapGraphEdge::kElement,
1733 snapshot_->gc_roots()->index(),
1734 snapshot_->gc_subroot(tag));
1735}
1736
1737
1738void V8HeapExplorer::SetGcSubrootReference(
1739 VisitorSynchronization::SyncTag tag, bool is_weak, Object* child_obj) {
1740 HeapEntry* child_entry = GetEntry(child_obj);
1741 if (child_entry != NULL) {
1742 const char* name = GetStrongGcSubrootName(child_obj);
1743 if (name != NULL) {
1744 filler_->SetNamedReference(
1745 HeapGraphEdge::kInternal,
1746 snapshot_->gc_subroot(tag)->index(),
1747 name,
1748 child_entry);
1749 } else {
1750 filler_->SetIndexedAutoIndexReference(
1751 is_weak ? HeapGraphEdge::kWeak : HeapGraphEdge::kElement,
1752 snapshot_->gc_subroot(tag)->index(),
1753 child_entry);
1754 }
1755 }
1756}
1757
1758
1759const char* V8HeapExplorer::GetStrongGcSubrootName(Object* object) {
1760 if (strong_gc_subroot_names_.is_empty()) {
1761#define NAME_ENTRY(name) strong_gc_subroot_names_.SetTag(heap_->name(), #name);
1762#define ROOT_NAME(type, name, camel_name) NAME_ENTRY(name)
1763 STRONG_ROOT_LIST(ROOT_NAME)
1764#undef ROOT_NAME
1765#define STRUCT_MAP_NAME(NAME, Name, name) NAME_ENTRY(name##_map)
1766 STRUCT_LIST(STRUCT_MAP_NAME)
1767#undef STRUCT_MAP_NAME
yangguo@chromium.org4a9f6552013-03-04 14:46:33 +00001768#define STRING_NAME(name, str) NAME_ENTRY(name)
1769 INTERNALIZED_STRING_LIST(STRING_NAME)
1770#undef STRING_NAME
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001771#undef NAME_ENTRY
1772 CHECK(!strong_gc_subroot_names_.is_empty());
1773 }
1774 return strong_gc_subroot_names_.GetTag(object);
1775}
1776
1777
1778void V8HeapExplorer::TagObject(Object* obj, const char* tag) {
1779 if (IsEssentialObject(obj)) {
1780 HeapEntry* entry = GetEntry(obj);
1781 if (entry->name()[0] == '\0') {
1782 entry->set_name(tag);
1783 }
1784 }
1785}
1786
1787
1788class GlobalObjectsEnumerator : public ObjectVisitor {
1789 public:
1790 virtual void VisitPointers(Object** start, Object** end) {
1791 for (Object** p = start; p < end; p++) {
1792 if ((*p)->IsNativeContext()) {
1793 Context* context = Context::cast(*p);
1794 JSObject* proxy = context->global_proxy();
1795 if (proxy->IsJSGlobalProxy()) {
1796 Object* global = proxy->map()->prototype();
1797 if (global->IsJSGlobalObject()) {
1798 objects_.Add(Handle<JSGlobalObject>(JSGlobalObject::cast(global)));
1799 }
1800 }
1801 }
1802 }
1803 }
1804 int count() { return objects_.length(); }
1805 Handle<JSGlobalObject>& at(int i) { return objects_[i]; }
1806
1807 private:
1808 List<Handle<JSGlobalObject> > objects_;
1809};
1810
1811
1812// Modifies heap. Must not be run during heap traversal.
1813void V8HeapExplorer::TagGlobalObjects() {
1814 Isolate* isolate = Isolate::Current();
1815 HandleScope scope(isolate);
1816 GlobalObjectsEnumerator enumerator;
1817 isolate->global_handles()->IterateAllRoots(&enumerator);
1818 const char** urls = NewArray<const char*>(enumerator.count());
1819 for (int i = 0, l = enumerator.count(); i < l; ++i) {
1820 if (global_object_name_resolver_) {
1821 HandleScope scope(isolate);
1822 Handle<JSGlobalObject> global_obj = enumerator.at(i);
1823 urls[i] = global_object_name_resolver_->GetName(
1824 Utils::ToLocal(Handle<JSObject>::cast(global_obj)));
1825 } else {
1826 urls[i] = NULL;
1827 }
1828 }
1829
1830 AssertNoAllocation no_allocation;
1831 for (int i = 0, l = enumerator.count(); i < l; ++i) {
1832 objects_tags_.SetTag(*enumerator.at(i), urls[i]);
1833 }
1834
1835 DeleteArray(urls);
1836}
1837
1838
1839class GlobalHandlesExtractor : public ObjectVisitor {
1840 public:
1841 explicit GlobalHandlesExtractor(NativeObjectsExplorer* explorer)
1842 : explorer_(explorer) {}
1843 virtual ~GlobalHandlesExtractor() {}
1844 virtual void VisitPointers(Object** start, Object** end) {
1845 UNREACHABLE();
1846 }
1847 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {
1848 explorer_->VisitSubtreeWrapper(p, class_id);
1849 }
1850 private:
1851 NativeObjectsExplorer* explorer_;
1852};
1853
1854
1855class BasicHeapEntriesAllocator : public HeapEntriesAllocator {
1856 public:
1857 BasicHeapEntriesAllocator(
1858 HeapSnapshot* snapshot,
1859 HeapEntry::Type entries_type)
1860 : snapshot_(snapshot),
1861 collection_(snapshot_->collection()),
1862 entries_type_(entries_type) {
1863 }
1864 virtual HeapEntry* AllocateEntry(HeapThing ptr);
1865 private:
1866 HeapSnapshot* snapshot_;
1867 HeapSnapshotsCollection* collection_;
1868 HeapEntry::Type entries_type_;
1869};
1870
1871
1872HeapEntry* BasicHeapEntriesAllocator::AllocateEntry(HeapThing ptr) {
1873 v8::RetainedObjectInfo* info = reinterpret_cast<v8::RetainedObjectInfo*>(ptr);
1874 intptr_t elements = info->GetElementCount();
1875 intptr_t size = info->GetSizeInBytes();
1876 const char* name = elements != -1
1877 ? collection_->names()->GetFormatted(
1878 "%s / %" V8_PTR_PREFIX "d entries", info->GetLabel(), elements)
1879 : collection_->names()->GetCopy(info->GetLabel());
1880 return snapshot_->AddEntry(
1881 entries_type_,
1882 name,
1883 HeapObjectsMap::GenerateId(info),
1884 size != -1 ? static_cast<int>(size) : 0);
1885}
1886
1887
1888NativeObjectsExplorer::NativeObjectsExplorer(
1889 HeapSnapshot* snapshot, SnapshottingProgressReportingInterface* progress)
1890 : snapshot_(snapshot),
1891 collection_(snapshot_->collection()),
1892 progress_(progress),
1893 embedder_queried_(false),
1894 objects_by_info_(RetainedInfosMatch),
1895 native_groups_(StringsMatch),
1896 filler_(NULL) {
1897 synthetic_entries_allocator_ =
1898 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kSynthetic);
1899 native_entries_allocator_ =
1900 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kNative);
1901}
1902
1903
1904NativeObjectsExplorer::~NativeObjectsExplorer() {
1905 for (HashMap::Entry* p = objects_by_info_.Start();
1906 p != NULL;
1907 p = objects_by_info_.Next(p)) {
1908 v8::RetainedObjectInfo* info =
1909 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
1910 info->Dispose();
1911 List<HeapObject*>* objects =
1912 reinterpret_cast<List<HeapObject*>* >(p->value);
1913 delete objects;
1914 }
1915 for (HashMap::Entry* p = native_groups_.Start();
1916 p != NULL;
1917 p = native_groups_.Next(p)) {
1918 v8::RetainedObjectInfo* info =
1919 reinterpret_cast<v8::RetainedObjectInfo*>(p->value);
1920 info->Dispose();
1921 }
1922 delete synthetic_entries_allocator_;
1923 delete native_entries_allocator_;
1924}
1925
1926
1927int NativeObjectsExplorer::EstimateObjectsCount() {
1928 FillRetainedObjects();
1929 return objects_by_info_.occupancy();
1930}
1931
1932
1933void NativeObjectsExplorer::FillRetainedObjects() {
1934 if (embedder_queried_) return;
1935 Isolate* isolate = Isolate::Current();
1936 const GCType major_gc_type = kGCTypeMarkSweepCompact;
1937 // Record objects that are joined into ObjectGroups.
danno@chromium.orgca29dd82013-04-26 11:59:48 +00001938 isolate->heap()->CallGCPrologueCallbacks(
1939 major_gc_type, kGCCallbackFlagConstructRetainedObjectInfos);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001940 List<ObjectGroup*>* groups = isolate->global_handles()->object_groups();
1941 for (int i = 0; i < groups->length(); ++i) {
1942 ObjectGroup* group = groups->at(i);
danno@chromium.orgca29dd82013-04-26 11:59:48 +00001943 if (group->info == NULL) continue;
1944 List<HeapObject*>* list = GetListMaybeDisposeInfo(group->info);
1945 for (size_t j = 0; j < group->length; ++j) {
1946 HeapObject* obj = HeapObject::cast(*group->objects[j]);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001947 list->Add(obj);
1948 in_groups_.Insert(obj);
1949 }
danno@chromium.orgca29dd82013-04-26 11:59:48 +00001950 group->info = NULL; // Acquire info object ownership.
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001951 }
1952 isolate->global_handles()->RemoveObjectGroups();
1953 isolate->heap()->CallGCEpilogueCallbacks(major_gc_type);
1954 // Record objects that are not in ObjectGroups, but have class ID.
1955 GlobalHandlesExtractor extractor(this);
1956 isolate->global_handles()->IterateAllRootsWithClassIds(&extractor);
1957 embedder_queried_ = true;
1958}
1959
1960void NativeObjectsExplorer::FillImplicitReferences() {
1961 Isolate* isolate = Isolate::Current();
1962 List<ImplicitRefGroup*>* groups =
1963 isolate->global_handles()->implicit_ref_groups();
1964 for (int i = 0; i < groups->length(); ++i) {
1965 ImplicitRefGroup* group = groups->at(i);
danno@chromium.orgca29dd82013-04-26 11:59:48 +00001966 HeapObject* parent = *group->parent;
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001967 int parent_entry =
1968 filler_->FindOrAddEntry(parent, native_entries_allocator_)->index();
1969 ASSERT(parent_entry != HeapEntry::kNoEntry);
danno@chromium.orgca29dd82013-04-26 11:59:48 +00001970 Object*** children = group->children;
1971 for (size_t j = 0; j < group->length; ++j) {
ulan@chromium.org2e04b582013-02-21 14:06:02 +00001972 Object* child = *children[j];
1973 HeapEntry* child_entry =
1974 filler_->FindOrAddEntry(child, native_entries_allocator_);
1975 filler_->SetNamedReference(
1976 HeapGraphEdge::kInternal,
1977 parent_entry,
1978 "native",
1979 child_entry);
1980 }
1981 }
1982 isolate->global_handles()->RemoveImplicitRefGroups();
1983}
1984
1985List<HeapObject*>* NativeObjectsExplorer::GetListMaybeDisposeInfo(
1986 v8::RetainedObjectInfo* info) {
1987 HashMap::Entry* entry =
1988 objects_by_info_.Lookup(info, InfoHash(info), true);
1989 if (entry->value != NULL) {
1990 info->Dispose();
1991 } else {
1992 entry->value = new List<HeapObject*>(4);
1993 }
1994 return reinterpret_cast<List<HeapObject*>* >(entry->value);
1995}
1996
1997
1998bool NativeObjectsExplorer::IterateAndExtractReferences(
1999 SnapshotFillerInterface* filler) {
2000 filler_ = filler;
2001 FillRetainedObjects();
2002 FillImplicitReferences();
2003 if (EstimateObjectsCount() > 0) {
2004 for (HashMap::Entry* p = objects_by_info_.Start();
2005 p != NULL;
2006 p = objects_by_info_.Next(p)) {
2007 v8::RetainedObjectInfo* info =
2008 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2009 SetNativeRootReference(info);
2010 List<HeapObject*>* objects =
2011 reinterpret_cast<List<HeapObject*>* >(p->value);
2012 for (int i = 0; i < objects->length(); ++i) {
2013 SetWrapperNativeReferences(objects->at(i), info);
2014 }
2015 }
2016 SetRootNativeRootsReference();
2017 }
2018 filler_ = NULL;
2019 return true;
2020}
2021
2022
2023class NativeGroupRetainedObjectInfo : public v8::RetainedObjectInfo {
2024 public:
2025 explicit NativeGroupRetainedObjectInfo(const char* label)
2026 : disposed_(false),
2027 hash_(reinterpret_cast<intptr_t>(label)),
2028 label_(label) {
2029 }
2030
2031 virtual ~NativeGroupRetainedObjectInfo() {}
2032 virtual void Dispose() {
2033 CHECK(!disposed_);
2034 disposed_ = true;
2035 delete this;
2036 }
2037 virtual bool IsEquivalent(RetainedObjectInfo* other) {
2038 return hash_ == other->GetHash() && !strcmp(label_, other->GetLabel());
2039 }
2040 virtual intptr_t GetHash() { return hash_; }
2041 virtual const char* GetLabel() { return label_; }
2042
2043 private:
2044 bool disposed_;
2045 intptr_t hash_;
2046 const char* label_;
2047};
2048
2049
2050NativeGroupRetainedObjectInfo* NativeObjectsExplorer::FindOrAddGroupInfo(
2051 const char* label) {
2052 const char* label_copy = collection_->names()->GetCopy(label);
2053 uint32_t hash = StringHasher::HashSequentialString(
2054 label_copy,
2055 static_cast<int>(strlen(label_copy)),
2056 HEAP->HashSeed());
2057 HashMap::Entry* entry = native_groups_.Lookup(const_cast<char*>(label_copy),
2058 hash, true);
2059 if (entry->value == NULL) {
2060 entry->value = new NativeGroupRetainedObjectInfo(label);
2061 }
2062 return static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2063}
2064
2065
2066void NativeObjectsExplorer::SetNativeRootReference(
2067 v8::RetainedObjectInfo* info) {
2068 HeapEntry* child_entry =
2069 filler_->FindOrAddEntry(info, native_entries_allocator_);
2070 ASSERT(child_entry != NULL);
2071 NativeGroupRetainedObjectInfo* group_info =
2072 FindOrAddGroupInfo(info->GetGroupLabel());
2073 HeapEntry* group_entry =
2074 filler_->FindOrAddEntry(group_info, synthetic_entries_allocator_);
2075 filler_->SetNamedAutoIndexReference(
2076 HeapGraphEdge::kInternal,
2077 group_entry->index(),
2078 child_entry);
2079}
2080
2081
2082void NativeObjectsExplorer::SetWrapperNativeReferences(
2083 HeapObject* wrapper, v8::RetainedObjectInfo* info) {
2084 HeapEntry* wrapper_entry = filler_->FindEntry(wrapper);
2085 ASSERT(wrapper_entry != NULL);
2086 HeapEntry* info_entry =
2087 filler_->FindOrAddEntry(info, native_entries_allocator_);
2088 ASSERT(info_entry != NULL);
2089 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2090 wrapper_entry->index(),
2091 "native",
2092 info_entry);
2093 filler_->SetIndexedAutoIndexReference(HeapGraphEdge::kElement,
2094 info_entry->index(),
2095 wrapper_entry);
2096}
2097
2098
2099void NativeObjectsExplorer::SetRootNativeRootsReference() {
2100 for (HashMap::Entry* entry = native_groups_.Start();
2101 entry;
2102 entry = native_groups_.Next(entry)) {
2103 NativeGroupRetainedObjectInfo* group_info =
2104 static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2105 HeapEntry* group_entry =
2106 filler_->FindOrAddEntry(group_info, native_entries_allocator_);
2107 ASSERT(group_entry != NULL);
2108 filler_->SetIndexedAutoIndexReference(
2109 HeapGraphEdge::kElement,
2110 snapshot_->root()->index(),
2111 group_entry);
2112 }
2113}
2114
2115
2116void NativeObjectsExplorer::VisitSubtreeWrapper(Object** p, uint16_t class_id) {
2117 if (in_groups_.Contains(*p)) return;
2118 Isolate* isolate = Isolate::Current();
2119 v8::RetainedObjectInfo* info =
2120 isolate->heap_profiler()->ExecuteWrapperClassCallback(class_id, p);
2121 if (info == NULL) return;
2122 GetListMaybeDisposeInfo(info)->Add(HeapObject::cast(*p));
2123}
2124
2125
2126class SnapshotFiller : public SnapshotFillerInterface {
2127 public:
2128 explicit SnapshotFiller(HeapSnapshot* snapshot, HeapEntriesMap* entries)
2129 : snapshot_(snapshot),
2130 collection_(snapshot->collection()),
2131 entries_(entries) { }
2132 HeapEntry* AddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
2133 HeapEntry* entry = allocator->AllocateEntry(ptr);
2134 entries_->Pair(ptr, entry->index());
2135 return entry;
2136 }
2137 HeapEntry* FindEntry(HeapThing ptr) {
2138 int index = entries_->Map(ptr);
2139 return index != HeapEntry::kNoEntry ? &snapshot_->entries()[index] : NULL;
2140 }
2141 HeapEntry* FindOrAddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
2142 HeapEntry* entry = FindEntry(ptr);
2143 return entry != NULL ? entry : AddEntry(ptr, allocator);
2144 }
2145 void SetIndexedReference(HeapGraphEdge::Type type,
2146 int parent,
2147 int index,
2148 HeapEntry* child_entry) {
2149 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2150 parent_entry->SetIndexedReference(type, index, child_entry);
2151 }
2152 void SetIndexedAutoIndexReference(HeapGraphEdge::Type type,
2153 int parent,
2154 HeapEntry* child_entry) {
2155 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2156 int index = parent_entry->children_count() + 1;
2157 parent_entry->SetIndexedReference(type, index, child_entry);
2158 }
2159 void SetNamedReference(HeapGraphEdge::Type type,
2160 int parent,
2161 const char* reference_name,
2162 HeapEntry* child_entry) {
2163 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2164 parent_entry->SetNamedReference(type, reference_name, child_entry);
2165 }
2166 void SetNamedAutoIndexReference(HeapGraphEdge::Type type,
2167 int parent,
2168 HeapEntry* child_entry) {
2169 HeapEntry* parent_entry = &snapshot_->entries()[parent];
2170 int index = parent_entry->children_count() + 1;
2171 parent_entry->SetNamedReference(
2172 type,
2173 collection_->names()->GetName(index),
2174 child_entry);
2175 }
2176
2177 private:
2178 HeapSnapshot* snapshot_;
2179 HeapSnapshotsCollection* collection_;
2180 HeapEntriesMap* entries_;
2181};
2182
2183
2184HeapSnapshotGenerator::HeapSnapshotGenerator(
2185 HeapSnapshot* snapshot,
2186 v8::ActivityControl* control,
2187 v8::HeapProfiler::ObjectNameResolver* resolver,
2188 Heap* heap)
2189 : snapshot_(snapshot),
2190 control_(control),
2191 v8_heap_explorer_(snapshot_, this, resolver),
2192 dom_explorer_(snapshot_, this),
2193 heap_(heap) {
2194}
2195
2196
2197bool HeapSnapshotGenerator::GenerateSnapshot() {
2198 v8_heap_explorer_.TagGlobalObjects();
2199
2200 // TODO(1562) Profiler assumes that any object that is in the heap after
2201 // full GC is reachable from the root when computing dominators.
2202 // This is not true for weakly reachable objects.
2203 // As a temporary solution we call GC twice.
2204 Isolate::Current()->heap()->CollectAllGarbage(
2205 Heap::kMakeHeapIterableMask,
2206 "HeapSnapshotGenerator::GenerateSnapshot");
2207 Isolate::Current()->heap()->CollectAllGarbage(
2208 Heap::kMakeHeapIterableMask,
2209 "HeapSnapshotGenerator::GenerateSnapshot");
2210
2211#ifdef VERIFY_HEAP
2212 Heap* debug_heap = Isolate::Current()->heap();
2213 CHECK(!debug_heap->old_data_space()->was_swept_conservatively());
2214 CHECK(!debug_heap->old_pointer_space()->was_swept_conservatively());
2215 CHECK(!debug_heap->code_space()->was_swept_conservatively());
2216 CHECK(!debug_heap->cell_space()->was_swept_conservatively());
2217 CHECK(!debug_heap->map_space()->was_swept_conservatively());
2218#endif
2219
2220 // The following code uses heap iterators, so we want the heap to be
2221 // stable. It should follow TagGlobalObjects as that can allocate.
2222 AssertNoAllocation no_alloc;
2223
2224#ifdef VERIFY_HEAP
2225 debug_heap->Verify();
2226#endif
2227
2228 SetProgressTotal(1); // 1 pass.
2229
2230#ifdef VERIFY_HEAP
2231 debug_heap->Verify();
2232#endif
2233
2234 if (!FillReferences()) return false;
2235
2236 snapshot_->FillChildren();
2237 snapshot_->RememberLastJSObjectId();
2238
2239 progress_counter_ = progress_total_;
2240 if (!ProgressReport(true)) return false;
2241 return true;
2242}
2243
2244
2245void HeapSnapshotGenerator::ProgressStep() {
2246 ++progress_counter_;
2247}
2248
2249
2250bool HeapSnapshotGenerator::ProgressReport(bool force) {
2251 const int kProgressReportGranularity = 10000;
2252 if (control_ != NULL
2253 && (force || progress_counter_ % kProgressReportGranularity == 0)) {
2254 return
2255 control_->ReportProgressValue(progress_counter_, progress_total_) ==
2256 v8::ActivityControl::kContinue;
2257 }
2258 return true;
2259}
2260
2261
2262void HeapSnapshotGenerator::SetProgressTotal(int iterations_count) {
2263 if (control_ == NULL) return;
2264 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
2265 progress_total_ = iterations_count * (
2266 v8_heap_explorer_.EstimateObjectsCount(&iterator) +
2267 dom_explorer_.EstimateObjectsCount());
2268 progress_counter_ = 0;
2269}
2270
2271
2272bool HeapSnapshotGenerator::FillReferences() {
2273 SnapshotFiller filler(snapshot_, &entries_);
2274 v8_heap_explorer_.AddRootEntries(&filler);
2275 return v8_heap_explorer_.IterateAndExtractReferences(&filler)
2276 && dom_explorer_.IterateAndExtractReferences(&filler);
2277}
2278
2279
2280template<int bytes> struct MaxDecimalDigitsIn;
2281template<> struct MaxDecimalDigitsIn<4> {
2282 static const int kSigned = 11;
2283 static const int kUnsigned = 10;
2284};
2285template<> struct MaxDecimalDigitsIn<8> {
2286 static const int kSigned = 20;
2287 static const int kUnsigned = 20;
2288};
2289
2290
2291class OutputStreamWriter {
2292 public:
2293 explicit OutputStreamWriter(v8::OutputStream* stream)
2294 : stream_(stream),
2295 chunk_size_(stream->GetChunkSize()),
2296 chunk_(chunk_size_),
2297 chunk_pos_(0),
2298 aborted_(false) {
2299 ASSERT(chunk_size_ > 0);
2300 }
2301 bool aborted() { return aborted_; }
2302 void AddCharacter(char c) {
2303 ASSERT(c != '\0');
2304 ASSERT(chunk_pos_ < chunk_size_);
2305 chunk_[chunk_pos_++] = c;
2306 MaybeWriteChunk();
2307 }
2308 void AddString(const char* s) {
2309 AddSubstring(s, StrLength(s));
2310 }
2311 void AddSubstring(const char* s, int n) {
2312 if (n <= 0) return;
2313 ASSERT(static_cast<size_t>(n) <= strlen(s));
2314 const char* s_end = s + n;
2315 while (s < s_end) {
2316 int s_chunk_size = Min(
2317 chunk_size_ - chunk_pos_, static_cast<int>(s_end - s));
2318 ASSERT(s_chunk_size > 0);
mstarzinger@chromium.orge27d6172013-04-17 11:51:44 +00002319 OS::MemCopy(chunk_.start() + chunk_pos_, s, s_chunk_size);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00002320 s += s_chunk_size;
2321 chunk_pos_ += s_chunk_size;
2322 MaybeWriteChunk();
2323 }
2324 }
2325 void AddNumber(unsigned n) { AddNumberImpl<unsigned>(n, "%u"); }
2326 void Finalize() {
2327 if (aborted_) return;
2328 ASSERT(chunk_pos_ < chunk_size_);
2329 if (chunk_pos_ != 0) {
2330 WriteChunk();
2331 }
2332 stream_->EndOfStream();
2333 }
2334
2335 private:
2336 template<typename T>
2337 void AddNumberImpl(T n, const char* format) {
2338 // Buffer for the longest value plus trailing \0
2339 static const int kMaxNumberSize =
2340 MaxDecimalDigitsIn<sizeof(T)>::kUnsigned + 1;
2341 if (chunk_size_ - chunk_pos_ >= kMaxNumberSize) {
2342 int result = OS::SNPrintF(
2343 chunk_.SubVector(chunk_pos_, chunk_size_), format, n);
2344 ASSERT(result != -1);
2345 chunk_pos_ += result;
2346 MaybeWriteChunk();
2347 } else {
2348 EmbeddedVector<char, kMaxNumberSize> buffer;
2349 int result = OS::SNPrintF(buffer, format, n);
2350 USE(result);
2351 ASSERT(result != -1);
2352 AddString(buffer.start());
2353 }
2354 }
2355 void MaybeWriteChunk() {
2356 ASSERT(chunk_pos_ <= chunk_size_);
2357 if (chunk_pos_ == chunk_size_) {
2358 WriteChunk();
2359 }
2360 }
2361 void WriteChunk() {
2362 if (aborted_) return;
2363 if (stream_->WriteAsciiChunk(chunk_.start(), chunk_pos_) ==
2364 v8::OutputStream::kAbort) aborted_ = true;
2365 chunk_pos_ = 0;
2366 }
2367
2368 v8::OutputStream* stream_;
2369 int chunk_size_;
2370 ScopedVector<char> chunk_;
2371 int chunk_pos_;
2372 bool aborted_;
2373};
2374
2375
2376// type, name|index, to_node.
2377const int HeapSnapshotJSONSerializer::kEdgeFieldsCount = 3;
2378// type, name, id, self_size, children_index.
2379const int HeapSnapshotJSONSerializer::kNodeFieldsCount = 5;
2380
2381void HeapSnapshotJSONSerializer::Serialize(v8::OutputStream* stream) {
2382 ASSERT(writer_ == NULL);
2383 writer_ = new OutputStreamWriter(stream);
ulan@chromium.org2e04b582013-02-21 14:06:02 +00002384 SerializeImpl();
ulan@chromium.org2e04b582013-02-21 14:06:02 +00002385 delete writer_;
2386 writer_ = NULL;
ulan@chromium.org2e04b582013-02-21 14:06:02 +00002387}
2388
2389
2390void HeapSnapshotJSONSerializer::SerializeImpl() {
2391 ASSERT(0 == snapshot_->root()->index());
2392 writer_->AddCharacter('{');
2393 writer_->AddString("\"snapshot\":{");
2394 SerializeSnapshot();
2395 if (writer_->aborted()) return;
2396 writer_->AddString("},\n");
2397 writer_->AddString("\"nodes\":[");
2398 SerializeNodes();
2399 if (writer_->aborted()) return;
2400 writer_->AddString("],\n");
2401 writer_->AddString("\"edges\":[");
2402 SerializeEdges();
2403 if (writer_->aborted()) return;
2404 writer_->AddString("],\n");
2405 writer_->AddString("\"strings\":[");
2406 SerializeStrings();
2407 if (writer_->aborted()) return;
2408 writer_->AddCharacter(']');
2409 writer_->AddCharacter('}');
2410 writer_->Finalize();
2411}
2412
2413
2414int HeapSnapshotJSONSerializer::GetStringId(const char* s) {
2415 HashMap::Entry* cache_entry = strings_.Lookup(
2416 const_cast<char*>(s), ObjectHash(s), true);
2417 if (cache_entry->value == NULL) {
2418 cache_entry->value = reinterpret_cast<void*>(next_string_id_++);
2419 }
2420 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2421}
2422
2423
2424static int utoa(unsigned value, const Vector<char>& buffer, int buffer_pos) {
2425 int number_of_digits = 0;
2426 unsigned t = value;
2427 do {
2428 ++number_of_digits;
2429 } while (t /= 10);
2430
2431 buffer_pos += number_of_digits;
2432 int result = buffer_pos;
2433 do {
2434 int last_digit = value % 10;
2435 buffer[--buffer_pos] = '0' + last_digit;
2436 value /= 10;
2437 } while (value);
2438 return result;
2439}
2440
2441
2442void HeapSnapshotJSONSerializer::SerializeEdge(HeapGraphEdge* edge,
2443 bool first_edge) {
2444 // The buffer needs space for 3 unsigned ints, 3 commas, \n and \0
2445 static const int kBufferSize =
2446 MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned * 3 + 3 + 2; // NOLINT
2447 EmbeddedVector<char, kBufferSize> buffer;
2448 int edge_name_or_index = edge->type() == HeapGraphEdge::kElement
2449 || edge->type() == HeapGraphEdge::kHidden
2450 || edge->type() == HeapGraphEdge::kWeak
2451 ? edge->index() : GetStringId(edge->name());
2452 int buffer_pos = 0;
2453 if (!first_edge) {
2454 buffer[buffer_pos++] = ',';
2455 }
2456 buffer_pos = utoa(edge->type(), buffer, buffer_pos);
2457 buffer[buffer_pos++] = ',';
2458 buffer_pos = utoa(edge_name_or_index, buffer, buffer_pos);
2459 buffer[buffer_pos++] = ',';
2460 buffer_pos = utoa(entry_index(edge->to()), buffer, buffer_pos);
2461 buffer[buffer_pos++] = '\n';
2462 buffer[buffer_pos++] = '\0';
2463 writer_->AddString(buffer.start());
2464}
2465
2466
2467void HeapSnapshotJSONSerializer::SerializeEdges() {
2468 List<HeapGraphEdge*>& edges = snapshot_->children();
2469 for (int i = 0; i < edges.length(); ++i) {
2470 ASSERT(i == 0 ||
2471 edges[i - 1]->from()->index() <= edges[i]->from()->index());
2472 SerializeEdge(edges[i], i == 0);
2473 if (writer_->aborted()) return;
2474 }
2475}
2476
2477
2478void HeapSnapshotJSONSerializer::SerializeNode(HeapEntry* entry) {
2479 // The buffer needs space for 5 unsigned ints, 5 commas, \n and \0
2480 static const int kBufferSize =
2481 5 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2482 + 5 + 1 + 1;
2483 EmbeddedVector<char, kBufferSize> buffer;
2484 int buffer_pos = 0;
2485 if (entry_index(entry) != 0) {
2486 buffer[buffer_pos++] = ',';
2487 }
2488 buffer_pos = utoa(entry->type(), buffer, buffer_pos);
2489 buffer[buffer_pos++] = ',';
2490 buffer_pos = utoa(GetStringId(entry->name()), buffer, buffer_pos);
2491 buffer[buffer_pos++] = ',';
2492 buffer_pos = utoa(entry->id(), buffer, buffer_pos);
2493 buffer[buffer_pos++] = ',';
2494 buffer_pos = utoa(entry->self_size(), buffer, buffer_pos);
2495 buffer[buffer_pos++] = ',';
2496 buffer_pos = utoa(entry->children_count(), buffer, buffer_pos);
2497 buffer[buffer_pos++] = '\n';
2498 buffer[buffer_pos++] = '\0';
2499 writer_->AddString(buffer.start());
2500}
2501
2502
2503void HeapSnapshotJSONSerializer::SerializeNodes() {
2504 List<HeapEntry>& entries = snapshot_->entries();
2505 for (int i = 0; i < entries.length(); ++i) {
2506 SerializeNode(&entries[i]);
2507 if (writer_->aborted()) return;
2508 }
2509}
2510
2511
2512void HeapSnapshotJSONSerializer::SerializeSnapshot() {
2513 writer_->AddString("\"title\":\"");
2514 writer_->AddString(snapshot_->title());
2515 writer_->AddString("\"");
2516 writer_->AddString(",\"uid\":");
2517 writer_->AddNumber(snapshot_->uid());
2518 writer_->AddString(",\"meta\":");
2519 // The object describing node serialization layout.
2520 // We use a set of macros to improve readability.
2521#define JSON_A(s) "[" s "]"
2522#define JSON_O(s) "{" s "}"
2523#define JSON_S(s) "\"" s "\""
2524 writer_->AddString(JSON_O(
2525 JSON_S("node_fields") ":" JSON_A(
2526 JSON_S("type") ","
2527 JSON_S("name") ","
2528 JSON_S("id") ","
2529 JSON_S("self_size") ","
2530 JSON_S("edge_count")) ","
2531 JSON_S("node_types") ":" JSON_A(
2532 JSON_A(
2533 JSON_S("hidden") ","
2534 JSON_S("array") ","
2535 JSON_S("string") ","
2536 JSON_S("object") ","
2537 JSON_S("code") ","
2538 JSON_S("closure") ","
2539 JSON_S("regexp") ","
2540 JSON_S("number") ","
2541 JSON_S("native") ","
svenpanne@chromium.org876cca82013-03-18 14:43:20 +00002542 JSON_S("synthetic")) ","
ulan@chromium.org2e04b582013-02-21 14:06:02 +00002543 JSON_S("string") ","
2544 JSON_S("number") ","
2545 JSON_S("number") ","
2546 JSON_S("number") ","
2547 JSON_S("number") ","
2548 JSON_S("number")) ","
2549 JSON_S("edge_fields") ":" JSON_A(
2550 JSON_S("type") ","
2551 JSON_S("name_or_index") ","
2552 JSON_S("to_node")) ","
2553 JSON_S("edge_types") ":" JSON_A(
2554 JSON_A(
2555 JSON_S("context") ","
2556 JSON_S("element") ","
2557 JSON_S("property") ","
2558 JSON_S("internal") ","
2559 JSON_S("hidden") ","
2560 JSON_S("shortcut") ","
2561 JSON_S("weak")) ","
2562 JSON_S("string_or_number") ","
2563 JSON_S("node"))));
2564#undef JSON_S
2565#undef JSON_O
2566#undef JSON_A
2567 writer_->AddString(",\"node_count\":");
2568 writer_->AddNumber(snapshot_->entries().length());
2569 writer_->AddString(",\"edge_count\":");
2570 writer_->AddNumber(snapshot_->edges().length());
2571}
2572
2573
2574static void WriteUChar(OutputStreamWriter* w, unibrow::uchar u) {
2575 static const char hex_chars[] = "0123456789ABCDEF";
2576 w->AddString("\\u");
2577 w->AddCharacter(hex_chars[(u >> 12) & 0xf]);
2578 w->AddCharacter(hex_chars[(u >> 8) & 0xf]);
2579 w->AddCharacter(hex_chars[(u >> 4) & 0xf]);
2580 w->AddCharacter(hex_chars[u & 0xf]);
2581}
2582
2583void HeapSnapshotJSONSerializer::SerializeString(const unsigned char* s) {
2584 writer_->AddCharacter('\n');
2585 writer_->AddCharacter('\"');
2586 for ( ; *s != '\0'; ++s) {
2587 switch (*s) {
2588 case '\b':
2589 writer_->AddString("\\b");
2590 continue;
2591 case '\f':
2592 writer_->AddString("\\f");
2593 continue;
2594 case '\n':
2595 writer_->AddString("\\n");
2596 continue;
2597 case '\r':
2598 writer_->AddString("\\r");
2599 continue;
2600 case '\t':
2601 writer_->AddString("\\t");
2602 continue;
2603 case '\"':
2604 case '\\':
2605 writer_->AddCharacter('\\');
2606 writer_->AddCharacter(*s);
2607 continue;
2608 default:
2609 if (*s > 31 && *s < 128) {
2610 writer_->AddCharacter(*s);
2611 } else if (*s <= 31) {
2612 // Special character with no dedicated literal.
2613 WriteUChar(writer_, *s);
2614 } else {
2615 // Convert UTF-8 into \u UTF-16 literal.
2616 unsigned length = 1, cursor = 0;
2617 for ( ; length <= 4 && *(s + length) != '\0'; ++length) { }
2618 unibrow::uchar c = unibrow::Utf8::CalculateValue(s, length, &cursor);
2619 if (c != unibrow::Utf8::kBadChar) {
2620 WriteUChar(writer_, c);
2621 ASSERT(cursor != 0);
2622 s += cursor - 1;
2623 } else {
2624 writer_->AddCharacter('?');
2625 }
2626 }
2627 }
2628 }
2629 writer_->AddCharacter('\"');
2630}
2631
2632
2633void HeapSnapshotJSONSerializer::SerializeStrings() {
2634 List<HashMap::Entry*> sorted_strings;
2635 SortHashMap(&strings_, &sorted_strings);
2636 writer_->AddString("\"<dummy>\"");
2637 for (int i = 0; i < sorted_strings.length(); ++i) {
2638 writer_->AddCharacter(',');
2639 SerializeString(
2640 reinterpret_cast<const unsigned char*>(sorted_strings[i]->key));
2641 if (writer_->aborted()) return;
2642 }
2643}
2644
2645
2646template<typename T>
2647inline static int SortUsingEntryValue(const T* x, const T* y) {
2648 uintptr_t x_uint = reinterpret_cast<uintptr_t>((*x)->value);
2649 uintptr_t y_uint = reinterpret_cast<uintptr_t>((*y)->value);
2650 if (x_uint > y_uint) {
2651 return 1;
2652 } else if (x_uint == y_uint) {
2653 return 0;
2654 } else {
2655 return -1;
2656 }
2657}
2658
2659
2660void HeapSnapshotJSONSerializer::SortHashMap(
2661 HashMap* map, List<HashMap::Entry*>* sorted_entries) {
2662 for (HashMap::Entry* p = map->Start(); p != NULL; p = map->Next(p))
2663 sorted_entries->Add(p);
2664 sorted_entries->Sort(SortUsingEntryValue);
2665}
2666
2667} } // namespace v8::internal