blob: e67acef268f1fdc340425ac07f59182287f3232c [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2013 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/profiler/heap-snapshot-generator.h"
6
7#include "src/code-stubs.h"
8#include "src/conversions.h"
9#include "src/debug/debug.h"
10#include "src/objects-body-descriptors.h"
11#include "src/profiler/allocation-tracker.h"
12#include "src/profiler/heap-profiler.h"
13#include "src/profiler/heap-snapshot-generator-inl.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000014
15namespace v8 {
16namespace internal {
17
18
19HeapGraphEdge::HeapGraphEdge(Type type, const char* name, int from, int to)
20 : bit_field_(TypeField::encode(type) | FromIndexField::encode(from)),
21 to_index_(to),
22 name_(name) {
23 DCHECK(type == kContextVariable
24 || type == kProperty
25 || type == kInternal
26 || type == kShortcut
27 || type == kWeak);
28}
29
30
31HeapGraphEdge::HeapGraphEdge(Type type, int index, int from, int to)
32 : bit_field_(TypeField::encode(type) | FromIndexField::encode(from)),
33 to_index_(to),
34 index_(index) {
35 DCHECK(type == kElement || type == kHidden);
36}
37
38
39void HeapGraphEdge::ReplaceToIndexWithEntry(HeapSnapshot* snapshot) {
40 to_entry_ = &snapshot->entries()[to_index_];
41}
42
43
44const int HeapEntry::kNoEntry = -1;
45
46HeapEntry::HeapEntry(HeapSnapshot* snapshot,
47 Type type,
48 const char* name,
49 SnapshotObjectId id,
50 size_t self_size,
51 unsigned trace_node_id)
52 : type_(type),
53 children_count_(0),
54 children_index_(-1),
55 self_size_(self_size),
56 snapshot_(snapshot),
57 name_(name),
58 id_(id),
59 trace_node_id_(trace_node_id) { }
60
61
62void HeapEntry::SetNamedReference(HeapGraphEdge::Type type,
63 const char* name,
64 HeapEntry* entry) {
65 HeapGraphEdge edge(type, name, this->index(), entry->index());
66 snapshot_->edges().Add(edge);
67 ++children_count_;
68}
69
70
71void HeapEntry::SetIndexedReference(HeapGraphEdge::Type type,
72 int index,
73 HeapEntry* entry) {
74 HeapGraphEdge edge(type, index, this->index(), entry->index());
75 snapshot_->edges().Add(edge);
76 ++children_count_;
77}
78
79
80void HeapEntry::Print(
81 const char* prefix, const char* edge_name, int max_depth, int indent) {
82 STATIC_ASSERT(sizeof(unsigned) == sizeof(id()));
Ben Murdochc5610432016-08-08 18:44:38 +010083 base::OS::Print("%6" PRIuS " @%6u %*c %s%s: ", self_size(), id(), indent,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000084 ' ', prefix, edge_name);
85 if (type() != kString) {
86 base::OS::Print("%s %.40s\n", TypeAsString(), name_);
87 } else {
88 base::OS::Print("\"");
89 const char* c = name_;
90 while (*c && (c - name_) <= 40) {
91 if (*c != '\n')
92 base::OS::Print("%c", *c);
93 else
94 base::OS::Print("\\n");
95 ++c;
96 }
97 base::OS::Print("\"\n");
98 }
99 if (--max_depth == 0) return;
100 Vector<HeapGraphEdge*> ch = children();
101 for (int i = 0; i < ch.length(); ++i) {
102 HeapGraphEdge& edge = *ch[i];
103 const char* edge_prefix = "";
104 EmbeddedVector<char, 64> index;
105 const char* edge_name = index.start();
106 switch (edge.type()) {
107 case HeapGraphEdge::kContextVariable:
108 edge_prefix = "#";
109 edge_name = edge.name();
110 break;
111 case HeapGraphEdge::kElement:
112 SNPrintF(index, "%d", edge.index());
113 break;
114 case HeapGraphEdge::kInternal:
115 edge_prefix = "$";
116 edge_name = edge.name();
117 break;
118 case HeapGraphEdge::kProperty:
119 edge_name = edge.name();
120 break;
121 case HeapGraphEdge::kHidden:
122 edge_prefix = "$";
123 SNPrintF(index, "%d", edge.index());
124 break;
125 case HeapGraphEdge::kShortcut:
126 edge_prefix = "^";
127 edge_name = edge.name();
128 break;
129 case HeapGraphEdge::kWeak:
130 edge_prefix = "w";
131 edge_name = edge.name();
132 break;
133 default:
134 SNPrintF(index, "!!! unknown edge type: %d ", edge.type());
135 }
136 edge.to()->Print(edge_prefix, edge_name, max_depth, indent + 2);
137 }
138}
139
140
141const char* HeapEntry::TypeAsString() {
142 switch (type()) {
143 case kHidden: return "/hidden/";
144 case kObject: return "/object/";
145 case kClosure: return "/closure/";
146 case kString: return "/string/";
147 case kCode: return "/code/";
148 case kArray: return "/array/";
149 case kRegExp: return "/regexp/";
150 case kHeapNumber: return "/number/";
151 case kNative: return "/native/";
152 case kSynthetic: return "/synthetic/";
153 case kConsString: return "/concatenated string/";
154 case kSlicedString: return "/sliced string/";
155 case kSymbol: return "/symbol/";
156 case kSimdValue: return "/simd/";
157 default: return "???";
158 }
159}
160
161
162// It is very important to keep objects that form a heap snapshot
163// as small as possible.
164namespace { // Avoid littering the global namespace.
165
166template <size_t ptr_size> struct SnapshotSizeConstants;
167
168template <> struct SnapshotSizeConstants<4> {
169 static const int kExpectedHeapGraphEdgeSize = 12;
170 static const int kExpectedHeapEntrySize = 28;
171};
172
173template <> struct SnapshotSizeConstants<8> {
174 static const int kExpectedHeapGraphEdgeSize = 24;
175 static const int kExpectedHeapEntrySize = 40;
176};
177
178} // namespace
179
180
181HeapSnapshot::HeapSnapshot(HeapProfiler* profiler)
182 : profiler_(profiler),
183 root_index_(HeapEntry::kNoEntry),
184 gc_roots_index_(HeapEntry::kNoEntry),
185 max_snapshot_js_object_id_(0) {
186 STATIC_ASSERT(
187 sizeof(HeapGraphEdge) ==
188 SnapshotSizeConstants<kPointerSize>::kExpectedHeapGraphEdgeSize);
189 STATIC_ASSERT(
190 sizeof(HeapEntry) ==
191 SnapshotSizeConstants<kPointerSize>::kExpectedHeapEntrySize);
192 USE(SnapshotSizeConstants<4>::kExpectedHeapGraphEdgeSize);
193 USE(SnapshotSizeConstants<4>::kExpectedHeapEntrySize);
194 USE(SnapshotSizeConstants<8>::kExpectedHeapGraphEdgeSize);
195 USE(SnapshotSizeConstants<8>::kExpectedHeapEntrySize);
196 for (int i = 0; i < VisitorSynchronization::kNumberOfSyncTags; ++i) {
197 gc_subroot_indexes_[i] = HeapEntry::kNoEntry;
198 }
199}
200
201
202void HeapSnapshot::Delete() {
203 profiler_->RemoveSnapshot(this);
204 delete this;
205}
206
207
208void HeapSnapshot::RememberLastJSObjectId() {
209 max_snapshot_js_object_id_ = profiler_->heap_object_map()->last_assigned_id();
210}
211
212
213void HeapSnapshot::AddSyntheticRootEntries() {
214 AddRootEntry();
215 AddGcRootsEntry();
216 SnapshotObjectId id = HeapObjectsMap::kGcRootsFirstSubrootId;
217 for (int tag = 0; tag < VisitorSynchronization::kNumberOfSyncTags; tag++) {
218 AddGcSubrootEntry(tag, id);
219 id += HeapObjectsMap::kObjectIdStep;
220 }
221 DCHECK(HeapObjectsMap::kFirstAvailableObjectId == id);
222}
223
224
225HeapEntry* HeapSnapshot::AddRootEntry() {
226 DCHECK(root_index_ == HeapEntry::kNoEntry);
227 DCHECK(entries_.is_empty()); // Root entry must be the first one.
228 HeapEntry* entry = AddEntry(HeapEntry::kSynthetic,
229 "",
230 HeapObjectsMap::kInternalRootObjectId,
231 0,
232 0);
233 root_index_ = entry->index();
234 DCHECK(root_index_ == 0);
235 return entry;
236}
237
238
239HeapEntry* HeapSnapshot::AddGcRootsEntry() {
240 DCHECK(gc_roots_index_ == HeapEntry::kNoEntry);
241 HeapEntry* entry = AddEntry(HeapEntry::kSynthetic,
242 "(GC roots)",
243 HeapObjectsMap::kGcRootsObjectId,
244 0,
245 0);
246 gc_roots_index_ = entry->index();
247 return entry;
248}
249
250
251HeapEntry* HeapSnapshot::AddGcSubrootEntry(int tag, SnapshotObjectId id) {
252 DCHECK(gc_subroot_indexes_[tag] == HeapEntry::kNoEntry);
253 DCHECK(0 <= tag && tag < VisitorSynchronization::kNumberOfSyncTags);
254 HeapEntry* entry = AddEntry(HeapEntry::kSynthetic,
255 VisitorSynchronization::kTagNames[tag], id, 0, 0);
256 gc_subroot_indexes_[tag] = entry->index();
257 return entry;
258}
259
260
261HeapEntry* HeapSnapshot::AddEntry(HeapEntry::Type type,
262 const char* name,
263 SnapshotObjectId id,
264 size_t size,
265 unsigned trace_node_id) {
266 HeapEntry entry(this, type, name, id, size, trace_node_id);
267 entries_.Add(entry);
268 return &entries_.last();
269}
270
271
272void HeapSnapshot::FillChildren() {
273 DCHECK(children().is_empty());
274 children().Allocate(edges().length());
275 int children_index = 0;
276 for (int i = 0; i < entries().length(); ++i) {
277 HeapEntry* entry = &entries()[i];
278 children_index = entry->set_children_index(children_index);
279 }
280 DCHECK(edges().length() == children_index);
281 for (int i = 0; i < edges().length(); ++i) {
282 HeapGraphEdge* edge = &edges()[i];
283 edge->ReplaceToIndexWithEntry(this);
284 edge->from()->add_child(edge);
285 }
286}
287
288
289class FindEntryById {
290 public:
291 explicit FindEntryById(SnapshotObjectId id) : id_(id) { }
292 int operator()(HeapEntry* const* entry) {
293 if ((*entry)->id() == id_) return 0;
294 return (*entry)->id() < id_ ? -1 : 1;
295 }
296 private:
297 SnapshotObjectId id_;
298};
299
300
301HeapEntry* HeapSnapshot::GetEntryById(SnapshotObjectId id) {
302 List<HeapEntry*>* entries_by_id = GetSortedEntriesList();
303 // Perform a binary search by id.
304 int index = SortedListBSearch(*entries_by_id, FindEntryById(id));
305 if (index == -1)
306 return NULL;
307 return entries_by_id->at(index);
308}
309
310
311template<class T>
312static int SortByIds(const T* entry1_ptr,
313 const T* entry2_ptr) {
314 if ((*entry1_ptr)->id() == (*entry2_ptr)->id()) return 0;
315 return (*entry1_ptr)->id() < (*entry2_ptr)->id() ? -1 : 1;
316}
317
318
319List<HeapEntry*>* HeapSnapshot::GetSortedEntriesList() {
320 if (sorted_entries_.is_empty()) {
321 sorted_entries_.Allocate(entries_.length());
322 for (int i = 0; i < entries_.length(); ++i) {
323 sorted_entries_[i] = &entries_[i];
324 }
325 sorted_entries_.Sort<int (*)(HeapEntry* const*, HeapEntry* const*)>(
326 SortByIds);
327 }
328 return &sorted_entries_;
329}
330
331
332void HeapSnapshot::Print(int max_depth) {
333 root()->Print("", "", max_depth, 0);
334}
335
336
337size_t HeapSnapshot::RawSnapshotSize() const {
338 return
339 sizeof(*this) +
340 GetMemoryUsedByList(entries_) +
341 GetMemoryUsedByList(edges_) +
342 GetMemoryUsedByList(children_) +
343 GetMemoryUsedByList(sorted_entries_);
344}
345
346
347// We split IDs on evens for embedder objects (see
348// HeapObjectsMap::GenerateId) and odds for native objects.
349const SnapshotObjectId HeapObjectsMap::kInternalRootObjectId = 1;
350const SnapshotObjectId HeapObjectsMap::kGcRootsObjectId =
351 HeapObjectsMap::kInternalRootObjectId + HeapObjectsMap::kObjectIdStep;
352const SnapshotObjectId HeapObjectsMap::kGcRootsFirstSubrootId =
353 HeapObjectsMap::kGcRootsObjectId + HeapObjectsMap::kObjectIdStep;
354const SnapshotObjectId HeapObjectsMap::kFirstAvailableObjectId =
355 HeapObjectsMap::kGcRootsFirstSubrootId +
356 VisitorSynchronization::kNumberOfSyncTags * HeapObjectsMap::kObjectIdStep;
357
358
359static bool AddressesMatch(void* key1, void* key2) {
360 return key1 == key2;
361}
362
363
364HeapObjectsMap::HeapObjectsMap(Heap* heap)
365 : next_id_(kFirstAvailableObjectId),
366 entries_map_(AddressesMatch),
367 heap_(heap) {
368 // This dummy element solves a problem with entries_map_.
369 // When we do lookup in HashMap we see no difference between two cases:
370 // it has an entry with NULL as the value or it has created
371 // a new entry on the fly with NULL as the default value.
372 // With such dummy element we have a guaranty that all entries_map_ entries
373 // will have the value field grater than 0.
374 // This fact is using in MoveObject method.
375 entries_.Add(EntryInfo(0, NULL, 0));
376}
377
378
379bool HeapObjectsMap::MoveObject(Address from, Address to, int object_size) {
380 DCHECK(to != NULL);
381 DCHECK(from != NULL);
382 if (from == to) return false;
383 void* from_value = entries_map_.Remove(from, ComputePointerHash(from));
384 if (from_value == NULL) {
385 // It may occur that some untracked object moves to an address X and there
386 // is a tracked object at that address. In this case we should remove the
387 // entry as we know that the object has died.
388 void* to_value = entries_map_.Remove(to, ComputePointerHash(to));
389 if (to_value != NULL) {
390 int to_entry_info_index =
391 static_cast<int>(reinterpret_cast<intptr_t>(to_value));
392 entries_.at(to_entry_info_index).addr = NULL;
393 }
394 } else {
395 HashMap::Entry* to_entry =
396 entries_map_.LookupOrInsert(to, ComputePointerHash(to));
397 if (to_entry->value != NULL) {
398 // We found the existing entry with to address for an old object.
399 // Without this operation we will have two EntryInfo's with the same
400 // value in addr field. It is bad because later at RemoveDeadEntries
401 // one of this entry will be removed with the corresponding entries_map_
402 // entry.
403 int to_entry_info_index =
404 static_cast<int>(reinterpret_cast<intptr_t>(to_entry->value));
405 entries_.at(to_entry_info_index).addr = NULL;
406 }
407 int from_entry_info_index =
408 static_cast<int>(reinterpret_cast<intptr_t>(from_value));
409 entries_.at(from_entry_info_index).addr = to;
410 // Size of an object can change during its life, so to keep information
411 // about the object in entries_ consistent, we have to adjust size when the
412 // object is migrated.
413 if (FLAG_heap_profiler_trace_objects) {
414 PrintF("Move object from %p to %p old size %6d new size %6d\n",
415 from,
416 to,
417 entries_.at(from_entry_info_index).size,
418 object_size);
419 }
420 entries_.at(from_entry_info_index).size = object_size;
421 to_entry->value = from_value;
422 }
423 return from_value != NULL;
424}
425
426
427void HeapObjectsMap::UpdateObjectSize(Address addr, int size) {
428 FindOrAddEntry(addr, size, false);
429}
430
431
432SnapshotObjectId HeapObjectsMap::FindEntry(Address addr) {
433 HashMap::Entry* entry = entries_map_.Lookup(addr, ComputePointerHash(addr));
434 if (entry == NULL) return 0;
435 int entry_index = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
436 EntryInfo& entry_info = entries_.at(entry_index);
437 DCHECK(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
438 return entry_info.id;
439}
440
441
442SnapshotObjectId HeapObjectsMap::FindOrAddEntry(Address addr,
443 unsigned int size,
444 bool accessed) {
445 DCHECK(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
446 HashMap::Entry* entry =
447 entries_map_.LookupOrInsert(addr, ComputePointerHash(addr));
448 if (entry->value != NULL) {
449 int entry_index =
450 static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
451 EntryInfo& entry_info = entries_.at(entry_index);
452 entry_info.accessed = accessed;
453 if (FLAG_heap_profiler_trace_objects) {
454 PrintF("Update object size : %p with old size %d and new size %d\n",
455 addr,
456 entry_info.size,
457 size);
458 }
459 entry_info.size = size;
460 return entry_info.id;
461 }
462 entry->value = reinterpret_cast<void*>(entries_.length());
463 SnapshotObjectId id = next_id_;
464 next_id_ += kObjectIdStep;
465 entries_.Add(EntryInfo(id, addr, size, accessed));
466 DCHECK(static_cast<uint32_t>(entries_.length()) > entries_map_.occupancy());
467 return id;
468}
469
470
471void HeapObjectsMap::StopHeapObjectsTracking() {
472 time_intervals_.Clear();
473}
474
475
476void HeapObjectsMap::UpdateHeapObjectsMap() {
477 if (FLAG_heap_profiler_trace_objects) {
478 PrintF("Begin HeapObjectsMap::UpdateHeapObjectsMap. map has %d entries.\n",
479 entries_map_.occupancy());
480 }
481 heap_->CollectAllGarbage(Heap::kMakeHeapIterableMask,
482 "HeapObjectsMap::UpdateHeapObjectsMap");
483 HeapIterator iterator(heap_);
484 for (HeapObject* obj = iterator.next();
485 obj != NULL;
486 obj = iterator.next()) {
487 FindOrAddEntry(obj->address(), obj->Size());
488 if (FLAG_heap_profiler_trace_objects) {
489 PrintF("Update object : %p %6d. Next address is %p\n",
490 obj->address(),
491 obj->Size(),
492 obj->address() + obj->Size());
493 }
494 }
495 RemoveDeadEntries();
496 if (FLAG_heap_profiler_trace_objects) {
497 PrintF("End HeapObjectsMap::UpdateHeapObjectsMap. map has %d entries.\n",
498 entries_map_.occupancy());
499 }
500}
501
502
503namespace {
504
505
506struct HeapObjectInfo {
507 HeapObjectInfo(HeapObject* obj, int expected_size)
508 : obj(obj),
509 expected_size(expected_size) {
510 }
511
512 HeapObject* obj;
513 int expected_size;
514
515 bool IsValid() const { return expected_size == obj->Size(); }
516
517 void Print() const {
518 if (expected_size == 0) {
519 PrintF("Untracked object : %p %6d. Next address is %p\n",
520 obj->address(),
521 obj->Size(),
522 obj->address() + obj->Size());
523 } else if (obj->Size() != expected_size) {
524 PrintF("Wrong size %6d: %p %6d. Next address is %p\n",
525 expected_size,
526 obj->address(),
527 obj->Size(),
528 obj->address() + obj->Size());
529 } else {
530 PrintF("Good object : %p %6d. Next address is %p\n",
531 obj->address(),
532 expected_size,
533 obj->address() + obj->Size());
534 }
535 }
536};
537
538
539static int comparator(const HeapObjectInfo* a, const HeapObjectInfo* b) {
540 if (a->obj < b->obj) return -1;
541 if (a->obj > b->obj) return 1;
542 return 0;
543}
544
545
546} // namespace
547
548
549int HeapObjectsMap::FindUntrackedObjects() {
550 List<HeapObjectInfo> heap_objects(1000);
551
552 HeapIterator iterator(heap_);
553 int untracked = 0;
554 for (HeapObject* obj = iterator.next();
555 obj != NULL;
556 obj = iterator.next()) {
557 HashMap::Entry* entry =
558 entries_map_.Lookup(obj->address(), ComputePointerHash(obj->address()));
559 if (entry == NULL) {
560 ++untracked;
561 if (FLAG_heap_profiler_trace_objects) {
562 heap_objects.Add(HeapObjectInfo(obj, 0));
563 }
564 } else {
565 int entry_index = static_cast<int>(
566 reinterpret_cast<intptr_t>(entry->value));
567 EntryInfo& entry_info = entries_.at(entry_index);
568 if (FLAG_heap_profiler_trace_objects) {
569 heap_objects.Add(HeapObjectInfo(obj,
570 static_cast<int>(entry_info.size)));
571 if (obj->Size() != static_cast<int>(entry_info.size))
572 ++untracked;
573 } else {
574 CHECK_EQ(obj->Size(), static_cast<int>(entry_info.size));
575 }
576 }
577 }
578 if (FLAG_heap_profiler_trace_objects) {
579 PrintF("\nBegin HeapObjectsMap::FindUntrackedObjects. %d entries in map.\n",
580 entries_map_.occupancy());
581 heap_objects.Sort(comparator);
582 int last_printed_object = -1;
583 bool print_next_object = false;
584 for (int i = 0; i < heap_objects.length(); ++i) {
585 const HeapObjectInfo& object_info = heap_objects[i];
586 if (!object_info.IsValid()) {
587 ++untracked;
588 if (last_printed_object != i - 1) {
589 if (i > 0) {
590 PrintF("%d objects were skipped\n", i - 1 - last_printed_object);
591 heap_objects[i - 1].Print();
592 }
593 }
594 object_info.Print();
595 last_printed_object = i;
596 print_next_object = true;
597 } else if (print_next_object) {
598 object_info.Print();
599 print_next_object = false;
600 last_printed_object = i;
601 }
602 }
603 if (last_printed_object < heap_objects.length() - 1) {
604 PrintF("Last %d objects were skipped\n",
605 heap_objects.length() - 1 - last_printed_object);
606 }
607 PrintF("End HeapObjectsMap::FindUntrackedObjects. %d entries in map.\n\n",
608 entries_map_.occupancy());
609 }
610 return untracked;
611}
612
613
614SnapshotObjectId HeapObjectsMap::PushHeapObjectsStats(OutputStream* stream,
615 int64_t* timestamp_us) {
616 UpdateHeapObjectsMap();
617 time_intervals_.Add(TimeInterval(next_id_));
618 int prefered_chunk_size = stream->GetChunkSize();
619 List<v8::HeapStatsUpdate> stats_buffer;
620 DCHECK(!entries_.is_empty());
621 EntryInfo* entry_info = &entries_.first();
622 EntryInfo* end_entry_info = &entries_.last() + 1;
623 for (int time_interval_index = 0;
624 time_interval_index < time_intervals_.length();
625 ++time_interval_index) {
626 TimeInterval& time_interval = time_intervals_[time_interval_index];
627 SnapshotObjectId time_interval_id = time_interval.id;
628 uint32_t entries_size = 0;
629 EntryInfo* start_entry_info = entry_info;
630 while (entry_info < end_entry_info && entry_info->id < time_interval_id) {
631 entries_size += entry_info->size;
632 ++entry_info;
633 }
634 uint32_t entries_count =
635 static_cast<uint32_t>(entry_info - start_entry_info);
636 if (time_interval.count != entries_count ||
637 time_interval.size != entries_size) {
638 stats_buffer.Add(v8::HeapStatsUpdate(
639 time_interval_index,
640 time_interval.count = entries_count,
641 time_interval.size = entries_size));
642 if (stats_buffer.length() >= prefered_chunk_size) {
643 OutputStream::WriteResult result = stream->WriteHeapStatsChunk(
644 &stats_buffer.first(), stats_buffer.length());
645 if (result == OutputStream::kAbort) return last_assigned_id();
646 stats_buffer.Clear();
647 }
648 }
649 }
650 DCHECK(entry_info == end_entry_info);
651 if (!stats_buffer.is_empty()) {
652 OutputStream::WriteResult result = stream->WriteHeapStatsChunk(
653 &stats_buffer.first(), stats_buffer.length());
654 if (result == OutputStream::kAbort) return last_assigned_id();
655 }
656 stream->EndOfStream();
657 if (timestamp_us) {
658 *timestamp_us = (time_intervals_.last().timestamp -
659 time_intervals_[0].timestamp).InMicroseconds();
660 }
661 return last_assigned_id();
662}
663
664
665void HeapObjectsMap::RemoveDeadEntries() {
666 DCHECK(entries_.length() > 0 &&
667 entries_.at(0).id == 0 &&
668 entries_.at(0).addr == NULL);
669 int first_free_entry = 1;
670 for (int i = 1; i < entries_.length(); ++i) {
671 EntryInfo& entry_info = entries_.at(i);
672 if (entry_info.accessed) {
673 if (first_free_entry != i) {
674 entries_.at(first_free_entry) = entry_info;
675 }
676 entries_.at(first_free_entry).accessed = false;
677 HashMap::Entry* entry = entries_map_.Lookup(
678 entry_info.addr, ComputePointerHash(entry_info.addr));
679 DCHECK(entry);
680 entry->value = reinterpret_cast<void*>(first_free_entry);
681 ++first_free_entry;
682 } else {
683 if (entry_info.addr) {
684 entries_map_.Remove(entry_info.addr,
685 ComputePointerHash(entry_info.addr));
686 }
687 }
688 }
689 entries_.Rewind(first_free_entry);
690 DCHECK(static_cast<uint32_t>(entries_.length()) - 1 ==
691 entries_map_.occupancy());
692}
693
694
695SnapshotObjectId HeapObjectsMap::GenerateId(v8::RetainedObjectInfo* info) {
696 SnapshotObjectId id = static_cast<SnapshotObjectId>(info->GetHash());
697 const char* label = info->GetLabel();
698 id ^= StringHasher::HashSequentialString(label,
699 static_cast<int>(strlen(label)),
700 heap_->HashSeed());
701 intptr_t element_count = info->GetElementCount();
702 if (element_count != -1)
703 id ^= ComputeIntegerHash(static_cast<uint32_t>(element_count),
704 v8::internal::kZeroHashSeed);
705 return id << 1;
706}
707
708
709size_t HeapObjectsMap::GetUsedMemorySize() const {
710 return
711 sizeof(*this) +
712 sizeof(HashMap::Entry) * entries_map_.capacity() +
713 GetMemoryUsedByList(entries_) +
714 GetMemoryUsedByList(time_intervals_);
715}
716
717
718HeapEntriesMap::HeapEntriesMap()
719 : entries_(HashMap::PointersMatch) {
720}
721
722
723int HeapEntriesMap::Map(HeapThing thing) {
724 HashMap::Entry* cache_entry = entries_.Lookup(thing, Hash(thing));
725 if (cache_entry == NULL) return HeapEntry::kNoEntry;
726 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
727}
728
729
730void HeapEntriesMap::Pair(HeapThing thing, int entry) {
731 HashMap::Entry* cache_entry = entries_.LookupOrInsert(thing, Hash(thing));
732 DCHECK(cache_entry->value == NULL);
733 cache_entry->value = reinterpret_cast<void*>(static_cast<intptr_t>(entry));
734}
735
736
737HeapObjectsSet::HeapObjectsSet()
738 : entries_(HashMap::PointersMatch) {
739}
740
741
742void HeapObjectsSet::Clear() {
743 entries_.Clear();
744}
745
746
747bool HeapObjectsSet::Contains(Object* obj) {
748 if (!obj->IsHeapObject()) return false;
749 HeapObject* object = HeapObject::cast(obj);
750 return entries_.Lookup(object, HeapEntriesMap::Hash(object)) != NULL;
751}
752
753
754void HeapObjectsSet::Insert(Object* obj) {
755 if (!obj->IsHeapObject()) return;
756 HeapObject* object = HeapObject::cast(obj);
757 entries_.LookupOrInsert(object, HeapEntriesMap::Hash(object));
758}
759
760
761const char* HeapObjectsSet::GetTag(Object* obj) {
762 HeapObject* object = HeapObject::cast(obj);
763 HashMap::Entry* cache_entry =
764 entries_.Lookup(object, HeapEntriesMap::Hash(object));
765 return cache_entry != NULL
766 ? reinterpret_cast<const char*>(cache_entry->value)
767 : NULL;
768}
769
770
771void HeapObjectsSet::SetTag(Object* obj, const char* tag) {
772 if (!obj->IsHeapObject()) return;
773 HeapObject* object = HeapObject::cast(obj);
774 HashMap::Entry* cache_entry =
775 entries_.LookupOrInsert(object, HeapEntriesMap::Hash(object));
776 cache_entry->value = const_cast<char*>(tag);
777}
778
779
780V8HeapExplorer::V8HeapExplorer(
781 HeapSnapshot* snapshot,
782 SnapshottingProgressReportingInterface* progress,
783 v8::HeapProfiler::ObjectNameResolver* resolver)
784 : heap_(snapshot->profiler()->heap_object_map()->heap()),
785 snapshot_(snapshot),
786 names_(snapshot_->profiler()->names()),
787 heap_object_map_(snapshot_->profiler()->heap_object_map()),
788 progress_(progress),
789 filler_(NULL),
790 global_object_name_resolver_(resolver) {
791}
792
793
794V8HeapExplorer::~V8HeapExplorer() {
795}
796
797
798HeapEntry* V8HeapExplorer::AllocateEntry(HeapThing ptr) {
799 return AddEntry(reinterpret_cast<HeapObject*>(ptr));
800}
801
802
803HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object) {
804 if (object->IsJSFunction()) {
805 JSFunction* func = JSFunction::cast(object);
806 SharedFunctionInfo* shared = func->shared();
807 const char* name = names_->GetName(String::cast(shared->name()));
808 return AddEntry(object, HeapEntry::kClosure, name);
809 } else if (object->IsJSBoundFunction()) {
810 return AddEntry(object, HeapEntry::kClosure, "native_bind");
811 } else if (object->IsJSRegExp()) {
812 JSRegExp* re = JSRegExp::cast(object);
813 return AddEntry(object,
814 HeapEntry::kRegExp,
815 names_->GetName(re->Pattern()));
816 } else if (object->IsJSObject()) {
817 const char* name = names_->GetName(
818 GetConstructorName(JSObject::cast(object)));
819 if (object->IsJSGlobalObject()) {
820 const char* tag = objects_tags_.GetTag(object);
821 if (tag != NULL) {
822 name = names_->GetFormatted("%s / %s", name, tag);
823 }
824 }
825 return AddEntry(object, HeapEntry::kObject, name);
826 } else if (object->IsString()) {
827 String* string = String::cast(object);
828 if (string->IsConsString())
829 return AddEntry(object,
830 HeapEntry::kConsString,
831 "(concatenated string)");
832 if (string->IsSlicedString())
833 return AddEntry(object,
834 HeapEntry::kSlicedString,
835 "(sliced string)");
836 return AddEntry(object,
837 HeapEntry::kString,
838 names_->GetName(String::cast(object)));
839 } else if (object->IsSymbol()) {
840 if (Symbol::cast(object)->is_private())
841 return AddEntry(object, HeapEntry::kHidden, "private symbol");
842 else
843 return AddEntry(object, HeapEntry::kSymbol, "symbol");
844 } else if (object->IsCode()) {
845 return AddEntry(object, HeapEntry::kCode, "");
846 } else if (object->IsSharedFunctionInfo()) {
847 String* name = String::cast(SharedFunctionInfo::cast(object)->name());
848 return AddEntry(object,
849 HeapEntry::kCode,
850 names_->GetName(name));
851 } else if (object->IsScript()) {
852 Object* name = Script::cast(object)->name();
853 return AddEntry(object,
854 HeapEntry::kCode,
855 name->IsString()
856 ? names_->GetName(String::cast(name))
857 : "");
858 } else if (object->IsNativeContext()) {
859 return AddEntry(object, HeapEntry::kHidden, "system / NativeContext");
860 } else if (object->IsContext()) {
861 return AddEntry(object, HeapEntry::kObject, "system / Context");
862 } else if (object->IsFixedArray() || object->IsFixedDoubleArray() ||
863 object->IsByteArray()) {
864 return AddEntry(object, HeapEntry::kArray, "");
865 } else if (object->IsHeapNumber()) {
866 return AddEntry(object, HeapEntry::kHeapNumber, "number");
867 } else if (object->IsSimd128Value()) {
868 return AddEntry(object, HeapEntry::kSimdValue, "simd");
869 }
870 return AddEntry(object, HeapEntry::kHidden, GetSystemEntryName(object));
871}
872
873
874HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object,
875 HeapEntry::Type type,
876 const char* name) {
877 return AddEntry(object->address(), type, name, object->Size());
878}
879
880
881HeapEntry* V8HeapExplorer::AddEntry(Address address,
882 HeapEntry::Type type,
883 const char* name,
884 size_t size) {
885 SnapshotObjectId object_id = heap_object_map_->FindOrAddEntry(
886 address, static_cast<unsigned int>(size));
887 unsigned trace_node_id = 0;
888 if (AllocationTracker* allocation_tracker =
889 snapshot_->profiler()->allocation_tracker()) {
890 trace_node_id =
891 allocation_tracker->address_to_trace()->GetTraceNodeId(address);
892 }
893 return snapshot_->AddEntry(type, name, object_id, size, trace_node_id);
894}
895
896
897class SnapshotFiller {
898 public:
899 explicit SnapshotFiller(HeapSnapshot* snapshot, HeapEntriesMap* entries)
900 : snapshot_(snapshot),
901 names_(snapshot->profiler()->names()),
902 entries_(entries) { }
903 HeapEntry* AddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
904 HeapEntry* entry = allocator->AllocateEntry(ptr);
905 entries_->Pair(ptr, entry->index());
906 return entry;
907 }
908 HeapEntry* FindEntry(HeapThing ptr) {
909 int index = entries_->Map(ptr);
910 return index != HeapEntry::kNoEntry ? &snapshot_->entries()[index] : NULL;
911 }
912 HeapEntry* FindOrAddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
913 HeapEntry* entry = FindEntry(ptr);
914 return entry != NULL ? entry : AddEntry(ptr, allocator);
915 }
916 void SetIndexedReference(HeapGraphEdge::Type type,
917 int parent,
918 int index,
919 HeapEntry* child_entry) {
920 HeapEntry* parent_entry = &snapshot_->entries()[parent];
921 parent_entry->SetIndexedReference(type, index, child_entry);
922 }
923 void SetIndexedAutoIndexReference(HeapGraphEdge::Type type,
924 int parent,
925 HeapEntry* child_entry) {
926 HeapEntry* parent_entry = &snapshot_->entries()[parent];
927 int index = parent_entry->children_count() + 1;
928 parent_entry->SetIndexedReference(type, index, child_entry);
929 }
930 void SetNamedReference(HeapGraphEdge::Type type,
931 int parent,
932 const char* reference_name,
933 HeapEntry* child_entry) {
934 HeapEntry* parent_entry = &snapshot_->entries()[parent];
935 parent_entry->SetNamedReference(type, reference_name, child_entry);
936 }
937 void SetNamedAutoIndexReference(HeapGraphEdge::Type type,
938 int parent,
939 HeapEntry* child_entry) {
940 HeapEntry* parent_entry = &snapshot_->entries()[parent];
941 int index = parent_entry->children_count() + 1;
942 parent_entry->SetNamedReference(
943 type,
944 names_->GetName(index),
945 child_entry);
946 }
947
948 private:
949 HeapSnapshot* snapshot_;
950 StringsStorage* names_;
951 HeapEntriesMap* entries_;
952};
953
954
955const char* V8HeapExplorer::GetSystemEntryName(HeapObject* object) {
956 switch (object->map()->instance_type()) {
957 case MAP_TYPE:
958 switch (Map::cast(object)->instance_type()) {
959#define MAKE_STRING_MAP_CASE(instance_type, size, name, Name) \
960 case instance_type: return "system / Map (" #Name ")";
961 STRING_TYPE_LIST(MAKE_STRING_MAP_CASE)
962#undef MAKE_STRING_MAP_CASE
963 default: return "system / Map";
964 }
965 case CELL_TYPE: return "system / Cell";
966 case PROPERTY_CELL_TYPE: return "system / PropertyCell";
967 case FOREIGN_TYPE: return "system / Foreign";
968 case ODDBALL_TYPE: return "system / Oddball";
969#define MAKE_STRUCT_CASE(NAME, Name, name) \
970 case NAME##_TYPE: return "system / "#Name;
971 STRUCT_LIST(MAKE_STRUCT_CASE)
972#undef MAKE_STRUCT_CASE
973 default: return "system";
974 }
975}
976
977
978int V8HeapExplorer::EstimateObjectsCount(HeapIterator* iterator) {
979 int objects_count = 0;
980 for (HeapObject* obj = iterator->next();
981 obj != NULL;
982 obj = iterator->next()) {
983 objects_count++;
984 }
985 return objects_count;
986}
987
988
989class IndexedReferencesExtractor : public ObjectVisitor {
990 public:
991 IndexedReferencesExtractor(V8HeapExplorer* generator, HeapObject* parent_obj,
992 int parent)
993 : generator_(generator),
994 parent_obj_(parent_obj),
995 parent_start_(HeapObject::RawField(parent_obj_, 0)),
996 parent_end_(HeapObject::RawField(parent_obj_, parent_obj_->Size())),
997 parent_(parent),
998 next_index_(0) {}
999 void VisitCodeEntry(Address entry_address) override {
1000 Code* code = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
1001 generator_->SetInternalReference(parent_obj_, parent_, "code", code);
1002 generator_->TagCodeObject(code);
1003 }
1004 void VisitPointers(Object** start, Object** end) override {
1005 for (Object** p = start; p < end; p++) {
1006 intptr_t index =
1007 static_cast<intptr_t>(p - HeapObject::RawField(parent_obj_, 0));
1008 ++next_index_;
1009 // |p| could be outside of the object, e.g., while visiting RelocInfo of
1010 // code objects.
1011 if (p >= parent_start_ && p < parent_end_ && generator_->marks_[index]) {
1012 generator_->marks_[index] = false;
1013 continue;
1014 }
1015 generator_->SetHiddenReference(parent_obj_, parent_, next_index_, *p);
1016 }
1017 }
1018
1019 private:
1020 V8HeapExplorer* generator_;
1021 HeapObject* parent_obj_;
1022 Object** parent_start_;
1023 Object** parent_end_;
1024 int parent_;
1025 int next_index_;
1026};
1027
1028
1029bool V8HeapExplorer::ExtractReferencesPass1(int entry, HeapObject* obj) {
1030 if (obj->IsFixedArray()) return false; // FixedArrays are processed on pass 2
1031
1032 if (obj->IsJSGlobalProxy()) {
1033 ExtractJSGlobalProxyReferences(entry, JSGlobalProxy::cast(obj));
1034 } else if (obj->IsJSArrayBuffer()) {
1035 ExtractJSArrayBufferReferences(entry, JSArrayBuffer::cast(obj));
1036 } else if (obj->IsJSObject()) {
1037 if (obj->IsJSWeakSet()) {
1038 ExtractJSWeakCollectionReferences(entry, JSWeakSet::cast(obj));
1039 } else if (obj->IsJSWeakMap()) {
1040 ExtractJSWeakCollectionReferences(entry, JSWeakMap::cast(obj));
1041 } else if (obj->IsJSSet()) {
1042 ExtractJSCollectionReferences(entry, JSSet::cast(obj));
1043 } else if (obj->IsJSMap()) {
1044 ExtractJSCollectionReferences(entry, JSMap::cast(obj));
1045 }
1046 ExtractJSObjectReferences(entry, JSObject::cast(obj));
1047 } else if (obj->IsString()) {
1048 ExtractStringReferences(entry, String::cast(obj));
1049 } else if (obj->IsSymbol()) {
1050 ExtractSymbolReferences(entry, Symbol::cast(obj));
1051 } else if (obj->IsMap()) {
1052 ExtractMapReferences(entry, Map::cast(obj));
1053 } else if (obj->IsSharedFunctionInfo()) {
1054 ExtractSharedFunctionInfoReferences(entry, SharedFunctionInfo::cast(obj));
1055 } else if (obj->IsScript()) {
1056 ExtractScriptReferences(entry, Script::cast(obj));
1057 } else if (obj->IsAccessorInfo()) {
1058 ExtractAccessorInfoReferences(entry, AccessorInfo::cast(obj));
1059 } else if (obj->IsAccessorPair()) {
1060 ExtractAccessorPairReferences(entry, AccessorPair::cast(obj));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001061 } else if (obj->IsCode()) {
1062 ExtractCodeReferences(entry, Code::cast(obj));
1063 } else if (obj->IsBox()) {
1064 ExtractBoxReferences(entry, Box::cast(obj));
1065 } else if (obj->IsCell()) {
1066 ExtractCellReferences(entry, Cell::cast(obj));
1067 } else if (obj->IsPropertyCell()) {
1068 ExtractPropertyCellReferences(entry, PropertyCell::cast(obj));
1069 } else if (obj->IsAllocationSite()) {
1070 ExtractAllocationSiteReferences(entry, AllocationSite::cast(obj));
1071 }
1072 return true;
1073}
1074
1075
1076bool V8HeapExplorer::ExtractReferencesPass2(int entry, HeapObject* obj) {
1077 if (!obj->IsFixedArray()) return false;
1078
1079 if (obj->IsContext()) {
1080 ExtractContextReferences(entry, Context::cast(obj));
1081 } else {
1082 ExtractFixedArrayReferences(entry, FixedArray::cast(obj));
1083 }
1084 return true;
1085}
1086
1087
1088void V8HeapExplorer::ExtractJSGlobalProxyReferences(
1089 int entry, JSGlobalProxy* proxy) {
1090 SetInternalReference(proxy, entry,
1091 "native_context", proxy->native_context(),
1092 JSGlobalProxy::kNativeContextOffset);
1093}
1094
1095
1096void V8HeapExplorer::ExtractJSObjectReferences(
1097 int entry, JSObject* js_obj) {
1098 HeapObject* obj = js_obj;
1099 ExtractPropertyReferences(js_obj, entry);
1100 ExtractElementReferences(js_obj, entry);
1101 ExtractInternalReferences(js_obj, entry);
1102 PrototypeIterator iter(heap_->isolate(), js_obj);
1103 SetPropertyReference(obj, entry, heap_->proto_string(), iter.GetCurrent());
1104 if (obj->IsJSBoundFunction()) {
1105 JSBoundFunction* js_fun = JSBoundFunction::cast(obj);
1106 TagObject(js_fun->bound_arguments(), "(bound arguments)");
1107 SetInternalReference(js_fun, entry, "bindings", js_fun->bound_arguments(),
1108 JSBoundFunction::kBoundArgumentsOffset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001109 SetNativeBindReference(js_obj, entry, "bound_this", js_fun->bound_this());
1110 SetNativeBindReference(js_obj, entry, "bound_function",
1111 js_fun->bound_target_function());
1112 FixedArray* bindings = js_fun->bound_arguments();
1113 for (int i = 0; i < bindings->length(); i++) {
1114 const char* reference_name = names_->GetFormatted("bound_argument_%d", i);
1115 SetNativeBindReference(js_obj, entry, reference_name, bindings->get(i));
1116 }
1117 } else if (obj->IsJSFunction()) {
1118 JSFunction* js_fun = JSFunction::cast(js_obj);
1119 Object* proto_or_map = js_fun->prototype_or_initial_map();
1120 if (!proto_or_map->IsTheHole()) {
1121 if (!proto_or_map->IsMap()) {
1122 SetPropertyReference(
1123 obj, entry,
1124 heap_->prototype_string(), proto_or_map,
1125 NULL,
1126 JSFunction::kPrototypeOrInitialMapOffset);
1127 } else {
1128 SetPropertyReference(
1129 obj, entry,
1130 heap_->prototype_string(), js_fun->prototype());
1131 SetInternalReference(
1132 obj, entry, "initial_map", proto_or_map,
1133 JSFunction::kPrototypeOrInitialMapOffset);
1134 }
1135 }
1136 SharedFunctionInfo* shared_info = js_fun->shared();
1137 TagObject(js_fun->literals(), "(function literals)");
1138 SetInternalReference(js_fun, entry, "literals", js_fun->literals(),
1139 JSFunction::kLiteralsOffset);
1140 TagObject(shared_info, "(shared function info)");
1141 SetInternalReference(js_fun, entry,
1142 "shared", shared_info,
1143 JSFunction::kSharedFunctionInfoOffset);
1144 TagObject(js_fun->context(), "(context)");
1145 SetInternalReference(js_fun, entry,
1146 "context", js_fun->context(),
1147 JSFunction::kContextOffset);
1148 SetWeakReference(js_fun, entry,
1149 "next_function_link", js_fun->next_function_link(),
1150 JSFunction::kNextFunctionLinkOffset);
1151 // Ensure no new weak references appeared in JSFunction.
1152 STATIC_ASSERT(JSFunction::kCodeEntryOffset ==
1153 JSFunction::kNonWeakFieldsEndOffset);
1154 STATIC_ASSERT(JSFunction::kCodeEntryOffset + kPointerSize ==
1155 JSFunction::kNextFunctionLinkOffset);
1156 STATIC_ASSERT(JSFunction::kNextFunctionLinkOffset + kPointerSize
1157 == JSFunction::kSize);
1158 } else if (obj->IsJSGlobalObject()) {
1159 JSGlobalObject* global_obj = JSGlobalObject::cast(obj);
1160 SetInternalReference(global_obj, entry, "native_context",
1161 global_obj->native_context(),
1162 JSGlobalObject::kNativeContextOffset);
1163 SetInternalReference(global_obj, entry, "global_proxy",
1164 global_obj->global_proxy(),
1165 JSGlobalObject::kGlobalProxyOffset);
1166 STATIC_ASSERT(JSGlobalObject::kSize - JSObject::kHeaderSize ==
1167 2 * kPointerSize);
1168 } else if (obj->IsJSArrayBufferView()) {
1169 JSArrayBufferView* view = JSArrayBufferView::cast(obj);
1170 SetInternalReference(view, entry, "buffer", view->buffer(),
1171 JSArrayBufferView::kBufferOffset);
1172 }
1173 TagObject(js_obj->properties(), "(object properties)");
1174 SetInternalReference(obj, entry,
1175 "properties", js_obj->properties(),
1176 JSObject::kPropertiesOffset);
1177 TagObject(js_obj->elements(), "(object elements)");
1178 SetInternalReference(obj, entry,
1179 "elements", js_obj->elements(),
1180 JSObject::kElementsOffset);
1181}
1182
1183
1184void V8HeapExplorer::ExtractStringReferences(int entry, String* string) {
1185 if (string->IsConsString()) {
1186 ConsString* cs = ConsString::cast(string);
1187 SetInternalReference(cs, entry, "first", cs->first(),
1188 ConsString::kFirstOffset);
1189 SetInternalReference(cs, entry, "second", cs->second(),
1190 ConsString::kSecondOffset);
1191 } else if (string->IsSlicedString()) {
1192 SlicedString* ss = SlicedString::cast(string);
1193 SetInternalReference(ss, entry, "parent", ss->parent(),
1194 SlicedString::kParentOffset);
1195 }
1196}
1197
1198
1199void V8HeapExplorer::ExtractSymbolReferences(int entry, Symbol* symbol) {
1200 SetInternalReference(symbol, entry,
1201 "name", symbol->name(),
1202 Symbol::kNameOffset);
1203}
1204
1205
1206void V8HeapExplorer::ExtractJSCollectionReferences(int entry,
1207 JSCollection* collection) {
1208 SetInternalReference(collection, entry, "table", collection->table(),
1209 JSCollection::kTableOffset);
1210}
1211
1212
1213void V8HeapExplorer::ExtractJSWeakCollectionReferences(
1214 int entry, JSWeakCollection* collection) {
1215 MarkAsWeakContainer(collection->table());
1216 SetInternalReference(collection, entry,
1217 "table", collection->table(),
1218 JSWeakCollection::kTableOffset);
1219}
1220
1221
1222void V8HeapExplorer::ExtractContextReferences(int entry, Context* context) {
1223 if (context == context->declaration_context()) {
1224 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
1225 // Add context allocated locals.
1226 int context_locals = scope_info->ContextLocalCount();
1227 for (int i = 0; i < context_locals; ++i) {
1228 String* local_name = scope_info->ContextLocalName(i);
1229 int idx = Context::MIN_CONTEXT_SLOTS + i;
1230 SetContextReference(context, entry, local_name, context->get(idx),
1231 Context::OffsetOfElementAt(idx));
1232 }
1233 if (scope_info->HasFunctionName()) {
1234 String* name = scope_info->FunctionName();
1235 VariableMode mode;
1236 int idx = scope_info->FunctionContextSlotIndex(name, &mode);
1237 if (idx >= 0) {
1238 SetContextReference(context, entry, name, context->get(idx),
1239 Context::OffsetOfElementAt(idx));
1240 }
1241 }
1242 }
1243
1244#define EXTRACT_CONTEXT_FIELD(index, type, name) \
1245 if (Context::index < Context::FIRST_WEAK_SLOT || \
1246 Context::index == Context::MAP_CACHE_INDEX) { \
1247 SetInternalReference(context, entry, #name, context->get(Context::index), \
1248 FixedArray::OffsetOfElementAt(Context::index)); \
1249 } else { \
1250 SetWeakReference(context, entry, #name, context->get(Context::index), \
1251 FixedArray::OffsetOfElementAt(Context::index)); \
1252 }
1253 EXTRACT_CONTEXT_FIELD(CLOSURE_INDEX, JSFunction, closure);
1254 EXTRACT_CONTEXT_FIELD(PREVIOUS_INDEX, Context, previous);
1255 EXTRACT_CONTEXT_FIELD(EXTENSION_INDEX, HeapObject, extension);
1256 EXTRACT_CONTEXT_FIELD(NATIVE_CONTEXT_INDEX, Context, native_context);
1257 if (context->IsNativeContext()) {
1258 TagObject(context->normalized_map_cache(), "(context norm. map cache)");
1259 TagObject(context->embedder_data(), "(context data)");
1260 NATIVE_CONTEXT_FIELDS(EXTRACT_CONTEXT_FIELD)
1261 EXTRACT_CONTEXT_FIELD(OPTIMIZED_FUNCTIONS_LIST, unused,
1262 optimized_functions_list);
1263 EXTRACT_CONTEXT_FIELD(OPTIMIZED_CODE_LIST, unused, optimized_code_list);
1264 EXTRACT_CONTEXT_FIELD(DEOPTIMIZED_CODE_LIST, unused, deoptimized_code_list);
1265 EXTRACT_CONTEXT_FIELD(NEXT_CONTEXT_LINK, unused, next_context_link);
1266#undef EXTRACT_CONTEXT_FIELD
1267 STATIC_ASSERT(Context::OPTIMIZED_FUNCTIONS_LIST ==
1268 Context::FIRST_WEAK_SLOT);
1269 STATIC_ASSERT(Context::NEXT_CONTEXT_LINK + 1 ==
1270 Context::NATIVE_CONTEXT_SLOTS);
1271 STATIC_ASSERT(Context::FIRST_WEAK_SLOT + 4 ==
1272 Context::NATIVE_CONTEXT_SLOTS);
1273 }
1274}
1275
1276
1277void V8HeapExplorer::ExtractMapReferences(int entry, Map* map) {
1278 Object* raw_transitions_or_prototype_info = map->raw_transitions();
1279 if (TransitionArray::IsFullTransitionArray(
1280 raw_transitions_or_prototype_info)) {
1281 TransitionArray* transitions =
1282 TransitionArray::cast(raw_transitions_or_prototype_info);
1283 int transitions_entry = GetEntry(transitions)->index();
1284
1285 if (map->CanTransition()) {
1286 if (transitions->HasPrototypeTransitions()) {
1287 FixedArray* prototype_transitions =
1288 transitions->GetPrototypeTransitions();
1289 MarkAsWeakContainer(prototype_transitions);
1290 TagObject(prototype_transitions, "(prototype transitions");
1291 SetInternalReference(transitions, transitions_entry,
1292 "prototype_transitions", prototype_transitions);
1293 }
1294 // TODO(alph): transitions keys are strong links.
1295 MarkAsWeakContainer(transitions);
1296 }
1297
1298 TagObject(transitions, "(transition array)");
1299 SetInternalReference(map, entry, "transitions", transitions,
1300 Map::kTransitionsOrPrototypeInfoOffset);
1301 } else if (TransitionArray::IsSimpleTransition(
1302 raw_transitions_or_prototype_info)) {
1303 TagObject(raw_transitions_or_prototype_info, "(transition)");
1304 SetInternalReference(map, entry, "transition",
1305 raw_transitions_or_prototype_info,
1306 Map::kTransitionsOrPrototypeInfoOffset);
1307 } else if (map->is_prototype_map()) {
1308 TagObject(raw_transitions_or_prototype_info, "prototype_info");
1309 SetInternalReference(map, entry, "prototype_info",
1310 raw_transitions_or_prototype_info,
1311 Map::kTransitionsOrPrototypeInfoOffset);
1312 }
1313 DescriptorArray* descriptors = map->instance_descriptors();
1314 TagObject(descriptors, "(map descriptors)");
1315 SetInternalReference(map, entry,
1316 "descriptors", descriptors,
1317 Map::kDescriptorsOffset);
1318
1319 MarkAsWeakContainer(map->code_cache());
1320 SetInternalReference(map, entry,
1321 "code_cache", map->code_cache(),
1322 Map::kCodeCacheOffset);
1323 SetInternalReference(map, entry,
1324 "prototype", map->prototype(), Map::kPrototypeOffset);
1325 Object* constructor_or_backpointer = map->constructor_or_backpointer();
1326 if (constructor_or_backpointer->IsMap()) {
1327 TagObject(constructor_or_backpointer, "(back pointer)");
1328 SetInternalReference(map, entry, "back_pointer", constructor_or_backpointer,
1329 Map::kConstructorOrBackPointerOffset);
1330 } else {
1331 SetInternalReference(map, entry, "constructor", constructor_or_backpointer,
1332 Map::kConstructorOrBackPointerOffset);
1333 }
1334 TagObject(map->dependent_code(), "(dependent code)");
1335 MarkAsWeakContainer(map->dependent_code());
1336 SetInternalReference(map, entry,
1337 "dependent_code", map->dependent_code(),
1338 Map::kDependentCodeOffset);
1339}
1340
1341
1342void V8HeapExplorer::ExtractSharedFunctionInfoReferences(
1343 int entry, SharedFunctionInfo* shared) {
1344 HeapObject* obj = shared;
1345 String* shared_name = shared->DebugName();
1346 const char* name = NULL;
1347 if (shared_name != *heap_->isolate()->factory()->empty_string()) {
1348 name = names_->GetName(shared_name);
1349 TagObject(shared->code(), names_->GetFormatted("(code for %s)", name));
1350 } else {
1351 TagObject(shared->code(), names_->GetFormatted("(%s code)",
1352 Code::Kind2String(shared->code()->kind())));
1353 }
1354
1355 SetInternalReference(obj, entry,
1356 "name", shared->name(),
1357 SharedFunctionInfo::kNameOffset);
1358 SetInternalReference(obj, entry,
1359 "code", shared->code(),
1360 SharedFunctionInfo::kCodeOffset);
1361 TagObject(shared->scope_info(), "(function scope info)");
1362 SetInternalReference(obj, entry,
1363 "scope_info", shared->scope_info(),
1364 SharedFunctionInfo::kScopeInfoOffset);
1365 SetInternalReference(obj, entry,
1366 "instance_class_name", shared->instance_class_name(),
1367 SharedFunctionInfo::kInstanceClassNameOffset);
1368 SetInternalReference(obj, entry,
1369 "script", shared->script(),
1370 SharedFunctionInfo::kScriptOffset);
1371 const char* construct_stub_name = name ?
1372 names_->GetFormatted("(construct stub code for %s)", name) :
1373 "(construct stub code)";
1374 TagObject(shared->construct_stub(), construct_stub_name);
1375 SetInternalReference(obj, entry,
1376 "construct_stub", shared->construct_stub(),
1377 SharedFunctionInfo::kConstructStubOffset);
1378 SetInternalReference(obj, entry,
1379 "function_data", shared->function_data(),
1380 SharedFunctionInfo::kFunctionDataOffset);
1381 SetInternalReference(obj, entry,
1382 "debug_info", shared->debug_info(),
1383 SharedFunctionInfo::kDebugInfoOffset);
Ben Murdochda12d292016-06-02 14:46:10 +01001384 SetInternalReference(obj, entry, "function_identifier",
1385 shared->function_identifier(),
1386 SharedFunctionInfo::kFunctionIdentifierOffset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001387 SetInternalReference(obj, entry,
1388 "optimized_code_map", shared->optimized_code_map(),
1389 SharedFunctionInfo::kOptimizedCodeMapOffset);
1390 SetInternalReference(obj, entry,
1391 "feedback_vector", shared->feedback_vector(),
1392 SharedFunctionInfo::kFeedbackVectorOffset);
1393}
1394
1395
1396void V8HeapExplorer::ExtractScriptReferences(int entry, Script* script) {
1397 HeapObject* obj = script;
1398 SetInternalReference(obj, entry,
1399 "source", script->source(),
1400 Script::kSourceOffset);
1401 SetInternalReference(obj, entry,
1402 "name", script->name(),
1403 Script::kNameOffset);
1404 SetInternalReference(obj, entry,
1405 "context_data", script->context_data(),
1406 Script::kContextOffset);
1407 TagObject(script->line_ends(), "(script line ends)");
1408 SetInternalReference(obj, entry,
1409 "line_ends", script->line_ends(),
1410 Script::kLineEndsOffset);
1411}
1412
1413
1414void V8HeapExplorer::ExtractAccessorInfoReferences(
1415 int entry, AccessorInfo* accessor_info) {
1416 SetInternalReference(accessor_info, entry, "name", accessor_info->name(),
1417 AccessorInfo::kNameOffset);
1418 SetInternalReference(accessor_info, entry, "expected_receiver_type",
1419 accessor_info->expected_receiver_type(),
1420 AccessorInfo::kExpectedReceiverTypeOffset);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001421 if (accessor_info->IsAccessorInfo()) {
1422 AccessorInfo* executable_accessor_info = AccessorInfo::cast(accessor_info);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001423 SetInternalReference(executable_accessor_info, entry, "getter",
1424 executable_accessor_info->getter(),
Ben Murdoch097c5b22016-05-18 11:27:45 +01001425 AccessorInfo::kGetterOffset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001426 SetInternalReference(executable_accessor_info, entry, "setter",
1427 executable_accessor_info->setter(),
Ben Murdoch097c5b22016-05-18 11:27:45 +01001428 AccessorInfo::kSetterOffset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001429 SetInternalReference(executable_accessor_info, entry, "data",
1430 executable_accessor_info->data(),
Ben Murdoch097c5b22016-05-18 11:27:45 +01001431 AccessorInfo::kDataOffset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001432 }
1433}
1434
1435
1436void V8HeapExplorer::ExtractAccessorPairReferences(
1437 int entry, AccessorPair* accessors) {
1438 SetInternalReference(accessors, entry, "getter", accessors->getter(),
1439 AccessorPair::kGetterOffset);
1440 SetInternalReference(accessors, entry, "setter", accessors->setter(),
1441 AccessorPair::kSetterOffset);
1442}
1443
1444
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001445void V8HeapExplorer::TagBuiltinCodeObject(Code* code, const char* name) {
1446 TagObject(code, names_->GetFormatted("(%s builtin)", name));
1447}
1448
1449
1450void V8HeapExplorer::TagCodeObject(Code* code) {
1451 if (code->kind() == Code::STUB) {
1452 TagObject(code, names_->GetFormatted(
1453 "(%s code)",
1454 CodeStub::MajorName(CodeStub::GetMajorKey(code))));
1455 }
1456}
1457
1458
1459void V8HeapExplorer::ExtractCodeReferences(int entry, Code* code) {
1460 TagCodeObject(code);
1461 TagObject(code->relocation_info(), "(code relocation info)");
1462 SetInternalReference(code, entry,
1463 "relocation_info", code->relocation_info(),
1464 Code::kRelocationInfoOffset);
1465 SetInternalReference(code, entry,
1466 "handler_table", code->handler_table(),
1467 Code::kHandlerTableOffset);
1468 TagObject(code->deoptimization_data(), "(code deopt data)");
1469 SetInternalReference(code, entry,
1470 "deoptimization_data", code->deoptimization_data(),
1471 Code::kDeoptimizationDataOffset);
1472 if (code->kind() == Code::FUNCTION) {
1473 SetInternalReference(code, entry,
1474 "type_feedback_info", code->type_feedback_info(),
1475 Code::kTypeFeedbackInfoOffset);
1476 }
1477 SetInternalReference(code, entry,
1478 "gc_metadata", code->gc_metadata(),
1479 Code::kGCMetadataOffset);
1480 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1481 SetWeakReference(code, entry,
1482 "next_code_link", code->next_code_link(),
1483 Code::kNextCodeLinkOffset);
1484 }
1485}
1486
1487
1488void V8HeapExplorer::ExtractBoxReferences(int entry, Box* box) {
1489 SetInternalReference(box, entry, "value", box->value(), Box::kValueOffset);
1490}
1491
1492
1493void V8HeapExplorer::ExtractCellReferences(int entry, Cell* cell) {
1494 SetInternalReference(cell, entry, "value", cell->value(), Cell::kValueOffset);
1495}
1496
1497
1498void V8HeapExplorer::ExtractPropertyCellReferences(int entry,
1499 PropertyCell* cell) {
1500 SetInternalReference(cell, entry, "value", cell->value(),
1501 PropertyCell::kValueOffset);
1502 MarkAsWeakContainer(cell->dependent_code());
1503 SetInternalReference(cell, entry, "dependent_code", cell->dependent_code(),
1504 PropertyCell::kDependentCodeOffset);
1505}
1506
1507
1508void V8HeapExplorer::ExtractAllocationSiteReferences(int entry,
1509 AllocationSite* site) {
1510 SetInternalReference(site, entry, "transition_info", site->transition_info(),
1511 AllocationSite::kTransitionInfoOffset);
1512 SetInternalReference(site, entry, "nested_site", site->nested_site(),
1513 AllocationSite::kNestedSiteOffset);
1514 MarkAsWeakContainer(site->dependent_code());
1515 SetInternalReference(site, entry, "dependent_code", site->dependent_code(),
1516 AllocationSite::kDependentCodeOffset);
1517 // Do not visit weak_next as it is not visited by the StaticVisitor,
1518 // and we're not very interested in weak_next field here.
1519 STATIC_ASSERT(AllocationSite::kWeakNextOffset >=
Ben Murdoch097c5b22016-05-18 11:27:45 +01001520 AllocationSite::kPointerFieldsEndOffset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001521}
1522
1523
1524class JSArrayBufferDataEntryAllocator : public HeapEntriesAllocator {
1525 public:
1526 JSArrayBufferDataEntryAllocator(size_t size, V8HeapExplorer* explorer)
1527 : size_(size)
1528 , explorer_(explorer) {
1529 }
1530 virtual HeapEntry* AllocateEntry(HeapThing ptr) {
1531 return explorer_->AddEntry(
1532 static_cast<Address>(ptr),
1533 HeapEntry::kNative, "system / JSArrayBufferData", size_);
1534 }
1535 private:
1536 size_t size_;
1537 V8HeapExplorer* explorer_;
1538};
1539
1540
1541void V8HeapExplorer::ExtractJSArrayBufferReferences(
1542 int entry, JSArrayBuffer* buffer) {
1543 // Setup a reference to a native memory backing_store object.
1544 if (!buffer->backing_store())
1545 return;
1546 size_t data_size = NumberToSize(heap_->isolate(), buffer->byte_length());
1547 JSArrayBufferDataEntryAllocator allocator(data_size, this);
1548 HeapEntry* data_entry =
1549 filler_->FindOrAddEntry(buffer->backing_store(), &allocator);
1550 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1551 entry, "backing_store", data_entry);
1552}
1553
1554
1555void V8HeapExplorer::ExtractFixedArrayReferences(int entry, FixedArray* array) {
1556 bool is_weak = weak_containers_.Contains(array);
1557 for (int i = 0, l = array->length(); i < l; ++i) {
1558 if (is_weak) {
1559 SetWeakReference(array, entry,
1560 i, array->get(i), array->OffsetOfElementAt(i));
1561 } else {
1562 SetInternalReference(array, entry,
1563 i, array->get(i), array->OffsetOfElementAt(i));
1564 }
1565 }
1566}
1567
1568
1569void V8HeapExplorer::ExtractPropertyReferences(JSObject* js_obj, int entry) {
1570 if (js_obj->HasFastProperties()) {
1571 DescriptorArray* descs = js_obj->map()->instance_descriptors();
1572 int real_size = js_obj->map()->NumberOfOwnDescriptors();
1573 for (int i = 0; i < real_size; i++) {
1574 PropertyDetails details = descs->GetDetails(i);
1575 switch (details.location()) {
1576 case kField: {
1577 Representation r = details.representation();
1578 if (r.IsSmi() || r.IsDouble()) break;
1579
1580 Name* k = descs->GetKey(i);
1581 FieldIndex field_index = FieldIndex::ForDescriptor(js_obj->map(), i);
1582 Object* value = js_obj->RawFastPropertyAt(field_index);
1583 int field_offset =
1584 field_index.is_inobject() ? field_index.offset() : -1;
1585
Ben Murdochc5610432016-08-08 18:44:38 +01001586 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry, k,
1587 value, NULL, field_offset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001588 break;
1589 }
1590 case kDescriptor:
1591 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1592 descs->GetKey(i),
1593 descs->GetValue(i));
1594 break;
1595 }
1596 }
1597 } else if (js_obj->IsJSGlobalObject()) {
1598 // We assume that global objects can only have slow properties.
1599 GlobalDictionary* dictionary = js_obj->global_dictionary();
1600 int length = dictionary->Capacity();
1601 for (int i = 0; i < length; ++i) {
1602 Object* k = dictionary->KeyAt(i);
1603 if (dictionary->IsKey(k)) {
1604 DCHECK(dictionary->ValueAt(i)->IsPropertyCell());
1605 PropertyCell* cell = PropertyCell::cast(dictionary->ValueAt(i));
1606 Object* value = cell->value();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001607 PropertyDetails details = cell->property_details();
1608 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1609 Name::cast(k), value);
1610 }
1611 }
1612 } else {
1613 NameDictionary* dictionary = js_obj->property_dictionary();
1614 int length = dictionary->Capacity();
1615 for (int i = 0; i < length; ++i) {
1616 Object* k = dictionary->KeyAt(i);
1617 if (dictionary->IsKey(k)) {
1618 Object* value = dictionary->ValueAt(i);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001619 PropertyDetails details = dictionary->DetailsAt(i);
1620 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1621 Name::cast(k), value);
1622 }
1623 }
1624 }
1625}
1626
1627
1628void V8HeapExplorer::ExtractAccessorPairProperty(JSObject* js_obj, int entry,
1629 Name* key,
1630 Object* callback_obj,
1631 int field_offset) {
1632 if (!callback_obj->IsAccessorPair()) return;
1633 AccessorPair* accessors = AccessorPair::cast(callback_obj);
1634 SetPropertyReference(js_obj, entry, key, accessors, NULL, field_offset);
1635 Object* getter = accessors->getter();
1636 if (!getter->IsOddball()) {
1637 SetPropertyReference(js_obj, entry, key, getter, "get %s");
1638 }
1639 Object* setter = accessors->setter();
1640 if (!setter->IsOddball()) {
1641 SetPropertyReference(js_obj, entry, key, setter, "set %s");
1642 }
1643}
1644
1645
1646void V8HeapExplorer::ExtractElementReferences(JSObject* js_obj, int entry) {
1647 if (js_obj->HasFastObjectElements()) {
1648 FixedArray* elements = FixedArray::cast(js_obj->elements());
1649 int length = js_obj->IsJSArray() ?
1650 Smi::cast(JSArray::cast(js_obj)->length())->value() :
1651 elements->length();
1652 for (int i = 0; i < length; ++i) {
1653 if (!elements->get(i)->IsTheHole()) {
1654 SetElementReference(js_obj, entry, i, elements->get(i));
1655 }
1656 }
1657 } else if (js_obj->HasDictionaryElements()) {
1658 SeededNumberDictionary* dictionary = js_obj->element_dictionary();
1659 int length = dictionary->Capacity();
1660 for (int i = 0; i < length; ++i) {
1661 Object* k = dictionary->KeyAt(i);
1662 if (dictionary->IsKey(k)) {
1663 DCHECK(k->IsNumber());
1664 uint32_t index = static_cast<uint32_t>(k->Number());
1665 SetElementReference(js_obj, entry, index, dictionary->ValueAt(i));
1666 }
1667 }
1668 }
1669}
1670
1671
1672void V8HeapExplorer::ExtractInternalReferences(JSObject* js_obj, int entry) {
1673 int length = js_obj->GetInternalFieldCount();
1674 for (int i = 0; i < length; ++i) {
1675 Object* o = js_obj->GetInternalField(i);
1676 SetInternalReference(
1677 js_obj, entry, i, o, js_obj->GetInternalFieldOffset(i));
1678 }
1679}
1680
1681
1682String* V8HeapExplorer::GetConstructorName(JSObject* object) {
1683 Isolate* isolate = object->GetIsolate();
1684 if (object->IsJSFunction()) return isolate->heap()->closure_string();
1685 DisallowHeapAllocation no_gc;
1686 HandleScope scope(isolate);
1687 return *JSReceiver::GetConstructorName(handle(object, isolate));
1688}
1689
1690
1691HeapEntry* V8HeapExplorer::GetEntry(Object* obj) {
1692 if (!obj->IsHeapObject()) return NULL;
1693 return filler_->FindOrAddEntry(obj, this);
1694}
1695
1696
1697class RootsReferencesExtractor : public ObjectVisitor {
1698 private:
1699 struct IndexTag {
1700 IndexTag(int index, VisitorSynchronization::SyncTag tag)
1701 : index(index), tag(tag) { }
1702 int index;
1703 VisitorSynchronization::SyncTag tag;
1704 };
1705
1706 public:
1707 explicit RootsReferencesExtractor(Heap* heap)
1708 : collecting_all_references_(false),
1709 previous_reference_count_(0),
1710 heap_(heap) {
1711 }
1712
1713 void VisitPointers(Object** start, Object** end) override {
1714 if (collecting_all_references_) {
1715 for (Object** p = start; p < end; p++) all_references_.Add(*p);
1716 } else {
1717 for (Object** p = start; p < end; p++) strong_references_.Add(*p);
1718 }
1719 }
1720
1721 void SetCollectingAllReferences() { collecting_all_references_ = true; }
1722
1723 void FillReferences(V8HeapExplorer* explorer) {
1724 DCHECK(strong_references_.length() <= all_references_.length());
1725 Builtins* builtins = heap_->isolate()->builtins();
1726 int strong_index = 0, all_index = 0, tags_index = 0, builtin_index = 0;
1727 while (all_index < all_references_.length()) {
1728 bool is_strong = strong_index < strong_references_.length()
1729 && strong_references_[strong_index] == all_references_[all_index];
1730 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1731 !is_strong,
1732 all_references_[all_index]);
1733 if (reference_tags_[tags_index].tag ==
1734 VisitorSynchronization::kBuiltins) {
1735 DCHECK(all_references_[all_index]->IsCode());
1736 explorer->TagBuiltinCodeObject(
1737 Code::cast(all_references_[all_index]),
1738 builtins->name(builtin_index++));
1739 }
1740 ++all_index;
1741 if (is_strong) ++strong_index;
1742 if (reference_tags_[tags_index].index == all_index) ++tags_index;
1743 }
1744 }
1745
1746 void Synchronize(VisitorSynchronization::SyncTag tag) override {
1747 if (collecting_all_references_ &&
1748 previous_reference_count_ != all_references_.length()) {
1749 previous_reference_count_ = all_references_.length();
1750 reference_tags_.Add(IndexTag(previous_reference_count_, tag));
1751 }
1752 }
1753
1754 private:
1755 bool collecting_all_references_;
1756 List<Object*> strong_references_;
1757 List<Object*> all_references_;
1758 int previous_reference_count_;
1759 List<IndexTag> reference_tags_;
1760 Heap* heap_;
1761};
1762
1763
1764bool V8HeapExplorer::IterateAndExtractReferences(
1765 SnapshotFiller* filler) {
1766 filler_ = filler;
1767
1768 // Create references to the synthetic roots.
1769 SetRootGcRootsReference();
1770 for (int tag = 0; tag < VisitorSynchronization::kNumberOfSyncTags; tag++) {
1771 SetGcRootsReference(static_cast<VisitorSynchronization::SyncTag>(tag));
1772 }
1773
1774 // Make sure builtin code objects get their builtin tags
1775 // first. Otherwise a particular JSFunction object could set
1776 // its custom name to a generic builtin.
1777 RootsReferencesExtractor extractor(heap_);
1778 heap_->IterateRoots(&extractor, VISIT_ONLY_STRONG);
1779 extractor.SetCollectingAllReferences();
1780 heap_->IterateRoots(&extractor, VISIT_ALL);
1781 extractor.FillReferences(this);
1782
1783 // We have to do two passes as sometimes FixedArrays are used
1784 // to weakly hold their items, and it's impossible to distinguish
1785 // between these cases without processing the array owner first.
1786 bool interrupted =
1787 IterateAndExtractSinglePass<&V8HeapExplorer::ExtractReferencesPass1>() ||
1788 IterateAndExtractSinglePass<&V8HeapExplorer::ExtractReferencesPass2>();
1789
1790 if (interrupted) {
1791 filler_ = NULL;
1792 return false;
1793 }
1794
1795 filler_ = NULL;
1796 return progress_->ProgressReport(true);
1797}
1798
1799
1800template<V8HeapExplorer::ExtractReferencesMethod extractor>
1801bool V8HeapExplorer::IterateAndExtractSinglePass() {
1802 // Now iterate the whole heap.
1803 bool interrupted = false;
1804 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
1805 // Heap iteration with filtering must be finished in any case.
1806 for (HeapObject* obj = iterator.next();
1807 obj != NULL;
1808 obj = iterator.next(), progress_->ProgressStep()) {
1809 if (interrupted) continue;
1810
1811 size_t max_pointer = obj->Size() / kPointerSize;
1812 if (max_pointer > marks_.size()) {
1813 // Clear the current bits.
1814 std::vector<bool>().swap(marks_);
1815 // Reallocate to right size.
1816 marks_.resize(max_pointer, false);
1817 }
1818
1819 HeapEntry* heap_entry = GetEntry(obj);
1820 int entry = heap_entry->index();
1821 if ((this->*extractor)(entry, obj)) {
1822 SetInternalReference(obj, entry,
1823 "map", obj->map(), HeapObject::kMapOffset);
1824 // Extract unvisited fields as hidden references and restore tags
1825 // of visited fields.
1826 IndexedReferencesExtractor refs_extractor(this, obj, entry);
1827 obj->Iterate(&refs_extractor);
1828 }
1829
1830 if (!progress_->ProgressReport(false)) interrupted = true;
1831 }
1832 return interrupted;
1833}
1834
1835
1836bool V8HeapExplorer::IsEssentialObject(Object* object) {
1837 return object->IsHeapObject() && !object->IsOddball() &&
1838 object != heap_->empty_byte_array() &&
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001839 object != heap_->empty_fixed_array() &&
1840 object != heap_->empty_descriptor_array() &&
1841 object != heap_->fixed_array_map() && object != heap_->cell_map() &&
1842 object != heap_->global_property_cell_map() &&
1843 object != heap_->shared_function_info_map() &&
1844 object != heap_->free_space_map() &&
1845 object != heap_->one_pointer_filler_map() &&
1846 object != heap_->two_pointer_filler_map();
1847}
1848
1849
1850void V8HeapExplorer::SetContextReference(HeapObject* parent_obj,
1851 int parent_entry,
1852 String* reference_name,
1853 Object* child_obj,
1854 int field_offset) {
1855 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1856 HeapEntry* child_entry = GetEntry(child_obj);
1857 if (child_entry != NULL) {
1858 filler_->SetNamedReference(HeapGraphEdge::kContextVariable,
1859 parent_entry,
1860 names_->GetName(reference_name),
1861 child_entry);
1862 MarkVisitedField(parent_obj, field_offset);
1863 }
1864}
1865
1866
1867void V8HeapExplorer::MarkVisitedField(HeapObject* obj, int offset) {
1868 if (offset < 0) return;
1869 int index = offset / kPointerSize;
1870 DCHECK(!marks_[index]);
1871 marks_[index] = true;
1872}
1873
1874
1875void V8HeapExplorer::SetNativeBindReference(HeapObject* parent_obj,
1876 int parent_entry,
1877 const char* reference_name,
1878 Object* child_obj) {
1879 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1880 HeapEntry* child_entry = GetEntry(child_obj);
1881 if (child_entry != NULL) {
1882 filler_->SetNamedReference(HeapGraphEdge::kShortcut,
1883 parent_entry,
1884 reference_name,
1885 child_entry);
1886 }
1887}
1888
1889
1890void V8HeapExplorer::SetElementReference(HeapObject* parent_obj,
1891 int parent_entry,
1892 int index,
1893 Object* child_obj) {
1894 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1895 HeapEntry* child_entry = GetEntry(child_obj);
1896 if (child_entry != NULL) {
1897 filler_->SetIndexedReference(HeapGraphEdge::kElement,
1898 parent_entry,
1899 index,
1900 child_entry);
1901 }
1902}
1903
1904
1905void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1906 int parent_entry,
1907 const char* reference_name,
1908 Object* child_obj,
1909 int field_offset) {
1910 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1911 HeapEntry* child_entry = GetEntry(child_obj);
1912 if (child_entry == NULL) return;
1913 if (IsEssentialObject(child_obj)) {
1914 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1915 parent_entry,
1916 reference_name,
1917 child_entry);
1918 }
1919 MarkVisitedField(parent_obj, field_offset);
1920}
1921
1922
1923void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1924 int parent_entry,
1925 int index,
1926 Object* child_obj,
1927 int field_offset) {
1928 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1929 HeapEntry* child_entry = GetEntry(child_obj);
1930 if (child_entry == NULL) return;
1931 if (IsEssentialObject(child_obj)) {
1932 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1933 parent_entry,
1934 names_->GetName(index),
1935 child_entry);
1936 }
1937 MarkVisitedField(parent_obj, field_offset);
1938}
1939
1940
1941void V8HeapExplorer::SetHiddenReference(HeapObject* parent_obj,
1942 int parent_entry,
1943 int index,
1944 Object* child_obj) {
1945 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1946 HeapEntry* child_entry = GetEntry(child_obj);
1947 if (child_entry != NULL && IsEssentialObject(child_obj)) {
1948 filler_->SetIndexedReference(HeapGraphEdge::kHidden,
1949 parent_entry,
1950 index,
1951 child_entry);
1952 }
1953}
1954
1955
1956void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
1957 int parent_entry,
1958 const char* reference_name,
1959 Object* child_obj,
1960 int field_offset) {
1961 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1962 HeapEntry* child_entry = GetEntry(child_obj);
1963 if (child_entry == NULL) return;
1964 if (IsEssentialObject(child_obj)) {
1965 filler_->SetNamedReference(HeapGraphEdge::kWeak,
1966 parent_entry,
1967 reference_name,
1968 child_entry);
1969 }
1970 MarkVisitedField(parent_obj, field_offset);
1971}
1972
1973
1974void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
1975 int parent_entry,
1976 int index,
1977 Object* child_obj,
1978 int field_offset) {
1979 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1980 HeapEntry* child_entry = GetEntry(child_obj);
1981 if (child_entry == NULL) return;
1982 if (IsEssentialObject(child_obj)) {
1983 filler_->SetNamedReference(HeapGraphEdge::kWeak,
1984 parent_entry,
1985 names_->GetFormatted("%d", index),
1986 child_entry);
1987 }
1988 MarkVisitedField(parent_obj, field_offset);
1989}
1990
1991
1992void V8HeapExplorer::SetDataOrAccessorPropertyReference(
1993 PropertyKind kind, JSObject* parent_obj, int parent_entry,
1994 Name* reference_name, Object* child_obj, const char* name_format_string,
1995 int field_offset) {
1996 if (kind == kAccessor) {
1997 ExtractAccessorPairProperty(parent_obj, parent_entry, reference_name,
1998 child_obj, field_offset);
1999 } else {
2000 SetPropertyReference(parent_obj, parent_entry, reference_name, child_obj,
2001 name_format_string, field_offset);
2002 }
2003}
2004
2005
2006void V8HeapExplorer::SetPropertyReference(HeapObject* parent_obj,
2007 int parent_entry,
2008 Name* reference_name,
2009 Object* child_obj,
2010 const char* name_format_string,
2011 int field_offset) {
2012 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2013 HeapEntry* child_entry = GetEntry(child_obj);
2014 if (child_entry != NULL) {
2015 HeapGraphEdge::Type type =
2016 reference_name->IsSymbol() || String::cast(reference_name)->length() > 0
2017 ? HeapGraphEdge::kProperty : HeapGraphEdge::kInternal;
2018 const char* name = name_format_string != NULL && reference_name->IsString()
2019 ? names_->GetFormatted(
2020 name_format_string,
2021 String::cast(reference_name)->ToCString(
2022 DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL).get()) :
2023 names_->GetName(reference_name);
2024
2025 filler_->SetNamedReference(type,
2026 parent_entry,
2027 name,
2028 child_entry);
2029 MarkVisitedField(parent_obj, field_offset);
2030 }
2031}
2032
2033
2034void V8HeapExplorer::SetRootGcRootsReference() {
2035 filler_->SetIndexedAutoIndexReference(
2036 HeapGraphEdge::kElement,
2037 snapshot_->root()->index(),
2038 snapshot_->gc_roots());
2039}
2040
2041
2042void V8HeapExplorer::SetUserGlobalReference(Object* child_obj) {
2043 HeapEntry* child_entry = GetEntry(child_obj);
2044 DCHECK(child_entry != NULL);
2045 filler_->SetNamedAutoIndexReference(
2046 HeapGraphEdge::kShortcut,
2047 snapshot_->root()->index(),
2048 child_entry);
2049}
2050
2051
2052void V8HeapExplorer::SetGcRootsReference(VisitorSynchronization::SyncTag tag) {
2053 filler_->SetIndexedAutoIndexReference(
2054 HeapGraphEdge::kElement,
2055 snapshot_->gc_roots()->index(),
2056 snapshot_->gc_subroot(tag));
2057}
2058
2059
2060void V8HeapExplorer::SetGcSubrootReference(
2061 VisitorSynchronization::SyncTag tag, bool is_weak, Object* child_obj) {
2062 HeapEntry* child_entry = GetEntry(child_obj);
2063 if (child_entry != NULL) {
2064 const char* name = GetStrongGcSubrootName(child_obj);
2065 if (name != NULL) {
2066 filler_->SetNamedReference(
2067 HeapGraphEdge::kInternal,
2068 snapshot_->gc_subroot(tag)->index(),
2069 name,
2070 child_entry);
2071 } else {
2072 if (is_weak) {
2073 filler_->SetNamedAutoIndexReference(
2074 HeapGraphEdge::kWeak,
2075 snapshot_->gc_subroot(tag)->index(),
2076 child_entry);
2077 } else {
2078 filler_->SetIndexedAutoIndexReference(
2079 HeapGraphEdge::kElement,
2080 snapshot_->gc_subroot(tag)->index(),
2081 child_entry);
2082 }
2083 }
2084
2085 // Add a shortcut to JS global object reference at snapshot root.
2086 if (child_obj->IsNativeContext()) {
2087 Context* context = Context::cast(child_obj);
2088 JSGlobalObject* global = context->global_object();
2089 if (global->IsJSGlobalObject()) {
2090 bool is_debug_object = false;
2091 is_debug_object = heap_->isolate()->debug()->IsDebugGlobal(global);
2092 if (!is_debug_object && !user_roots_.Contains(global)) {
2093 user_roots_.Insert(global);
2094 SetUserGlobalReference(global);
2095 }
2096 }
2097 }
2098 }
2099}
2100
2101
2102const char* V8HeapExplorer::GetStrongGcSubrootName(Object* object) {
2103 if (strong_gc_subroot_names_.is_empty()) {
2104#define NAME_ENTRY(name) strong_gc_subroot_names_.SetTag(heap_->name(), #name);
2105#define ROOT_NAME(type, name, camel_name) NAME_ENTRY(name)
2106 STRONG_ROOT_LIST(ROOT_NAME)
2107#undef ROOT_NAME
2108#define STRUCT_MAP_NAME(NAME, Name, name) NAME_ENTRY(name##_map)
2109 STRUCT_LIST(STRUCT_MAP_NAME)
2110#undef STRUCT_MAP_NAME
2111#define STRING_NAME(name, str) NAME_ENTRY(name)
2112 INTERNALIZED_STRING_LIST(STRING_NAME)
2113#undef STRING_NAME
2114#define SYMBOL_NAME(name) NAME_ENTRY(name)
2115 PRIVATE_SYMBOL_LIST(SYMBOL_NAME)
2116#undef SYMBOL_NAME
2117#define SYMBOL_NAME(name, description) NAME_ENTRY(name)
2118 PUBLIC_SYMBOL_LIST(SYMBOL_NAME)
2119 WELL_KNOWN_SYMBOL_LIST(SYMBOL_NAME)
2120#undef SYMBOL_NAME
2121#undef NAME_ENTRY
2122 CHECK(!strong_gc_subroot_names_.is_empty());
2123 }
2124 return strong_gc_subroot_names_.GetTag(object);
2125}
2126
2127
2128void V8HeapExplorer::TagObject(Object* obj, const char* tag) {
2129 if (IsEssentialObject(obj)) {
2130 HeapEntry* entry = GetEntry(obj);
2131 if (entry->name()[0] == '\0') {
2132 entry->set_name(tag);
2133 }
2134 }
2135}
2136
2137
2138void V8HeapExplorer::MarkAsWeakContainer(Object* object) {
2139 if (IsEssentialObject(object) && object->IsFixedArray()) {
2140 weak_containers_.Insert(object);
2141 }
2142}
2143
2144
2145class GlobalObjectsEnumerator : public ObjectVisitor {
2146 public:
2147 void VisitPointers(Object** start, Object** end) override {
2148 for (Object** p = start; p < end; p++) {
2149 if ((*p)->IsNativeContext()) {
2150 Context* context = Context::cast(*p);
2151 JSObject* proxy = context->global_proxy();
2152 if (proxy->IsJSGlobalProxy()) {
2153 Object* global = proxy->map()->prototype();
2154 if (global->IsJSGlobalObject()) {
2155 objects_.Add(Handle<JSGlobalObject>(JSGlobalObject::cast(global)));
2156 }
2157 }
2158 }
2159 }
2160 }
2161 int count() { return objects_.length(); }
2162 Handle<JSGlobalObject>& at(int i) { return objects_[i]; }
2163
2164 private:
2165 List<Handle<JSGlobalObject> > objects_;
2166};
2167
2168
2169// Modifies heap. Must not be run during heap traversal.
2170void V8HeapExplorer::TagGlobalObjects() {
2171 Isolate* isolate = heap_->isolate();
2172 HandleScope scope(isolate);
2173 GlobalObjectsEnumerator enumerator;
2174 isolate->global_handles()->IterateAllRoots(&enumerator);
2175 const char** urls = NewArray<const char*>(enumerator.count());
2176 for (int i = 0, l = enumerator.count(); i < l; ++i) {
2177 if (global_object_name_resolver_) {
2178 HandleScope scope(isolate);
2179 Handle<JSGlobalObject> global_obj = enumerator.at(i);
2180 urls[i] = global_object_name_resolver_->GetName(
2181 Utils::ToLocal(Handle<JSObject>::cast(global_obj)));
2182 } else {
2183 urls[i] = NULL;
2184 }
2185 }
2186
2187 DisallowHeapAllocation no_allocation;
2188 for (int i = 0, l = enumerator.count(); i < l; ++i) {
2189 objects_tags_.SetTag(*enumerator.at(i), urls[i]);
2190 }
2191
2192 DeleteArray(urls);
2193}
2194
2195
2196class GlobalHandlesExtractor : public ObjectVisitor {
2197 public:
2198 explicit GlobalHandlesExtractor(NativeObjectsExplorer* explorer)
2199 : explorer_(explorer) {}
2200 ~GlobalHandlesExtractor() override {}
2201 void VisitPointers(Object** start, Object** end) override { UNREACHABLE(); }
2202 void VisitEmbedderReference(Object** p, uint16_t class_id) override {
2203 explorer_->VisitSubtreeWrapper(p, class_id);
2204 }
2205 private:
2206 NativeObjectsExplorer* explorer_;
2207};
2208
2209
2210class BasicHeapEntriesAllocator : public HeapEntriesAllocator {
2211 public:
2212 BasicHeapEntriesAllocator(
2213 HeapSnapshot* snapshot,
2214 HeapEntry::Type entries_type)
2215 : snapshot_(snapshot),
2216 names_(snapshot_->profiler()->names()),
2217 heap_object_map_(snapshot_->profiler()->heap_object_map()),
2218 entries_type_(entries_type) {
2219 }
2220 virtual HeapEntry* AllocateEntry(HeapThing ptr);
2221 private:
2222 HeapSnapshot* snapshot_;
2223 StringsStorage* names_;
2224 HeapObjectsMap* heap_object_map_;
2225 HeapEntry::Type entries_type_;
2226};
2227
2228
2229HeapEntry* BasicHeapEntriesAllocator::AllocateEntry(HeapThing ptr) {
2230 v8::RetainedObjectInfo* info = reinterpret_cast<v8::RetainedObjectInfo*>(ptr);
2231 intptr_t elements = info->GetElementCount();
2232 intptr_t size = info->GetSizeInBytes();
2233 const char* name = elements != -1
Ben Murdochc5610432016-08-08 18:44:38 +01002234 ? names_->GetFormatted("%s / %" V8PRIdPTR " entries",
2235 info->GetLabel(), elements)
2236 : names_->GetCopy(info->GetLabel());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002237 return snapshot_->AddEntry(
2238 entries_type_,
2239 name,
2240 heap_object_map_->GenerateId(info),
2241 size != -1 ? static_cast<int>(size) : 0,
2242 0);
2243}
2244
2245
2246NativeObjectsExplorer::NativeObjectsExplorer(
2247 HeapSnapshot* snapshot,
2248 SnapshottingProgressReportingInterface* progress)
2249 : isolate_(snapshot->profiler()->heap_object_map()->heap()->isolate()),
2250 snapshot_(snapshot),
2251 names_(snapshot_->profiler()->names()),
2252 embedder_queried_(false),
2253 objects_by_info_(RetainedInfosMatch),
2254 native_groups_(StringsMatch),
2255 filler_(NULL) {
2256 synthetic_entries_allocator_ =
2257 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kSynthetic);
2258 native_entries_allocator_ =
2259 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kNative);
2260}
2261
2262
2263NativeObjectsExplorer::~NativeObjectsExplorer() {
2264 for (HashMap::Entry* p = objects_by_info_.Start();
2265 p != NULL;
2266 p = objects_by_info_.Next(p)) {
2267 v8::RetainedObjectInfo* info =
2268 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2269 info->Dispose();
2270 List<HeapObject*>* objects =
2271 reinterpret_cast<List<HeapObject*>* >(p->value);
2272 delete objects;
2273 }
2274 for (HashMap::Entry* p = native_groups_.Start();
2275 p != NULL;
2276 p = native_groups_.Next(p)) {
2277 v8::RetainedObjectInfo* info =
2278 reinterpret_cast<v8::RetainedObjectInfo*>(p->value);
2279 info->Dispose();
2280 }
2281 delete synthetic_entries_allocator_;
2282 delete native_entries_allocator_;
2283}
2284
2285
2286int NativeObjectsExplorer::EstimateObjectsCount() {
2287 FillRetainedObjects();
2288 return objects_by_info_.occupancy();
2289}
2290
2291
2292void NativeObjectsExplorer::FillRetainedObjects() {
2293 if (embedder_queried_) return;
2294 Isolate* isolate = isolate_;
2295 const GCType major_gc_type = kGCTypeMarkSweepCompact;
2296 // Record objects that are joined into ObjectGroups.
2297 isolate->heap()->CallGCPrologueCallbacks(
2298 major_gc_type, kGCCallbackFlagConstructRetainedObjectInfos);
2299 List<ObjectGroup*>* groups = isolate->global_handles()->object_groups();
2300 for (int i = 0; i < groups->length(); ++i) {
2301 ObjectGroup* group = groups->at(i);
2302 if (group->info == NULL) continue;
2303 List<HeapObject*>* list = GetListMaybeDisposeInfo(group->info);
2304 for (size_t j = 0; j < group->length; ++j) {
2305 HeapObject* obj = HeapObject::cast(*group->objects[j]);
2306 list->Add(obj);
2307 in_groups_.Insert(obj);
2308 }
2309 group->info = NULL; // Acquire info object ownership.
2310 }
2311 isolate->global_handles()->RemoveObjectGroups();
2312 isolate->heap()->CallGCEpilogueCallbacks(major_gc_type, kNoGCCallbackFlags);
2313 // Record objects that are not in ObjectGroups, but have class ID.
2314 GlobalHandlesExtractor extractor(this);
2315 isolate->global_handles()->IterateAllRootsWithClassIds(&extractor);
2316 embedder_queried_ = true;
2317}
2318
2319
2320void NativeObjectsExplorer::FillImplicitReferences() {
2321 Isolate* isolate = isolate_;
2322 List<ImplicitRefGroup*>* groups =
2323 isolate->global_handles()->implicit_ref_groups();
2324 for (int i = 0; i < groups->length(); ++i) {
2325 ImplicitRefGroup* group = groups->at(i);
2326 HeapObject* parent = *group->parent;
2327 int parent_entry =
2328 filler_->FindOrAddEntry(parent, native_entries_allocator_)->index();
2329 DCHECK(parent_entry != HeapEntry::kNoEntry);
2330 Object*** children = group->children;
2331 for (size_t j = 0; j < group->length; ++j) {
2332 Object* child = *children[j];
2333 HeapEntry* child_entry =
2334 filler_->FindOrAddEntry(child, native_entries_allocator_);
2335 filler_->SetNamedReference(
2336 HeapGraphEdge::kInternal,
2337 parent_entry,
2338 "native",
2339 child_entry);
2340 }
2341 }
2342 isolate->global_handles()->RemoveImplicitRefGroups();
2343}
2344
2345List<HeapObject*>* NativeObjectsExplorer::GetListMaybeDisposeInfo(
2346 v8::RetainedObjectInfo* info) {
2347 HashMap::Entry* entry = objects_by_info_.LookupOrInsert(info, InfoHash(info));
2348 if (entry->value != NULL) {
2349 info->Dispose();
2350 } else {
2351 entry->value = new List<HeapObject*>(4);
2352 }
2353 return reinterpret_cast<List<HeapObject*>* >(entry->value);
2354}
2355
2356
2357bool NativeObjectsExplorer::IterateAndExtractReferences(
2358 SnapshotFiller* filler) {
2359 filler_ = filler;
2360 FillRetainedObjects();
2361 FillImplicitReferences();
2362 if (EstimateObjectsCount() > 0) {
2363 for (HashMap::Entry* p = objects_by_info_.Start();
2364 p != NULL;
2365 p = objects_by_info_.Next(p)) {
2366 v8::RetainedObjectInfo* info =
2367 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2368 SetNativeRootReference(info);
2369 List<HeapObject*>* objects =
2370 reinterpret_cast<List<HeapObject*>* >(p->value);
2371 for (int i = 0; i < objects->length(); ++i) {
2372 SetWrapperNativeReferences(objects->at(i), info);
2373 }
2374 }
2375 SetRootNativeRootsReference();
2376 }
2377 filler_ = NULL;
2378 return true;
2379}
2380
2381
2382class NativeGroupRetainedObjectInfo : public v8::RetainedObjectInfo {
2383 public:
2384 explicit NativeGroupRetainedObjectInfo(const char* label)
2385 : disposed_(false),
2386 hash_(reinterpret_cast<intptr_t>(label)),
2387 label_(label) {
2388 }
2389
2390 virtual ~NativeGroupRetainedObjectInfo() {}
2391 virtual void Dispose() {
2392 CHECK(!disposed_);
2393 disposed_ = true;
2394 delete this;
2395 }
2396 virtual bool IsEquivalent(RetainedObjectInfo* other) {
2397 return hash_ == other->GetHash() && !strcmp(label_, other->GetLabel());
2398 }
2399 virtual intptr_t GetHash() { return hash_; }
2400 virtual const char* GetLabel() { return label_; }
2401
2402 private:
2403 bool disposed_;
2404 intptr_t hash_;
2405 const char* label_;
2406};
2407
2408
2409NativeGroupRetainedObjectInfo* NativeObjectsExplorer::FindOrAddGroupInfo(
2410 const char* label) {
2411 const char* label_copy = names_->GetCopy(label);
2412 uint32_t hash = StringHasher::HashSequentialString(
2413 label_copy,
2414 static_cast<int>(strlen(label_copy)),
2415 isolate_->heap()->HashSeed());
2416 HashMap::Entry* entry =
2417 native_groups_.LookupOrInsert(const_cast<char*>(label_copy), hash);
2418 if (entry->value == NULL) {
2419 entry->value = new NativeGroupRetainedObjectInfo(label);
2420 }
2421 return static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2422}
2423
2424
2425void NativeObjectsExplorer::SetNativeRootReference(
2426 v8::RetainedObjectInfo* info) {
2427 HeapEntry* child_entry =
2428 filler_->FindOrAddEntry(info, native_entries_allocator_);
2429 DCHECK(child_entry != NULL);
2430 NativeGroupRetainedObjectInfo* group_info =
2431 FindOrAddGroupInfo(info->GetGroupLabel());
2432 HeapEntry* group_entry =
2433 filler_->FindOrAddEntry(group_info, synthetic_entries_allocator_);
2434 // |FindOrAddEntry| can move and resize the entries backing store. Reload
2435 // potentially-stale pointer.
2436 child_entry = filler_->FindEntry(info);
2437 filler_->SetNamedAutoIndexReference(
2438 HeapGraphEdge::kInternal,
2439 group_entry->index(),
2440 child_entry);
2441}
2442
2443
2444void NativeObjectsExplorer::SetWrapperNativeReferences(
2445 HeapObject* wrapper, v8::RetainedObjectInfo* info) {
2446 HeapEntry* wrapper_entry = filler_->FindEntry(wrapper);
2447 DCHECK(wrapper_entry != NULL);
2448 HeapEntry* info_entry =
2449 filler_->FindOrAddEntry(info, native_entries_allocator_);
2450 DCHECK(info_entry != NULL);
2451 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2452 wrapper_entry->index(),
2453 "native",
2454 info_entry);
2455 filler_->SetIndexedAutoIndexReference(HeapGraphEdge::kElement,
2456 info_entry->index(),
2457 wrapper_entry);
2458}
2459
2460
2461void NativeObjectsExplorer::SetRootNativeRootsReference() {
2462 for (HashMap::Entry* entry = native_groups_.Start();
2463 entry;
2464 entry = native_groups_.Next(entry)) {
2465 NativeGroupRetainedObjectInfo* group_info =
2466 static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2467 HeapEntry* group_entry =
2468 filler_->FindOrAddEntry(group_info, native_entries_allocator_);
2469 DCHECK(group_entry != NULL);
2470 filler_->SetIndexedAutoIndexReference(
2471 HeapGraphEdge::kElement,
2472 snapshot_->root()->index(),
2473 group_entry);
2474 }
2475}
2476
2477
2478void NativeObjectsExplorer::VisitSubtreeWrapper(Object** p, uint16_t class_id) {
2479 if (in_groups_.Contains(*p)) return;
2480 Isolate* isolate = isolate_;
2481 v8::RetainedObjectInfo* info =
2482 isolate->heap_profiler()->ExecuteWrapperClassCallback(class_id, p);
2483 if (info == NULL) return;
2484 GetListMaybeDisposeInfo(info)->Add(HeapObject::cast(*p));
2485}
2486
2487
2488HeapSnapshotGenerator::HeapSnapshotGenerator(
2489 HeapSnapshot* snapshot,
2490 v8::ActivityControl* control,
2491 v8::HeapProfiler::ObjectNameResolver* resolver,
2492 Heap* heap)
2493 : snapshot_(snapshot),
2494 control_(control),
2495 v8_heap_explorer_(snapshot_, this, resolver),
2496 dom_explorer_(snapshot_, this),
2497 heap_(heap) {
2498}
2499
2500
2501bool HeapSnapshotGenerator::GenerateSnapshot() {
2502 v8_heap_explorer_.TagGlobalObjects();
2503
2504 // TODO(1562) Profiler assumes that any object that is in the heap after
2505 // full GC is reachable from the root when computing dominators.
2506 // This is not true for weakly reachable objects.
2507 // As a temporary solution we call GC twice.
2508 heap_->CollectAllGarbage(
2509 Heap::kMakeHeapIterableMask,
2510 "HeapSnapshotGenerator::GenerateSnapshot");
2511 heap_->CollectAllGarbage(
2512 Heap::kMakeHeapIterableMask,
2513 "HeapSnapshotGenerator::GenerateSnapshot");
2514
2515#ifdef VERIFY_HEAP
2516 Heap* debug_heap = heap_;
2517 if (FLAG_verify_heap) {
2518 debug_heap->Verify();
2519 }
2520#endif
2521
2522 SetProgressTotal(2); // 2 passes.
2523
2524#ifdef VERIFY_HEAP
2525 if (FLAG_verify_heap) {
2526 debug_heap->Verify();
2527 }
2528#endif
2529
2530 snapshot_->AddSyntheticRootEntries();
2531
2532 if (!FillReferences()) return false;
2533
2534 snapshot_->FillChildren();
2535 snapshot_->RememberLastJSObjectId();
2536
2537 progress_counter_ = progress_total_;
2538 if (!ProgressReport(true)) return false;
2539 return true;
2540}
2541
2542
2543void HeapSnapshotGenerator::ProgressStep() {
2544 ++progress_counter_;
2545}
2546
2547
2548bool HeapSnapshotGenerator::ProgressReport(bool force) {
2549 const int kProgressReportGranularity = 10000;
2550 if (control_ != NULL
2551 && (force || progress_counter_ % kProgressReportGranularity == 0)) {
2552 return
2553 control_->ReportProgressValue(progress_counter_, progress_total_) ==
2554 v8::ActivityControl::kContinue;
2555 }
2556 return true;
2557}
2558
2559
2560void HeapSnapshotGenerator::SetProgressTotal(int iterations_count) {
2561 if (control_ == NULL) return;
2562 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
2563 progress_total_ = iterations_count * (
2564 v8_heap_explorer_.EstimateObjectsCount(&iterator) +
2565 dom_explorer_.EstimateObjectsCount());
2566 progress_counter_ = 0;
2567}
2568
2569
2570bool HeapSnapshotGenerator::FillReferences() {
2571 SnapshotFiller filler(snapshot_, &entries_);
2572 return v8_heap_explorer_.IterateAndExtractReferences(&filler)
2573 && dom_explorer_.IterateAndExtractReferences(&filler);
2574}
2575
2576
2577template<int bytes> struct MaxDecimalDigitsIn;
2578template<> struct MaxDecimalDigitsIn<4> {
2579 static const int kSigned = 11;
2580 static const int kUnsigned = 10;
2581};
2582template<> struct MaxDecimalDigitsIn<8> {
2583 static const int kSigned = 20;
2584 static const int kUnsigned = 20;
2585};
2586
2587
2588class OutputStreamWriter {
2589 public:
2590 explicit OutputStreamWriter(v8::OutputStream* stream)
2591 : stream_(stream),
2592 chunk_size_(stream->GetChunkSize()),
2593 chunk_(chunk_size_),
2594 chunk_pos_(0),
2595 aborted_(false) {
2596 DCHECK(chunk_size_ > 0);
2597 }
2598 bool aborted() { return aborted_; }
2599 void AddCharacter(char c) {
2600 DCHECK(c != '\0');
2601 DCHECK(chunk_pos_ < chunk_size_);
2602 chunk_[chunk_pos_++] = c;
2603 MaybeWriteChunk();
2604 }
2605 void AddString(const char* s) {
2606 AddSubstring(s, StrLength(s));
2607 }
2608 void AddSubstring(const char* s, int n) {
2609 if (n <= 0) return;
2610 DCHECK(static_cast<size_t>(n) <= strlen(s));
2611 const char* s_end = s + n;
2612 while (s < s_end) {
2613 int s_chunk_size =
2614 Min(chunk_size_ - chunk_pos_, static_cast<int>(s_end - s));
2615 DCHECK(s_chunk_size > 0);
2616 MemCopy(chunk_.start() + chunk_pos_, s, s_chunk_size);
2617 s += s_chunk_size;
2618 chunk_pos_ += s_chunk_size;
2619 MaybeWriteChunk();
2620 }
2621 }
2622 void AddNumber(unsigned n) { AddNumberImpl<unsigned>(n, "%u"); }
2623 void Finalize() {
2624 if (aborted_) return;
2625 DCHECK(chunk_pos_ < chunk_size_);
2626 if (chunk_pos_ != 0) {
2627 WriteChunk();
2628 }
2629 stream_->EndOfStream();
2630 }
2631
2632 private:
2633 template<typename T>
2634 void AddNumberImpl(T n, const char* format) {
2635 // Buffer for the longest value plus trailing \0
2636 static const int kMaxNumberSize =
2637 MaxDecimalDigitsIn<sizeof(T)>::kUnsigned + 1;
2638 if (chunk_size_ - chunk_pos_ >= kMaxNumberSize) {
2639 int result = SNPrintF(
2640 chunk_.SubVector(chunk_pos_, chunk_size_), format, n);
2641 DCHECK(result != -1);
2642 chunk_pos_ += result;
2643 MaybeWriteChunk();
2644 } else {
2645 EmbeddedVector<char, kMaxNumberSize> buffer;
2646 int result = SNPrintF(buffer, format, n);
2647 USE(result);
2648 DCHECK(result != -1);
2649 AddString(buffer.start());
2650 }
2651 }
2652 void MaybeWriteChunk() {
2653 DCHECK(chunk_pos_ <= chunk_size_);
2654 if (chunk_pos_ == chunk_size_) {
2655 WriteChunk();
2656 }
2657 }
2658 void WriteChunk() {
2659 if (aborted_) return;
2660 if (stream_->WriteAsciiChunk(chunk_.start(), chunk_pos_) ==
2661 v8::OutputStream::kAbort) aborted_ = true;
2662 chunk_pos_ = 0;
2663 }
2664
2665 v8::OutputStream* stream_;
2666 int chunk_size_;
2667 ScopedVector<char> chunk_;
2668 int chunk_pos_;
2669 bool aborted_;
2670};
2671
2672
2673// type, name|index, to_node.
2674const int HeapSnapshotJSONSerializer::kEdgeFieldsCount = 3;
2675// type, name, id, self_size, edge_count, trace_node_id.
2676const int HeapSnapshotJSONSerializer::kNodeFieldsCount = 6;
2677
2678void HeapSnapshotJSONSerializer::Serialize(v8::OutputStream* stream) {
2679 if (AllocationTracker* allocation_tracker =
2680 snapshot_->profiler()->allocation_tracker()) {
2681 allocation_tracker->PrepareForSerialization();
2682 }
2683 DCHECK(writer_ == NULL);
2684 writer_ = new OutputStreamWriter(stream);
2685 SerializeImpl();
2686 delete writer_;
2687 writer_ = NULL;
2688}
2689
2690
2691void HeapSnapshotJSONSerializer::SerializeImpl() {
2692 DCHECK(0 == snapshot_->root()->index());
2693 writer_->AddCharacter('{');
2694 writer_->AddString("\"snapshot\":{");
2695 SerializeSnapshot();
2696 if (writer_->aborted()) return;
2697 writer_->AddString("},\n");
2698 writer_->AddString("\"nodes\":[");
2699 SerializeNodes();
2700 if (writer_->aborted()) return;
2701 writer_->AddString("],\n");
2702 writer_->AddString("\"edges\":[");
2703 SerializeEdges();
2704 if (writer_->aborted()) return;
2705 writer_->AddString("],\n");
2706
2707 writer_->AddString("\"trace_function_infos\":[");
2708 SerializeTraceNodeInfos();
2709 if (writer_->aborted()) return;
2710 writer_->AddString("],\n");
2711 writer_->AddString("\"trace_tree\":[");
2712 SerializeTraceTree();
2713 if (writer_->aborted()) return;
2714 writer_->AddString("],\n");
2715
2716 writer_->AddString("\"samples\":[");
2717 SerializeSamples();
2718 if (writer_->aborted()) return;
2719 writer_->AddString("],\n");
2720
2721 writer_->AddString("\"strings\":[");
2722 SerializeStrings();
2723 if (writer_->aborted()) return;
2724 writer_->AddCharacter(']');
2725 writer_->AddCharacter('}');
2726 writer_->Finalize();
2727}
2728
2729
2730int HeapSnapshotJSONSerializer::GetStringId(const char* s) {
2731 HashMap::Entry* cache_entry =
2732 strings_.LookupOrInsert(const_cast<char*>(s), StringHash(s));
2733 if (cache_entry->value == NULL) {
2734 cache_entry->value = reinterpret_cast<void*>(next_string_id_++);
2735 }
2736 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2737}
2738
2739
2740namespace {
2741
2742template<size_t size> struct ToUnsigned;
2743
2744template<> struct ToUnsigned<4> {
2745 typedef uint32_t Type;
2746};
2747
2748template<> struct ToUnsigned<8> {
2749 typedef uint64_t Type;
2750};
2751
2752} // namespace
2753
2754
2755template<typename T>
2756static int utoa_impl(T value, const Vector<char>& buffer, int buffer_pos) {
2757 STATIC_ASSERT(static_cast<T>(-1) > 0); // Check that T is unsigned
2758 int number_of_digits = 0;
2759 T t = value;
2760 do {
2761 ++number_of_digits;
2762 } while (t /= 10);
2763
2764 buffer_pos += number_of_digits;
2765 int result = buffer_pos;
2766 do {
2767 int last_digit = static_cast<int>(value % 10);
2768 buffer[--buffer_pos] = '0' + last_digit;
2769 value /= 10;
2770 } while (value);
2771 return result;
2772}
2773
2774
2775template<typename T>
2776static int utoa(T value, const Vector<char>& buffer, int buffer_pos) {
2777 typename ToUnsigned<sizeof(value)>::Type unsigned_value = value;
2778 STATIC_ASSERT(sizeof(value) == sizeof(unsigned_value));
2779 return utoa_impl(unsigned_value, buffer, buffer_pos);
2780}
2781
2782
2783void HeapSnapshotJSONSerializer::SerializeEdge(HeapGraphEdge* edge,
2784 bool first_edge) {
2785 // The buffer needs space for 3 unsigned ints, 3 commas, \n and \0
2786 static const int kBufferSize =
2787 MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned * 3 + 3 + 2; // NOLINT
2788 EmbeddedVector<char, kBufferSize> buffer;
2789 int edge_name_or_index = edge->type() == HeapGraphEdge::kElement
2790 || edge->type() == HeapGraphEdge::kHidden
2791 ? edge->index() : GetStringId(edge->name());
2792 int buffer_pos = 0;
2793 if (!first_edge) {
2794 buffer[buffer_pos++] = ',';
2795 }
2796 buffer_pos = utoa(edge->type(), buffer, buffer_pos);
2797 buffer[buffer_pos++] = ',';
2798 buffer_pos = utoa(edge_name_or_index, buffer, buffer_pos);
2799 buffer[buffer_pos++] = ',';
2800 buffer_pos = utoa(entry_index(edge->to()), buffer, buffer_pos);
2801 buffer[buffer_pos++] = '\n';
2802 buffer[buffer_pos++] = '\0';
2803 writer_->AddString(buffer.start());
2804}
2805
2806
2807void HeapSnapshotJSONSerializer::SerializeEdges() {
2808 List<HeapGraphEdge*>& edges = snapshot_->children();
2809 for (int i = 0; i < edges.length(); ++i) {
2810 DCHECK(i == 0 ||
2811 edges[i - 1]->from()->index() <= edges[i]->from()->index());
2812 SerializeEdge(edges[i], i == 0);
2813 if (writer_->aborted()) return;
2814 }
2815}
2816
2817
2818void HeapSnapshotJSONSerializer::SerializeNode(HeapEntry* entry) {
2819 // The buffer needs space for 4 unsigned ints, 1 size_t, 5 commas, \n and \0
2820 static const int kBufferSize =
2821 5 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2822 + MaxDecimalDigitsIn<sizeof(size_t)>::kUnsigned // NOLINT
2823 + 6 + 1 + 1;
2824 EmbeddedVector<char, kBufferSize> buffer;
2825 int buffer_pos = 0;
2826 if (entry_index(entry) != 0) {
2827 buffer[buffer_pos++] = ',';
2828 }
2829 buffer_pos = utoa(entry->type(), buffer, buffer_pos);
2830 buffer[buffer_pos++] = ',';
2831 buffer_pos = utoa(GetStringId(entry->name()), buffer, buffer_pos);
2832 buffer[buffer_pos++] = ',';
2833 buffer_pos = utoa(entry->id(), buffer, buffer_pos);
2834 buffer[buffer_pos++] = ',';
2835 buffer_pos = utoa(entry->self_size(), buffer, buffer_pos);
2836 buffer[buffer_pos++] = ',';
2837 buffer_pos = utoa(entry->children_count(), buffer, buffer_pos);
2838 buffer[buffer_pos++] = ',';
2839 buffer_pos = utoa(entry->trace_node_id(), buffer, buffer_pos);
2840 buffer[buffer_pos++] = '\n';
2841 buffer[buffer_pos++] = '\0';
2842 writer_->AddString(buffer.start());
2843}
2844
2845
2846void HeapSnapshotJSONSerializer::SerializeNodes() {
2847 List<HeapEntry>& entries = snapshot_->entries();
2848 for (int i = 0; i < entries.length(); ++i) {
2849 SerializeNode(&entries[i]);
2850 if (writer_->aborted()) return;
2851 }
2852}
2853
2854
2855void HeapSnapshotJSONSerializer::SerializeSnapshot() {
2856 writer_->AddString("\"meta\":");
2857 // The object describing node serialization layout.
2858 // We use a set of macros to improve readability.
2859#define JSON_A(s) "[" s "]"
2860#define JSON_O(s) "{" s "}"
2861#define JSON_S(s) "\"" s "\""
2862 writer_->AddString(JSON_O(
2863 JSON_S("node_fields") ":" JSON_A(
2864 JSON_S("type") ","
2865 JSON_S("name") ","
2866 JSON_S("id") ","
2867 JSON_S("self_size") ","
2868 JSON_S("edge_count") ","
2869 JSON_S("trace_node_id")) ","
2870 JSON_S("node_types") ":" JSON_A(
2871 JSON_A(
2872 JSON_S("hidden") ","
2873 JSON_S("array") ","
2874 JSON_S("string") ","
2875 JSON_S("object") ","
2876 JSON_S("code") ","
2877 JSON_S("closure") ","
2878 JSON_S("regexp") ","
2879 JSON_S("number") ","
2880 JSON_S("native") ","
2881 JSON_S("synthetic") ","
2882 JSON_S("concatenated string") ","
2883 JSON_S("sliced string")) ","
2884 JSON_S("string") ","
2885 JSON_S("number") ","
2886 JSON_S("number") ","
2887 JSON_S("number") ","
2888 JSON_S("number") ","
2889 JSON_S("number")) ","
2890 JSON_S("edge_fields") ":" JSON_A(
2891 JSON_S("type") ","
2892 JSON_S("name_or_index") ","
2893 JSON_S("to_node")) ","
2894 JSON_S("edge_types") ":" JSON_A(
2895 JSON_A(
2896 JSON_S("context") ","
2897 JSON_S("element") ","
2898 JSON_S("property") ","
2899 JSON_S("internal") ","
2900 JSON_S("hidden") ","
2901 JSON_S("shortcut") ","
2902 JSON_S("weak")) ","
2903 JSON_S("string_or_number") ","
2904 JSON_S("node")) ","
2905 JSON_S("trace_function_info_fields") ":" JSON_A(
2906 JSON_S("function_id") ","
2907 JSON_S("name") ","
2908 JSON_S("script_name") ","
2909 JSON_S("script_id") ","
2910 JSON_S("line") ","
2911 JSON_S("column")) ","
2912 JSON_S("trace_node_fields") ":" JSON_A(
2913 JSON_S("id") ","
2914 JSON_S("function_info_index") ","
2915 JSON_S("count") ","
2916 JSON_S("size") ","
2917 JSON_S("children")) ","
2918 JSON_S("sample_fields") ":" JSON_A(
2919 JSON_S("timestamp_us") ","
2920 JSON_S("last_assigned_id"))));
2921#undef JSON_S
2922#undef JSON_O
2923#undef JSON_A
2924 writer_->AddString(",\"node_count\":");
2925 writer_->AddNumber(snapshot_->entries().length());
2926 writer_->AddString(",\"edge_count\":");
2927 writer_->AddNumber(snapshot_->edges().length());
2928 writer_->AddString(",\"trace_function_count\":");
2929 uint32_t count = 0;
2930 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
2931 if (tracker) {
2932 count = tracker->function_info_list().length();
2933 }
2934 writer_->AddNumber(count);
2935}
2936
2937
2938static void WriteUChar(OutputStreamWriter* w, unibrow::uchar u) {
2939 static const char hex_chars[] = "0123456789ABCDEF";
2940 w->AddString("\\u");
2941 w->AddCharacter(hex_chars[(u >> 12) & 0xf]);
2942 w->AddCharacter(hex_chars[(u >> 8) & 0xf]);
2943 w->AddCharacter(hex_chars[(u >> 4) & 0xf]);
2944 w->AddCharacter(hex_chars[u & 0xf]);
2945}
2946
2947
2948void HeapSnapshotJSONSerializer::SerializeTraceTree() {
2949 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
2950 if (!tracker) return;
2951 AllocationTraceTree* traces = tracker->trace_tree();
2952 SerializeTraceNode(traces->root());
2953}
2954
2955
2956void HeapSnapshotJSONSerializer::SerializeTraceNode(AllocationTraceNode* node) {
2957 // The buffer needs space for 4 unsigned ints, 4 commas, [ and \0
2958 const int kBufferSize =
2959 4 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2960 + 4 + 1 + 1;
2961 EmbeddedVector<char, kBufferSize> buffer;
2962 int buffer_pos = 0;
2963 buffer_pos = utoa(node->id(), buffer, buffer_pos);
2964 buffer[buffer_pos++] = ',';
2965 buffer_pos = utoa(node->function_info_index(), buffer, buffer_pos);
2966 buffer[buffer_pos++] = ',';
2967 buffer_pos = utoa(node->allocation_count(), buffer, buffer_pos);
2968 buffer[buffer_pos++] = ',';
2969 buffer_pos = utoa(node->allocation_size(), buffer, buffer_pos);
2970 buffer[buffer_pos++] = ',';
2971 buffer[buffer_pos++] = '[';
2972 buffer[buffer_pos++] = '\0';
2973 writer_->AddString(buffer.start());
2974
2975 Vector<AllocationTraceNode*> children = node->children();
2976 for (int i = 0; i < children.length(); i++) {
2977 if (i > 0) {
2978 writer_->AddCharacter(',');
2979 }
2980 SerializeTraceNode(children[i]);
2981 }
2982 writer_->AddCharacter(']');
2983}
2984
2985
2986// 0-based position is converted to 1-based during the serialization.
2987static int SerializePosition(int position, const Vector<char>& buffer,
2988 int buffer_pos) {
2989 if (position == -1) {
2990 buffer[buffer_pos++] = '0';
2991 } else {
2992 DCHECK(position >= 0);
2993 buffer_pos = utoa(static_cast<unsigned>(position + 1), buffer, buffer_pos);
2994 }
2995 return buffer_pos;
2996}
2997
2998
2999void HeapSnapshotJSONSerializer::SerializeTraceNodeInfos() {
3000 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
3001 if (!tracker) return;
3002 // The buffer needs space for 6 unsigned ints, 6 commas, \n and \0
3003 const int kBufferSize =
3004 6 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
3005 + 6 + 1 + 1;
3006 EmbeddedVector<char, kBufferSize> buffer;
3007 const List<AllocationTracker::FunctionInfo*>& list =
3008 tracker->function_info_list();
3009 for (int i = 0; i < list.length(); i++) {
3010 AllocationTracker::FunctionInfo* info = list[i];
3011 int buffer_pos = 0;
3012 if (i > 0) {
3013 buffer[buffer_pos++] = ',';
3014 }
3015 buffer_pos = utoa(info->function_id, buffer, buffer_pos);
3016 buffer[buffer_pos++] = ',';
3017 buffer_pos = utoa(GetStringId(info->name), buffer, buffer_pos);
3018 buffer[buffer_pos++] = ',';
3019 buffer_pos = utoa(GetStringId(info->script_name), buffer, buffer_pos);
3020 buffer[buffer_pos++] = ',';
3021 // The cast is safe because script id is a non-negative Smi.
3022 buffer_pos = utoa(static_cast<unsigned>(info->script_id), buffer,
3023 buffer_pos);
3024 buffer[buffer_pos++] = ',';
3025 buffer_pos = SerializePosition(info->line, buffer, buffer_pos);
3026 buffer[buffer_pos++] = ',';
3027 buffer_pos = SerializePosition(info->column, buffer, buffer_pos);
3028 buffer[buffer_pos++] = '\n';
3029 buffer[buffer_pos++] = '\0';
3030 writer_->AddString(buffer.start());
3031 }
3032}
3033
3034
3035void HeapSnapshotJSONSerializer::SerializeSamples() {
3036 const List<HeapObjectsMap::TimeInterval>& samples =
3037 snapshot_->profiler()->heap_object_map()->samples();
3038 if (samples.is_empty()) return;
3039 base::TimeTicks start_time = samples[0].timestamp;
3040 // The buffer needs space for 2 unsigned ints, 2 commas, \n and \0
3041 const int kBufferSize = MaxDecimalDigitsIn<sizeof(
3042 base::TimeDelta().InMicroseconds())>::kUnsigned +
3043 MaxDecimalDigitsIn<sizeof(samples[0].id)>::kUnsigned +
3044 2 + 1 + 1;
3045 EmbeddedVector<char, kBufferSize> buffer;
3046 for (int i = 0; i < samples.length(); i++) {
3047 HeapObjectsMap::TimeInterval& sample = samples[i];
3048 int buffer_pos = 0;
3049 if (i > 0) {
3050 buffer[buffer_pos++] = ',';
3051 }
3052 base::TimeDelta time_delta = sample.timestamp - start_time;
3053 buffer_pos = utoa(time_delta.InMicroseconds(), buffer, buffer_pos);
3054 buffer[buffer_pos++] = ',';
3055 buffer_pos = utoa(sample.last_assigned_id(), buffer, buffer_pos);
3056 buffer[buffer_pos++] = '\n';
3057 buffer[buffer_pos++] = '\0';
3058 writer_->AddString(buffer.start());
3059 }
3060}
3061
3062
3063void HeapSnapshotJSONSerializer::SerializeString(const unsigned char* s) {
3064 writer_->AddCharacter('\n');
3065 writer_->AddCharacter('\"');
3066 for ( ; *s != '\0'; ++s) {
3067 switch (*s) {
3068 case '\b':
3069 writer_->AddString("\\b");
3070 continue;
3071 case '\f':
3072 writer_->AddString("\\f");
3073 continue;
3074 case '\n':
3075 writer_->AddString("\\n");
3076 continue;
3077 case '\r':
3078 writer_->AddString("\\r");
3079 continue;
3080 case '\t':
3081 writer_->AddString("\\t");
3082 continue;
3083 case '\"':
3084 case '\\':
3085 writer_->AddCharacter('\\');
3086 writer_->AddCharacter(*s);
3087 continue;
3088 default:
3089 if (*s > 31 && *s < 128) {
3090 writer_->AddCharacter(*s);
3091 } else if (*s <= 31) {
3092 // Special character with no dedicated literal.
3093 WriteUChar(writer_, *s);
3094 } else {
3095 // Convert UTF-8 into \u UTF-16 literal.
3096 size_t length = 1, cursor = 0;
3097 for ( ; length <= 4 && *(s + length) != '\0'; ++length) { }
3098 unibrow::uchar c = unibrow::Utf8::CalculateValue(s, length, &cursor);
3099 if (c != unibrow::Utf8::kBadChar) {
3100 WriteUChar(writer_, c);
3101 DCHECK(cursor != 0);
3102 s += cursor - 1;
3103 } else {
3104 writer_->AddCharacter('?');
3105 }
3106 }
3107 }
3108 }
3109 writer_->AddCharacter('\"');
3110}
3111
3112
3113void HeapSnapshotJSONSerializer::SerializeStrings() {
3114 ScopedVector<const unsigned char*> sorted_strings(
3115 strings_.occupancy() + 1);
3116 for (HashMap::Entry* entry = strings_.Start();
3117 entry != NULL;
3118 entry = strings_.Next(entry)) {
3119 int index = static_cast<int>(reinterpret_cast<uintptr_t>(entry->value));
3120 sorted_strings[index] = reinterpret_cast<const unsigned char*>(entry->key);
3121 }
3122 writer_->AddString("\"<dummy>\"");
3123 for (int i = 1; i < sorted_strings.length(); ++i) {
3124 writer_->AddCharacter(',');
3125 SerializeString(sorted_strings[i]);
3126 if (writer_->aborted()) return;
3127 }
3128}
3129
3130
3131} // namespace internal
3132} // namespace v8