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