Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1230)

Side by Side Diff: src/heap-snapshot-generator.cc

Issue 1356223004: Move heap and CPU profilers into a dedicated directory. (Closed) Base URL: https://chromium.googlesource.com/v8/v8.git@master
Patch Set: rebaseline Created 5 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « src/heap-snapshot-generator.h ('k') | src/heap-snapshot-generator-inl.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // 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/heap-snapshot-generator.h"
6
7 #include "src/allocation-tracker.h"
8 #include "src/code-stubs.h"
9 #include "src/conversions.h"
10 #include "src/debug/debug.h"
11 #include "src/heap-profiler.h"
12 #include "src/heap-snapshot-generator-inl.h"
13 #include "src/types.h"
14
15 namespace v8 {
16 namespace internal {
17
18
19 HeapGraphEdge::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
31 HeapGraphEdge::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
39 void HeapGraphEdge::ReplaceToIndexWithEntry(HeapSnapshot* snapshot) {
40 to_entry_ = &snapshot->entries()[to_index_];
41 }
42
43
44 const int HeapEntry::kNoEntry = -1;
45
46 HeapEntry::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
62 void 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
71 void 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
80 void HeapEntry::Print(
81 const char* prefix, const char* edge_name, int max_depth, int indent) {
82 STATIC_ASSERT(sizeof(unsigned) == sizeof(id()));
83 base::OS::Print("%6" V8PRIuPTR " @%6u %*c %s%s: ", self_size(), id(), indent,
84 ' ', 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
141 const 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.
164 namespace { // Avoid littering the global namespace.
165
166 template <size_t ptr_size> struct SnapshotSizeConstants;
167
168 template <> struct SnapshotSizeConstants<4> {
169 static const int kExpectedHeapGraphEdgeSize = 12;
170 static const int kExpectedHeapEntrySize = 28;
171 };
172
173 template <> struct SnapshotSizeConstants<8> {
174 static const int kExpectedHeapGraphEdgeSize = 24;
175 static const int kExpectedHeapEntrySize = 40;
176 };
177
178 } // namespace
179
180
181 HeapSnapshot::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
202 void HeapSnapshot::Delete() {
203 profiler_->RemoveSnapshot(this);
204 delete this;
205 }
206
207
208 void HeapSnapshot::RememberLastJSObjectId() {
209 max_snapshot_js_object_id_ = profiler_->heap_object_map()->last_assigned_id();
210 }
211
212
213 void 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
225 HeapEntry* 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
239 HeapEntry* 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
251 HeapEntry* 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
261 HeapEntry* 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
272 void 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
289 class 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
301 HeapEntry* 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
311 template<class T>
312 static 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
319 List<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
332 void HeapSnapshot::Print(int max_depth) {
333 root()->Print("", "", max_depth, 0);
334 }
335
336
337 size_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.
349 const SnapshotObjectId HeapObjectsMap::kInternalRootObjectId = 1;
350 const SnapshotObjectId HeapObjectsMap::kGcRootsObjectId =
351 HeapObjectsMap::kInternalRootObjectId + HeapObjectsMap::kObjectIdStep;
352 const SnapshotObjectId HeapObjectsMap::kGcRootsFirstSubrootId =
353 HeapObjectsMap::kGcRootsObjectId + HeapObjectsMap::kObjectIdStep;
354 const SnapshotObjectId HeapObjectsMap::kFirstAvailableObjectId =
355 HeapObjectsMap::kGcRootsFirstSubrootId +
356 VisitorSynchronization::kNumberOfSyncTags * HeapObjectsMap::kObjectIdStep;
357
358
359 static bool AddressesMatch(void* key1, void* key2) {
360 return key1 == key2;
361 }
362
363
364 HeapObjectsMap::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
379 bool 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
427 void HeapObjectsMap::UpdateObjectSize(Address addr, int size) {
428 FindOrAddEntry(addr, size, false);
429 }
430
431
432 SnapshotObjectId 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
442 SnapshotObjectId 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
471 void HeapObjectsMap::StopHeapObjectsTracking() {
472 time_intervals_.Clear();
473 }
474
475
476 void 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
503 namespace {
504
505
506 struct 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
539 static 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
549 int 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
614 SnapshotObjectId 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
665 void 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
695 SnapshotObjectId 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
709 size_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
718 HeapEntriesMap::HeapEntriesMap()
719 : entries_(HashMap::PointersMatch) {
720 }
721
722
723 int 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
730 void 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
737 HeapObjectsSet::HeapObjectsSet()
738 : entries_(HashMap::PointersMatch) {
739 }
740
741
742 void HeapObjectsSet::Clear() {
743 entries_.Clear();
744 }
745
746
747 bool 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
754 void 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
761 const 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
771 void 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
780 V8HeapExplorer::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
794 V8HeapExplorer::~V8HeapExplorer() {
795 }
796
797
798 HeapEntry* V8HeapExplorer::AllocateEntry(HeapThing ptr) {
799 return AddEntry(reinterpret_cast<HeapObject*>(ptr));
800 }
801
802
803 HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object) {
804 if (object->IsJSFunction()) {
805 JSFunction* func = JSFunction::cast(object);
806 SharedFunctionInfo* shared = func->shared();
807 const char* name = shared->bound() ? "native_bind" :
808 names_->GetName(String::cast(shared->name()));
809 return AddEntry(object, HeapEntry::kClosure, name);
810 } else if (object->IsJSRegExp()) {
811 JSRegExp* re = JSRegExp::cast(object);
812 return AddEntry(object,
813 HeapEntry::kRegExp,
814 names_->GetName(re->Pattern()));
815 } else if (object->IsJSObject()) {
816 const char* name = names_->GetName(
817 GetConstructorName(JSObject::cast(object)));
818 if (object->IsJSGlobalObject()) {
819 const char* tag = objects_tags_.GetTag(object);
820 if (tag != NULL) {
821 name = names_->GetFormatted("%s / %s", name, tag);
822 }
823 }
824 return AddEntry(object, HeapEntry::kObject, name);
825 } else if (object->IsString()) {
826 String* string = String::cast(object);
827 if (string->IsConsString())
828 return AddEntry(object,
829 HeapEntry::kConsString,
830 "(concatenated string)");
831 if (string->IsSlicedString())
832 return AddEntry(object,
833 HeapEntry::kSlicedString,
834 "(sliced string)");
835 return AddEntry(object,
836 HeapEntry::kString,
837 names_->GetName(String::cast(object)));
838 } else if (object->IsSymbol()) {
839 return AddEntry(object, HeapEntry::kSymbol, "symbol");
840 } else if (object->IsCode()) {
841 return AddEntry(object, HeapEntry::kCode, "");
842 } else if (object->IsSharedFunctionInfo()) {
843 String* name = String::cast(SharedFunctionInfo::cast(object)->name());
844 return AddEntry(object,
845 HeapEntry::kCode,
846 names_->GetName(name));
847 } else if (object->IsScript()) {
848 Object* name = Script::cast(object)->name();
849 return AddEntry(object,
850 HeapEntry::kCode,
851 name->IsString()
852 ? names_->GetName(String::cast(name))
853 : "");
854 } else if (object->IsNativeContext()) {
855 return AddEntry(object, HeapEntry::kHidden, "system / NativeContext");
856 } else if (object->IsContext()) {
857 return AddEntry(object, HeapEntry::kObject, "system / Context");
858 } else if (object->IsFixedArray() || object->IsFixedDoubleArray() ||
859 object->IsByteArray()) {
860 return AddEntry(object, HeapEntry::kArray, "");
861 } else if (object->IsHeapNumber()) {
862 return AddEntry(object, HeapEntry::kHeapNumber, "number");
863 } else if (object->IsSimd128Value()) {
864 return AddEntry(object, HeapEntry::kSimdValue, "simd");
865 }
866 return AddEntry(object, HeapEntry::kHidden, GetSystemEntryName(object));
867 }
868
869
870 HeapEntry* V8HeapExplorer::AddEntry(HeapObject* object,
871 HeapEntry::Type type,
872 const char* name) {
873 return AddEntry(object->address(), type, name, object->Size());
874 }
875
876
877 HeapEntry* V8HeapExplorer::AddEntry(Address address,
878 HeapEntry::Type type,
879 const char* name,
880 size_t size) {
881 SnapshotObjectId object_id = heap_object_map_->FindOrAddEntry(
882 address, static_cast<unsigned int>(size));
883 unsigned trace_node_id = 0;
884 if (AllocationTracker* allocation_tracker =
885 snapshot_->profiler()->allocation_tracker()) {
886 trace_node_id =
887 allocation_tracker->address_to_trace()->GetTraceNodeId(address);
888 }
889 return snapshot_->AddEntry(type, name, object_id, size, trace_node_id);
890 }
891
892
893 class SnapshotFiller {
894 public:
895 explicit SnapshotFiller(HeapSnapshot* snapshot, HeapEntriesMap* entries)
896 : snapshot_(snapshot),
897 names_(snapshot->profiler()->names()),
898 entries_(entries) { }
899 HeapEntry* AddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
900 HeapEntry* entry = allocator->AllocateEntry(ptr);
901 entries_->Pair(ptr, entry->index());
902 return entry;
903 }
904 HeapEntry* FindEntry(HeapThing ptr) {
905 int index = entries_->Map(ptr);
906 return index != HeapEntry::kNoEntry ? &snapshot_->entries()[index] : NULL;
907 }
908 HeapEntry* FindOrAddEntry(HeapThing ptr, HeapEntriesAllocator* allocator) {
909 HeapEntry* entry = FindEntry(ptr);
910 return entry != NULL ? entry : AddEntry(ptr, allocator);
911 }
912 void SetIndexedReference(HeapGraphEdge::Type type,
913 int parent,
914 int index,
915 HeapEntry* child_entry) {
916 HeapEntry* parent_entry = &snapshot_->entries()[parent];
917 parent_entry->SetIndexedReference(type, index, child_entry);
918 }
919 void SetIndexedAutoIndexReference(HeapGraphEdge::Type type,
920 int parent,
921 HeapEntry* child_entry) {
922 HeapEntry* parent_entry = &snapshot_->entries()[parent];
923 int index = parent_entry->children_count() + 1;
924 parent_entry->SetIndexedReference(type, index, child_entry);
925 }
926 void SetNamedReference(HeapGraphEdge::Type type,
927 int parent,
928 const char* reference_name,
929 HeapEntry* child_entry) {
930 HeapEntry* parent_entry = &snapshot_->entries()[parent];
931 parent_entry->SetNamedReference(type, reference_name, child_entry);
932 }
933 void SetNamedAutoIndexReference(HeapGraphEdge::Type type,
934 int parent,
935 HeapEntry* child_entry) {
936 HeapEntry* parent_entry = &snapshot_->entries()[parent];
937 int index = parent_entry->children_count() + 1;
938 parent_entry->SetNamedReference(
939 type,
940 names_->GetName(index),
941 child_entry);
942 }
943
944 private:
945 HeapSnapshot* snapshot_;
946 StringsStorage* names_;
947 HeapEntriesMap* entries_;
948 };
949
950
951 const char* V8HeapExplorer::GetSystemEntryName(HeapObject* object) {
952 switch (object->map()->instance_type()) {
953 case MAP_TYPE:
954 switch (Map::cast(object)->instance_type()) {
955 #define MAKE_STRING_MAP_CASE(instance_type, size, name, Name) \
956 case instance_type: return "system / Map (" #Name ")";
957 STRING_TYPE_LIST(MAKE_STRING_MAP_CASE)
958 #undef MAKE_STRING_MAP_CASE
959 default: return "system / Map";
960 }
961 case CELL_TYPE: return "system / Cell";
962 case PROPERTY_CELL_TYPE: return "system / PropertyCell";
963 case FOREIGN_TYPE: return "system / Foreign";
964 case ODDBALL_TYPE: return "system / Oddball";
965 #define MAKE_STRUCT_CASE(NAME, Name, name) \
966 case NAME##_TYPE: return "system / "#Name;
967 STRUCT_LIST(MAKE_STRUCT_CASE)
968 #undef MAKE_STRUCT_CASE
969 default: return "system";
970 }
971 }
972
973
974 int V8HeapExplorer::EstimateObjectsCount(HeapIterator* iterator) {
975 int objects_count = 0;
976 for (HeapObject* obj = iterator->next();
977 obj != NULL;
978 obj = iterator->next()) {
979 objects_count++;
980 }
981 return objects_count;
982 }
983
984
985 class IndexedReferencesExtractor : public ObjectVisitor {
986 public:
987 IndexedReferencesExtractor(V8HeapExplorer* generator,
988 HeapObject* parent_obj,
989 int parent)
990 : generator_(generator),
991 parent_obj_(parent_obj),
992 parent_(parent),
993 next_index_(0) {
994 }
995 void VisitCodeEntry(Address entry_address) {
996 Code* code = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
997 generator_->SetInternalReference(parent_obj_, parent_, "code", code);
998 generator_->TagCodeObject(code);
999 }
1000 void VisitPointers(Object** start, Object** end) {
1001 for (Object** p = start; p < end; p++) {
1002 ++next_index_;
1003 if (CheckVisitedAndUnmark(p)) continue;
1004 generator_->SetHiddenReference(parent_obj_, parent_, next_index_, *p);
1005 }
1006 }
1007 static void MarkVisitedField(HeapObject* obj, int offset) {
1008 if (offset < 0) return;
1009 Address field = obj->address() + offset;
1010 DCHECK(Memory::Object_at(field)->IsHeapObject());
1011 intptr_t p = reinterpret_cast<intptr_t>(Memory::Object_at(field));
1012 DCHECK(!IsMarked(p));
1013 intptr_t p_tagged = p | kTag;
1014 Memory::Object_at(field) = reinterpret_cast<Object*>(p_tagged);
1015 }
1016
1017 private:
1018 bool CheckVisitedAndUnmark(Object** field) {
1019 intptr_t p = reinterpret_cast<intptr_t>(*field);
1020 if (IsMarked(p)) {
1021 intptr_t p_untagged = (p & ~kTaggingMask) | kHeapObjectTag;
1022 *field = reinterpret_cast<Object*>(p_untagged);
1023 DCHECK((*field)->IsHeapObject());
1024 return true;
1025 }
1026 return false;
1027 }
1028
1029 static const intptr_t kTaggingMask = 3;
1030 static const intptr_t kTag = 3;
1031
1032 static bool IsMarked(intptr_t p) { return (p & kTaggingMask) == kTag; }
1033
1034 V8HeapExplorer* generator_;
1035 HeapObject* parent_obj_;
1036 int parent_;
1037 int next_index_;
1038 };
1039
1040
1041 bool V8HeapExplorer::ExtractReferencesPass1(int entry, HeapObject* obj) {
1042 if (obj->IsFixedArray()) return false; // FixedArrays are processed on pass 2
1043
1044 if (obj->IsJSGlobalProxy()) {
1045 ExtractJSGlobalProxyReferences(entry, JSGlobalProxy::cast(obj));
1046 } else if (obj->IsJSArrayBuffer()) {
1047 ExtractJSArrayBufferReferences(entry, JSArrayBuffer::cast(obj));
1048 } else if (obj->IsJSObject()) {
1049 if (obj->IsJSWeakSet()) {
1050 ExtractJSWeakCollectionReferences(entry, JSWeakSet::cast(obj));
1051 } else if (obj->IsJSWeakMap()) {
1052 ExtractJSWeakCollectionReferences(entry, JSWeakMap::cast(obj));
1053 } else if (obj->IsJSSet()) {
1054 ExtractJSCollectionReferences(entry, JSSet::cast(obj));
1055 } else if (obj->IsJSMap()) {
1056 ExtractJSCollectionReferences(entry, JSMap::cast(obj));
1057 }
1058 ExtractJSObjectReferences(entry, JSObject::cast(obj));
1059 } else if (obj->IsString()) {
1060 ExtractStringReferences(entry, String::cast(obj));
1061 } else if (obj->IsSymbol()) {
1062 ExtractSymbolReferences(entry, Symbol::cast(obj));
1063 } else if (obj->IsMap()) {
1064 ExtractMapReferences(entry, Map::cast(obj));
1065 } else if (obj->IsSharedFunctionInfo()) {
1066 ExtractSharedFunctionInfoReferences(entry, SharedFunctionInfo::cast(obj));
1067 } else if (obj->IsScript()) {
1068 ExtractScriptReferences(entry, Script::cast(obj));
1069 } else if (obj->IsAccessorInfo()) {
1070 ExtractAccessorInfoReferences(entry, AccessorInfo::cast(obj));
1071 } else if (obj->IsAccessorPair()) {
1072 ExtractAccessorPairReferences(entry, AccessorPair::cast(obj));
1073 } else if (obj->IsCodeCache()) {
1074 ExtractCodeCacheReferences(entry, CodeCache::cast(obj));
1075 } else if (obj->IsCode()) {
1076 ExtractCodeReferences(entry, Code::cast(obj));
1077 } else if (obj->IsBox()) {
1078 ExtractBoxReferences(entry, Box::cast(obj));
1079 } else if (obj->IsCell()) {
1080 ExtractCellReferences(entry, Cell::cast(obj));
1081 } else if (obj->IsPropertyCell()) {
1082 ExtractPropertyCellReferences(entry, PropertyCell::cast(obj));
1083 } else if (obj->IsAllocationSite()) {
1084 ExtractAllocationSiteReferences(entry, AllocationSite::cast(obj));
1085 }
1086 return true;
1087 }
1088
1089
1090 bool V8HeapExplorer::ExtractReferencesPass2(int entry, HeapObject* obj) {
1091 if (!obj->IsFixedArray()) return false;
1092
1093 if (obj->IsContext()) {
1094 ExtractContextReferences(entry, Context::cast(obj));
1095 } else {
1096 ExtractFixedArrayReferences(entry, FixedArray::cast(obj));
1097 }
1098 return true;
1099 }
1100
1101
1102 void V8HeapExplorer::ExtractJSGlobalProxyReferences(
1103 int entry, JSGlobalProxy* proxy) {
1104 SetInternalReference(proxy, entry,
1105 "native_context", proxy->native_context(),
1106 JSGlobalProxy::kNativeContextOffset);
1107 }
1108
1109
1110 void V8HeapExplorer::ExtractJSObjectReferences(
1111 int entry, JSObject* js_obj) {
1112 HeapObject* obj = js_obj;
1113 ExtractClosureReferences(js_obj, entry);
1114 ExtractPropertyReferences(js_obj, entry);
1115 ExtractElementReferences(js_obj, entry);
1116 ExtractInternalReferences(js_obj, entry);
1117 PrototypeIterator iter(heap_->isolate(), js_obj);
1118 SetPropertyReference(obj, entry, heap_->proto_string(), iter.GetCurrent());
1119 if (obj->IsJSFunction()) {
1120 JSFunction* js_fun = JSFunction::cast(js_obj);
1121 Object* proto_or_map = js_fun->prototype_or_initial_map();
1122 if (!proto_or_map->IsTheHole()) {
1123 if (!proto_or_map->IsMap()) {
1124 SetPropertyReference(
1125 obj, entry,
1126 heap_->prototype_string(), proto_or_map,
1127 NULL,
1128 JSFunction::kPrototypeOrInitialMapOffset);
1129 } else {
1130 SetPropertyReference(
1131 obj, entry,
1132 heap_->prototype_string(), js_fun->prototype());
1133 SetInternalReference(
1134 obj, entry, "initial_map", proto_or_map,
1135 JSFunction::kPrototypeOrInitialMapOffset);
1136 }
1137 }
1138 SharedFunctionInfo* shared_info = js_fun->shared();
1139 // JSFunction has either bindings or literals and never both.
1140 bool bound = shared_info->bound();
1141 TagObject(js_fun->literals_or_bindings(),
1142 bound ? "(function bindings)" : "(function literals)");
1143 SetInternalReference(js_fun, entry,
1144 bound ? "bindings" : "literals",
1145 js_fun->literals_or_bindings(),
1146 JSFunction::kLiteralsOffset);
1147 TagObject(shared_info, "(shared function info)");
1148 SetInternalReference(js_fun, entry,
1149 "shared", shared_info,
1150 JSFunction::kSharedFunctionInfoOffset);
1151 TagObject(js_fun->context(), "(context)");
1152 SetInternalReference(js_fun, entry,
1153 "context", js_fun->context(),
1154 JSFunction::kContextOffset);
1155 SetWeakReference(js_fun, entry,
1156 "next_function_link", js_fun->next_function_link(),
1157 JSFunction::kNextFunctionLinkOffset);
1158 STATIC_ASSERT(JSFunction::kNextFunctionLinkOffset
1159 == JSFunction::kNonWeakFieldsEndOffset);
1160 STATIC_ASSERT(JSFunction::kNextFunctionLinkOffset + kPointerSize
1161 == JSFunction::kSize);
1162 } else if (obj->IsGlobalObject()) {
1163 GlobalObject* global_obj = GlobalObject::cast(obj);
1164 SetInternalReference(global_obj, entry,
1165 "builtins", global_obj->builtins(),
1166 GlobalObject::kBuiltinsOffset);
1167 SetInternalReference(global_obj, entry,
1168 "native_context", global_obj->native_context(),
1169 GlobalObject::kNativeContextOffset);
1170 SetInternalReference(global_obj, entry,
1171 "global_proxy", global_obj->global_proxy(),
1172 GlobalObject::kGlobalProxyOffset);
1173 STATIC_ASSERT(GlobalObject::kHeaderSize - JSObject::kHeaderSize ==
1174 3 * kPointerSize);
1175 } else if (obj->IsJSArrayBufferView()) {
1176 JSArrayBufferView* view = JSArrayBufferView::cast(obj);
1177 SetInternalReference(view, entry, "buffer", view->buffer(),
1178 JSArrayBufferView::kBufferOffset);
1179 }
1180 TagObject(js_obj->properties(), "(object properties)");
1181 SetInternalReference(obj, entry,
1182 "properties", js_obj->properties(),
1183 JSObject::kPropertiesOffset);
1184 TagObject(js_obj->elements(), "(object elements)");
1185 SetInternalReference(obj, entry,
1186 "elements", js_obj->elements(),
1187 JSObject::kElementsOffset);
1188 }
1189
1190
1191 void V8HeapExplorer::ExtractStringReferences(int entry, String* string) {
1192 if (string->IsConsString()) {
1193 ConsString* cs = ConsString::cast(string);
1194 SetInternalReference(cs, entry, "first", cs->first(),
1195 ConsString::kFirstOffset);
1196 SetInternalReference(cs, entry, "second", cs->second(),
1197 ConsString::kSecondOffset);
1198 } else if (string->IsSlicedString()) {
1199 SlicedString* ss = SlicedString::cast(string);
1200 SetInternalReference(ss, entry, "parent", ss->parent(),
1201 SlicedString::kParentOffset);
1202 }
1203 }
1204
1205
1206 void V8HeapExplorer::ExtractSymbolReferences(int entry, Symbol* symbol) {
1207 SetInternalReference(symbol, entry,
1208 "name", symbol->name(),
1209 Symbol::kNameOffset);
1210 }
1211
1212
1213 void V8HeapExplorer::ExtractJSCollectionReferences(int entry,
1214 JSCollection* collection) {
1215 SetInternalReference(collection, entry, "table", collection->table(),
1216 JSCollection::kTableOffset);
1217 }
1218
1219
1220 void V8HeapExplorer::ExtractJSWeakCollectionReferences(
1221 int entry, JSWeakCollection* collection) {
1222 MarkAsWeakContainer(collection->table());
1223 SetInternalReference(collection, entry,
1224 "table", collection->table(),
1225 JSWeakCollection::kTableOffset);
1226 }
1227
1228
1229 void V8HeapExplorer::ExtractContextReferences(int entry, Context* context) {
1230 if (context == context->declaration_context()) {
1231 ScopeInfo* scope_info = context->closure()->shared()->scope_info();
1232 // Add context allocated locals.
1233 int context_locals = scope_info->ContextLocalCount();
1234 for (int i = 0; i < context_locals; ++i) {
1235 String* local_name = scope_info->ContextLocalName(i);
1236 int idx = Context::MIN_CONTEXT_SLOTS + i;
1237 SetContextReference(context, entry, local_name, context->get(idx),
1238 Context::OffsetOfElementAt(idx));
1239 }
1240 if (scope_info->HasFunctionName()) {
1241 String* name = scope_info->FunctionName();
1242 VariableMode mode;
1243 int idx = scope_info->FunctionContextSlotIndex(name, &mode);
1244 if (idx >= 0) {
1245 SetContextReference(context, entry, name, context->get(idx),
1246 Context::OffsetOfElementAt(idx));
1247 }
1248 }
1249 }
1250
1251 #define EXTRACT_CONTEXT_FIELD(index, type, name) \
1252 if (Context::index < Context::FIRST_WEAK_SLOT || \
1253 Context::index == Context::MAP_CACHE_INDEX) { \
1254 SetInternalReference(context, entry, #name, context->get(Context::index), \
1255 FixedArray::OffsetOfElementAt(Context::index)); \
1256 } else { \
1257 SetWeakReference(context, entry, #name, context->get(Context::index), \
1258 FixedArray::OffsetOfElementAt(Context::index)); \
1259 }
1260 EXTRACT_CONTEXT_FIELD(CLOSURE_INDEX, JSFunction, closure);
1261 EXTRACT_CONTEXT_FIELD(PREVIOUS_INDEX, Context, previous);
1262 EXTRACT_CONTEXT_FIELD(EXTENSION_INDEX, Object, extension);
1263 EXTRACT_CONTEXT_FIELD(GLOBAL_OBJECT_INDEX, GlobalObject, global);
1264 if (context->IsNativeContext()) {
1265 TagObject(context->normalized_map_cache(), "(context norm. map cache)");
1266 TagObject(context->runtime_context(), "(runtime context)");
1267 TagObject(context->embedder_data(), "(context data)");
1268 NATIVE_CONTEXT_FIELDS(EXTRACT_CONTEXT_FIELD)
1269 EXTRACT_CONTEXT_FIELD(OPTIMIZED_FUNCTIONS_LIST, unused,
1270 optimized_functions_list);
1271 EXTRACT_CONTEXT_FIELD(OPTIMIZED_CODE_LIST, unused, optimized_code_list);
1272 EXTRACT_CONTEXT_FIELD(DEOPTIMIZED_CODE_LIST, unused, deoptimized_code_list);
1273 EXTRACT_CONTEXT_FIELD(NEXT_CONTEXT_LINK, unused, next_context_link);
1274 #undef EXTRACT_CONTEXT_FIELD
1275 STATIC_ASSERT(Context::OPTIMIZED_FUNCTIONS_LIST ==
1276 Context::FIRST_WEAK_SLOT);
1277 STATIC_ASSERT(Context::NEXT_CONTEXT_LINK + 1 ==
1278 Context::NATIVE_CONTEXT_SLOTS);
1279 STATIC_ASSERT(Context::FIRST_WEAK_SLOT + 4 ==
1280 Context::NATIVE_CONTEXT_SLOTS);
1281 }
1282 }
1283
1284
1285 void V8HeapExplorer::ExtractMapReferences(int entry, Map* map) {
1286 Object* raw_transitions_or_prototype_info = map->raw_transitions();
1287 if (TransitionArray::IsFullTransitionArray(
1288 raw_transitions_or_prototype_info)) {
1289 TransitionArray* transitions =
1290 TransitionArray::cast(raw_transitions_or_prototype_info);
1291 int transitions_entry = GetEntry(transitions)->index();
1292
1293 if (map->CanTransition()) {
1294 if (transitions->HasPrototypeTransitions()) {
1295 FixedArray* prototype_transitions =
1296 transitions->GetPrototypeTransitions();
1297 MarkAsWeakContainer(prototype_transitions);
1298 TagObject(prototype_transitions, "(prototype transitions");
1299 SetInternalReference(transitions, transitions_entry,
1300 "prototype_transitions", prototype_transitions);
1301 }
1302 // TODO(alph): transitions keys are strong links.
1303 MarkAsWeakContainer(transitions);
1304 }
1305
1306 TagObject(transitions, "(transition array)");
1307 SetInternalReference(map, entry, "transitions", transitions,
1308 Map::kTransitionsOrPrototypeInfoOffset);
1309 } else if (TransitionArray::IsSimpleTransition(
1310 raw_transitions_or_prototype_info)) {
1311 TagObject(raw_transitions_or_prototype_info, "(transition)");
1312 SetInternalReference(map, entry, "transition",
1313 raw_transitions_or_prototype_info,
1314 Map::kTransitionsOrPrototypeInfoOffset);
1315 } else if (map->is_prototype_map()) {
1316 TagObject(raw_transitions_or_prototype_info, "prototype_info");
1317 SetInternalReference(map, entry, "prototype_info",
1318 raw_transitions_or_prototype_info,
1319 Map::kTransitionsOrPrototypeInfoOffset);
1320 }
1321 DescriptorArray* descriptors = map->instance_descriptors();
1322 TagObject(descriptors, "(map descriptors)");
1323 SetInternalReference(map, entry,
1324 "descriptors", descriptors,
1325 Map::kDescriptorsOffset);
1326
1327 MarkAsWeakContainer(map->code_cache());
1328 SetInternalReference(map, entry,
1329 "code_cache", map->code_cache(),
1330 Map::kCodeCacheOffset);
1331 SetInternalReference(map, entry,
1332 "prototype", map->prototype(), Map::kPrototypeOffset);
1333 Object* constructor_or_backpointer = map->constructor_or_backpointer();
1334 if (constructor_or_backpointer->IsMap()) {
1335 TagObject(constructor_or_backpointer, "(back pointer)");
1336 SetInternalReference(map, entry, "back_pointer", constructor_or_backpointer,
1337 Map::kConstructorOrBackPointerOffset);
1338 } else {
1339 SetInternalReference(map, entry, "constructor", constructor_or_backpointer,
1340 Map::kConstructorOrBackPointerOffset);
1341 }
1342 TagObject(map->dependent_code(), "(dependent code)");
1343 MarkAsWeakContainer(map->dependent_code());
1344 SetInternalReference(map, entry,
1345 "dependent_code", map->dependent_code(),
1346 Map::kDependentCodeOffset);
1347 }
1348
1349
1350 void V8HeapExplorer::ExtractSharedFunctionInfoReferences(
1351 int entry, SharedFunctionInfo* shared) {
1352 HeapObject* obj = shared;
1353 String* shared_name = shared->DebugName();
1354 const char* name = NULL;
1355 if (shared_name != *heap_->isolate()->factory()->empty_string()) {
1356 name = names_->GetName(shared_name);
1357 TagObject(shared->code(), names_->GetFormatted("(code for %s)", name));
1358 } else {
1359 TagObject(shared->code(), names_->GetFormatted("(%s code)",
1360 Code::Kind2String(shared->code()->kind())));
1361 }
1362
1363 SetInternalReference(obj, entry,
1364 "name", shared->name(),
1365 SharedFunctionInfo::kNameOffset);
1366 SetInternalReference(obj, entry,
1367 "code", shared->code(),
1368 SharedFunctionInfo::kCodeOffset);
1369 TagObject(shared->scope_info(), "(function scope info)");
1370 SetInternalReference(obj, entry,
1371 "scope_info", shared->scope_info(),
1372 SharedFunctionInfo::kScopeInfoOffset);
1373 SetInternalReference(obj, entry,
1374 "instance_class_name", shared->instance_class_name(),
1375 SharedFunctionInfo::kInstanceClassNameOffset);
1376 SetInternalReference(obj, entry,
1377 "script", shared->script(),
1378 SharedFunctionInfo::kScriptOffset);
1379 const char* construct_stub_name = name ?
1380 names_->GetFormatted("(construct stub code for %s)", name) :
1381 "(construct stub code)";
1382 TagObject(shared->construct_stub(), construct_stub_name);
1383 SetInternalReference(obj, entry,
1384 "construct_stub", shared->construct_stub(),
1385 SharedFunctionInfo::kConstructStubOffset);
1386 SetInternalReference(obj, entry,
1387 "function_data", shared->function_data(),
1388 SharedFunctionInfo::kFunctionDataOffset);
1389 SetInternalReference(obj, entry,
1390 "debug_info", shared->debug_info(),
1391 SharedFunctionInfo::kDebugInfoOffset);
1392 SetInternalReference(obj, entry,
1393 "inferred_name", shared->inferred_name(),
1394 SharedFunctionInfo::kInferredNameOffset);
1395 SetInternalReference(obj, entry,
1396 "optimized_code_map", shared->optimized_code_map(),
1397 SharedFunctionInfo::kOptimizedCodeMapOffset);
1398 SetInternalReference(obj, entry,
1399 "feedback_vector", shared->feedback_vector(),
1400 SharedFunctionInfo::kFeedbackVectorOffset);
1401 }
1402
1403
1404 void V8HeapExplorer::ExtractScriptReferences(int entry, Script* script) {
1405 HeapObject* obj = script;
1406 SetInternalReference(obj, entry,
1407 "source", script->source(),
1408 Script::kSourceOffset);
1409 SetInternalReference(obj, entry,
1410 "name", script->name(),
1411 Script::kNameOffset);
1412 SetInternalReference(obj, entry,
1413 "context_data", script->context_data(),
1414 Script::kContextOffset);
1415 TagObject(script->line_ends(), "(script line ends)");
1416 SetInternalReference(obj, entry,
1417 "line_ends", script->line_ends(),
1418 Script::kLineEndsOffset);
1419 }
1420
1421
1422 void V8HeapExplorer::ExtractAccessorInfoReferences(
1423 int entry, AccessorInfo* accessor_info) {
1424 SetInternalReference(accessor_info, entry, "name", accessor_info->name(),
1425 AccessorInfo::kNameOffset);
1426 SetInternalReference(accessor_info, entry, "expected_receiver_type",
1427 accessor_info->expected_receiver_type(),
1428 AccessorInfo::kExpectedReceiverTypeOffset);
1429 if (accessor_info->IsExecutableAccessorInfo()) {
1430 ExecutableAccessorInfo* executable_accessor_info =
1431 ExecutableAccessorInfo::cast(accessor_info);
1432 SetInternalReference(executable_accessor_info, entry, "getter",
1433 executable_accessor_info->getter(),
1434 ExecutableAccessorInfo::kGetterOffset);
1435 SetInternalReference(executable_accessor_info, entry, "setter",
1436 executable_accessor_info->setter(),
1437 ExecutableAccessorInfo::kSetterOffset);
1438 SetInternalReference(executable_accessor_info, entry, "data",
1439 executable_accessor_info->data(),
1440 ExecutableAccessorInfo::kDataOffset);
1441 }
1442 }
1443
1444
1445 void V8HeapExplorer::ExtractAccessorPairReferences(
1446 int entry, AccessorPair* accessors) {
1447 SetInternalReference(accessors, entry, "getter", accessors->getter(),
1448 AccessorPair::kGetterOffset);
1449 SetInternalReference(accessors, entry, "setter", accessors->setter(),
1450 AccessorPair::kSetterOffset);
1451 }
1452
1453
1454 void V8HeapExplorer::ExtractCodeCacheReferences(
1455 int entry, CodeCache* code_cache) {
1456 TagObject(code_cache->default_cache(), "(default code cache)");
1457 SetInternalReference(code_cache, entry,
1458 "default_cache", code_cache->default_cache(),
1459 CodeCache::kDefaultCacheOffset);
1460 TagObject(code_cache->normal_type_cache(), "(code type cache)");
1461 SetInternalReference(code_cache, entry,
1462 "type_cache", code_cache->normal_type_cache(),
1463 CodeCache::kNormalTypeCacheOffset);
1464 }
1465
1466
1467 void V8HeapExplorer::TagBuiltinCodeObject(Code* code, const char* name) {
1468 TagObject(code, names_->GetFormatted("(%s builtin)", name));
1469 }
1470
1471
1472 void V8HeapExplorer::TagCodeObject(Code* code) {
1473 if (code->kind() == Code::STUB) {
1474 TagObject(code, names_->GetFormatted(
1475 "(%s code)",
1476 CodeStub::MajorName(CodeStub::GetMajorKey(code))));
1477 }
1478 }
1479
1480
1481 void V8HeapExplorer::ExtractCodeReferences(int entry, Code* code) {
1482 TagCodeObject(code);
1483 TagObject(code->relocation_info(), "(code relocation info)");
1484 SetInternalReference(code, entry,
1485 "relocation_info", code->relocation_info(),
1486 Code::kRelocationInfoOffset);
1487 SetInternalReference(code, entry,
1488 "handler_table", code->handler_table(),
1489 Code::kHandlerTableOffset);
1490 TagObject(code->deoptimization_data(), "(code deopt data)");
1491 SetInternalReference(code, entry,
1492 "deoptimization_data", code->deoptimization_data(),
1493 Code::kDeoptimizationDataOffset);
1494 if (code->kind() == Code::FUNCTION) {
1495 SetInternalReference(code, entry,
1496 "type_feedback_info", code->type_feedback_info(),
1497 Code::kTypeFeedbackInfoOffset);
1498 }
1499 SetInternalReference(code, entry,
1500 "gc_metadata", code->gc_metadata(),
1501 Code::kGCMetadataOffset);
1502 if (code->kind() == Code::OPTIMIZED_FUNCTION) {
1503 SetWeakReference(code, entry,
1504 "next_code_link", code->next_code_link(),
1505 Code::kNextCodeLinkOffset);
1506 }
1507 }
1508
1509
1510 void V8HeapExplorer::ExtractBoxReferences(int entry, Box* box) {
1511 SetInternalReference(box, entry, "value", box->value(), Box::kValueOffset);
1512 }
1513
1514
1515 void V8HeapExplorer::ExtractCellReferences(int entry, Cell* cell) {
1516 SetInternalReference(cell, entry, "value", cell->value(), Cell::kValueOffset);
1517 }
1518
1519
1520 void V8HeapExplorer::ExtractPropertyCellReferences(int entry,
1521 PropertyCell* cell) {
1522 SetInternalReference(cell, entry, "value", cell->value(),
1523 PropertyCell::kValueOffset);
1524 MarkAsWeakContainer(cell->dependent_code());
1525 SetInternalReference(cell, entry, "dependent_code", cell->dependent_code(),
1526 PropertyCell::kDependentCodeOffset);
1527 }
1528
1529
1530 void V8HeapExplorer::ExtractAllocationSiteReferences(int entry,
1531 AllocationSite* site) {
1532 SetInternalReference(site, entry, "transition_info", site->transition_info(),
1533 AllocationSite::kTransitionInfoOffset);
1534 SetInternalReference(site, entry, "nested_site", site->nested_site(),
1535 AllocationSite::kNestedSiteOffset);
1536 MarkAsWeakContainer(site->dependent_code());
1537 SetInternalReference(site, entry, "dependent_code", site->dependent_code(),
1538 AllocationSite::kDependentCodeOffset);
1539 // Do not visit weak_next as it is not visited by the StaticVisitor,
1540 // and we're not very interested in weak_next field here.
1541 STATIC_ASSERT(AllocationSite::kWeakNextOffset >=
1542 AllocationSite::BodyDescriptor::kEndOffset);
1543 }
1544
1545
1546 class JSArrayBufferDataEntryAllocator : public HeapEntriesAllocator {
1547 public:
1548 JSArrayBufferDataEntryAllocator(size_t size, V8HeapExplorer* explorer)
1549 : size_(size)
1550 , explorer_(explorer) {
1551 }
1552 virtual HeapEntry* AllocateEntry(HeapThing ptr) {
1553 return explorer_->AddEntry(
1554 static_cast<Address>(ptr),
1555 HeapEntry::kNative, "system / JSArrayBufferData", size_);
1556 }
1557 private:
1558 size_t size_;
1559 V8HeapExplorer* explorer_;
1560 };
1561
1562
1563 void V8HeapExplorer::ExtractJSArrayBufferReferences(
1564 int entry, JSArrayBuffer* buffer) {
1565 // Setup a reference to a native memory backing_store object.
1566 if (!buffer->backing_store())
1567 return;
1568 size_t data_size = NumberToSize(heap_->isolate(), buffer->byte_length());
1569 JSArrayBufferDataEntryAllocator allocator(data_size, this);
1570 HeapEntry* data_entry =
1571 filler_->FindOrAddEntry(buffer->backing_store(), &allocator);
1572 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1573 entry, "backing_store", data_entry);
1574 }
1575
1576
1577 void V8HeapExplorer::ExtractFixedArrayReferences(int entry, FixedArray* array) {
1578 bool is_weak = weak_containers_.Contains(array);
1579 for (int i = 0, l = array->length(); i < l; ++i) {
1580 if (is_weak) {
1581 SetWeakReference(array, entry,
1582 i, array->get(i), array->OffsetOfElementAt(i));
1583 } else {
1584 SetInternalReference(array, entry,
1585 i, array->get(i), array->OffsetOfElementAt(i));
1586 }
1587 }
1588 }
1589
1590
1591 void V8HeapExplorer::ExtractClosureReferences(JSObject* js_obj, int entry) {
1592 if (!js_obj->IsJSFunction()) return;
1593
1594 JSFunction* func = JSFunction::cast(js_obj);
1595 if (func->shared()->bound()) {
1596 FixedArray* bindings = func->function_bindings();
1597 SetNativeBindReference(js_obj, entry, "bound_this",
1598 bindings->get(JSFunction::kBoundThisIndex));
1599 SetNativeBindReference(js_obj, entry, "bound_function",
1600 bindings->get(JSFunction::kBoundFunctionIndex));
1601 for (int i = JSFunction::kBoundArgumentsStartIndex;
1602 i < bindings->length(); i++) {
1603 const char* reference_name = names_->GetFormatted(
1604 "bound_argument_%d",
1605 i - JSFunction::kBoundArgumentsStartIndex);
1606 SetNativeBindReference(js_obj, entry, reference_name,
1607 bindings->get(i));
1608 }
1609 }
1610 }
1611
1612
1613 void V8HeapExplorer::ExtractPropertyReferences(JSObject* js_obj, int entry) {
1614 if (js_obj->HasFastProperties()) {
1615 DescriptorArray* descs = js_obj->map()->instance_descriptors();
1616 int real_size = js_obj->map()->NumberOfOwnDescriptors();
1617 for (int i = 0; i < real_size; i++) {
1618 PropertyDetails details = descs->GetDetails(i);
1619 switch (details.location()) {
1620 case kField: {
1621 Representation r = details.representation();
1622 if (r.IsSmi() || r.IsDouble()) break;
1623
1624 Name* k = descs->GetKey(i);
1625 FieldIndex field_index = FieldIndex::ForDescriptor(js_obj->map(), i);
1626 Object* value = js_obj->RawFastPropertyAt(field_index);
1627 int field_offset =
1628 field_index.is_inobject() ? field_index.offset() : -1;
1629
1630 if (k != heap_->hidden_string()) {
1631 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry, k,
1632 value, NULL, field_offset);
1633 } else {
1634 TagObject(value, "(hidden properties)");
1635 SetInternalReference(js_obj, entry, "hidden_properties", value,
1636 field_offset);
1637 }
1638 break;
1639 }
1640 case kDescriptor:
1641 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1642 descs->GetKey(i),
1643 descs->GetValue(i));
1644 break;
1645 }
1646 }
1647 } else if (js_obj->IsGlobalObject()) {
1648 // We assume that global objects can only have slow properties.
1649 GlobalDictionary* dictionary = js_obj->global_dictionary();
1650 int length = dictionary->Capacity();
1651 for (int i = 0; i < length; ++i) {
1652 Object* k = dictionary->KeyAt(i);
1653 if (dictionary->IsKey(k)) {
1654 DCHECK(dictionary->ValueAt(i)->IsPropertyCell());
1655 PropertyCell* cell = PropertyCell::cast(dictionary->ValueAt(i));
1656 Object* value = cell->value();
1657 if (k == heap_->hidden_string()) {
1658 TagObject(value, "(hidden properties)");
1659 SetInternalReference(js_obj, entry, "hidden_properties", value);
1660 continue;
1661 }
1662 PropertyDetails details = cell->property_details();
1663 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1664 Name::cast(k), value);
1665 }
1666 }
1667 } else {
1668 NameDictionary* dictionary = js_obj->property_dictionary();
1669 int length = dictionary->Capacity();
1670 for (int i = 0; i < length; ++i) {
1671 Object* k = dictionary->KeyAt(i);
1672 if (dictionary->IsKey(k)) {
1673 Object* value = dictionary->ValueAt(i);
1674 if (k == heap_->hidden_string()) {
1675 TagObject(value, "(hidden properties)");
1676 SetInternalReference(js_obj, entry, "hidden_properties", value);
1677 continue;
1678 }
1679 PropertyDetails details = dictionary->DetailsAt(i);
1680 SetDataOrAccessorPropertyReference(details.kind(), js_obj, entry,
1681 Name::cast(k), value);
1682 }
1683 }
1684 }
1685 }
1686
1687
1688 void V8HeapExplorer::ExtractAccessorPairProperty(JSObject* js_obj, int entry,
1689 Name* key,
1690 Object* callback_obj,
1691 int field_offset) {
1692 if (!callback_obj->IsAccessorPair()) return;
1693 AccessorPair* accessors = AccessorPair::cast(callback_obj);
1694 SetPropertyReference(js_obj, entry, key, accessors, NULL, field_offset);
1695 Object* getter = accessors->getter();
1696 if (!getter->IsOddball()) {
1697 SetPropertyReference(js_obj, entry, key, getter, "get %s");
1698 }
1699 Object* setter = accessors->setter();
1700 if (!setter->IsOddball()) {
1701 SetPropertyReference(js_obj, entry, key, setter, "set %s");
1702 }
1703 }
1704
1705
1706 void V8HeapExplorer::ExtractElementReferences(JSObject* js_obj, int entry) {
1707 if (js_obj->HasFastObjectElements()) {
1708 FixedArray* elements = FixedArray::cast(js_obj->elements());
1709 int length = js_obj->IsJSArray() ?
1710 Smi::cast(JSArray::cast(js_obj)->length())->value() :
1711 elements->length();
1712 for (int i = 0; i < length; ++i) {
1713 if (!elements->get(i)->IsTheHole()) {
1714 SetElementReference(js_obj, entry, i, elements->get(i));
1715 }
1716 }
1717 } else if (js_obj->HasDictionaryElements()) {
1718 SeededNumberDictionary* dictionary = js_obj->element_dictionary();
1719 int length = dictionary->Capacity();
1720 for (int i = 0; i < length; ++i) {
1721 Object* k = dictionary->KeyAt(i);
1722 if (dictionary->IsKey(k)) {
1723 DCHECK(k->IsNumber());
1724 uint32_t index = static_cast<uint32_t>(k->Number());
1725 SetElementReference(js_obj, entry, index, dictionary->ValueAt(i));
1726 }
1727 }
1728 }
1729 }
1730
1731
1732 void V8HeapExplorer::ExtractInternalReferences(JSObject* js_obj, int entry) {
1733 int length = js_obj->GetInternalFieldCount();
1734 for (int i = 0; i < length; ++i) {
1735 Object* o = js_obj->GetInternalField(i);
1736 SetInternalReference(
1737 js_obj, entry, i, o, js_obj->GetInternalFieldOffset(i));
1738 }
1739 }
1740
1741
1742 String* V8HeapExplorer::GetConstructorName(JSObject* object) {
1743 Heap* heap = object->GetHeap();
1744 if (object->IsJSFunction()) return heap->closure_string();
1745 String* constructor_name = object->constructor_name();
1746 if (constructor_name == heap->Object_string()) {
1747 // TODO(verwaest): Try to get object.constructor.name in this case.
1748 // This requires handlification of the V8HeapExplorer.
1749 }
1750 return object->constructor_name();
1751 }
1752
1753
1754 HeapEntry* V8HeapExplorer::GetEntry(Object* obj) {
1755 if (!obj->IsHeapObject()) return NULL;
1756 return filler_->FindOrAddEntry(obj, this);
1757 }
1758
1759
1760 class RootsReferencesExtractor : public ObjectVisitor {
1761 private:
1762 struct IndexTag {
1763 IndexTag(int index, VisitorSynchronization::SyncTag tag)
1764 : index(index), tag(tag) { }
1765 int index;
1766 VisitorSynchronization::SyncTag tag;
1767 };
1768
1769 public:
1770 explicit RootsReferencesExtractor(Heap* heap)
1771 : collecting_all_references_(false),
1772 previous_reference_count_(0),
1773 heap_(heap) {
1774 }
1775
1776 void VisitPointers(Object** start, Object** end) {
1777 if (collecting_all_references_) {
1778 for (Object** p = start; p < end; p++) all_references_.Add(*p);
1779 } else {
1780 for (Object** p = start; p < end; p++) strong_references_.Add(*p);
1781 }
1782 }
1783
1784 void SetCollectingAllReferences() { collecting_all_references_ = true; }
1785
1786 void FillReferences(V8HeapExplorer* explorer) {
1787 DCHECK(strong_references_.length() <= all_references_.length());
1788 Builtins* builtins = heap_->isolate()->builtins();
1789 int strong_index = 0, all_index = 0, tags_index = 0, builtin_index = 0;
1790 while (all_index < all_references_.length()) {
1791 bool is_strong = strong_index < strong_references_.length()
1792 && strong_references_[strong_index] == all_references_[all_index];
1793 explorer->SetGcSubrootReference(reference_tags_[tags_index].tag,
1794 !is_strong,
1795 all_references_[all_index]);
1796 if (reference_tags_[tags_index].tag ==
1797 VisitorSynchronization::kBuiltins) {
1798 DCHECK(all_references_[all_index]->IsCode());
1799 explorer->TagBuiltinCodeObject(
1800 Code::cast(all_references_[all_index]),
1801 builtins->name(builtin_index++));
1802 }
1803 ++all_index;
1804 if (is_strong) ++strong_index;
1805 if (reference_tags_[tags_index].index == all_index) ++tags_index;
1806 }
1807 }
1808
1809 void Synchronize(VisitorSynchronization::SyncTag tag) {
1810 if (collecting_all_references_ &&
1811 previous_reference_count_ != all_references_.length()) {
1812 previous_reference_count_ = all_references_.length();
1813 reference_tags_.Add(IndexTag(previous_reference_count_, tag));
1814 }
1815 }
1816
1817 private:
1818 bool collecting_all_references_;
1819 List<Object*> strong_references_;
1820 List<Object*> all_references_;
1821 int previous_reference_count_;
1822 List<IndexTag> reference_tags_;
1823 Heap* heap_;
1824 };
1825
1826
1827 bool V8HeapExplorer::IterateAndExtractReferences(
1828 SnapshotFiller* filler) {
1829 filler_ = filler;
1830
1831 // Create references to the synthetic roots.
1832 SetRootGcRootsReference();
1833 for (int tag = 0; tag < VisitorSynchronization::kNumberOfSyncTags; tag++) {
1834 SetGcRootsReference(static_cast<VisitorSynchronization::SyncTag>(tag));
1835 }
1836
1837 // Make sure builtin code objects get their builtin tags
1838 // first. Otherwise a particular JSFunction object could set
1839 // its custom name to a generic builtin.
1840 RootsReferencesExtractor extractor(heap_);
1841 heap_->IterateRoots(&extractor, VISIT_ONLY_STRONG);
1842 extractor.SetCollectingAllReferences();
1843 heap_->IterateRoots(&extractor, VISIT_ALL);
1844 extractor.FillReferences(this);
1845
1846 // We have to do two passes as sometimes FixedArrays are used
1847 // to weakly hold their items, and it's impossible to distinguish
1848 // between these cases without processing the array owner first.
1849 bool interrupted =
1850 IterateAndExtractSinglePass<&V8HeapExplorer::ExtractReferencesPass1>() ||
1851 IterateAndExtractSinglePass<&V8HeapExplorer::ExtractReferencesPass2>();
1852
1853 if (interrupted) {
1854 filler_ = NULL;
1855 return false;
1856 }
1857
1858 filler_ = NULL;
1859 return progress_->ProgressReport(true);
1860 }
1861
1862
1863 template<V8HeapExplorer::ExtractReferencesMethod extractor>
1864 bool V8HeapExplorer::IterateAndExtractSinglePass() {
1865 // Now iterate the whole heap.
1866 bool interrupted = false;
1867 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
1868 // Heap iteration with filtering must be finished in any case.
1869 for (HeapObject* obj = iterator.next();
1870 obj != NULL;
1871 obj = iterator.next(), progress_->ProgressStep()) {
1872 if (interrupted) continue;
1873
1874 HeapEntry* heap_entry = GetEntry(obj);
1875 int entry = heap_entry->index();
1876 if ((this->*extractor)(entry, obj)) {
1877 SetInternalReference(obj, entry,
1878 "map", obj->map(), HeapObject::kMapOffset);
1879 // Extract unvisited fields as hidden references and restore tags
1880 // of visited fields.
1881 IndexedReferencesExtractor refs_extractor(this, obj, entry);
1882 obj->Iterate(&refs_extractor);
1883 }
1884
1885 if (!progress_->ProgressReport(false)) interrupted = true;
1886 }
1887 return interrupted;
1888 }
1889
1890
1891 bool V8HeapExplorer::IsEssentialObject(Object* object) {
1892 return object->IsHeapObject() && !object->IsOddball() &&
1893 object != heap_->empty_byte_array() &&
1894 object != heap_->empty_bytecode_array() &&
1895 object != heap_->empty_fixed_array() &&
1896 object != heap_->empty_descriptor_array() &&
1897 object != heap_->fixed_array_map() && object != heap_->cell_map() &&
1898 object != heap_->global_property_cell_map() &&
1899 object != heap_->shared_function_info_map() &&
1900 object != heap_->free_space_map() &&
1901 object != heap_->one_pointer_filler_map() &&
1902 object != heap_->two_pointer_filler_map();
1903 }
1904
1905
1906 void V8HeapExplorer::SetContextReference(HeapObject* parent_obj,
1907 int parent_entry,
1908 String* reference_name,
1909 Object* child_obj,
1910 int field_offset) {
1911 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1912 HeapEntry* child_entry = GetEntry(child_obj);
1913 if (child_entry != NULL) {
1914 filler_->SetNamedReference(HeapGraphEdge::kContextVariable,
1915 parent_entry,
1916 names_->GetName(reference_name),
1917 child_entry);
1918 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1919 }
1920 }
1921
1922
1923 void V8HeapExplorer::SetNativeBindReference(HeapObject* parent_obj,
1924 int parent_entry,
1925 const char* reference_name,
1926 Object* child_obj) {
1927 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1928 HeapEntry* child_entry = GetEntry(child_obj);
1929 if (child_entry != NULL) {
1930 filler_->SetNamedReference(HeapGraphEdge::kShortcut,
1931 parent_entry,
1932 reference_name,
1933 child_entry);
1934 }
1935 }
1936
1937
1938 void V8HeapExplorer::SetElementReference(HeapObject* parent_obj,
1939 int parent_entry,
1940 int index,
1941 Object* child_obj) {
1942 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1943 HeapEntry* child_entry = GetEntry(child_obj);
1944 if (child_entry != NULL) {
1945 filler_->SetIndexedReference(HeapGraphEdge::kElement,
1946 parent_entry,
1947 index,
1948 child_entry);
1949 }
1950 }
1951
1952
1953 void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1954 int parent_entry,
1955 const char* reference_name,
1956 Object* child_obj,
1957 int field_offset) {
1958 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1959 HeapEntry* child_entry = GetEntry(child_obj);
1960 if (child_entry == NULL) return;
1961 if (IsEssentialObject(child_obj)) {
1962 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1963 parent_entry,
1964 reference_name,
1965 child_entry);
1966 }
1967 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1968 }
1969
1970
1971 void V8HeapExplorer::SetInternalReference(HeapObject* parent_obj,
1972 int parent_entry,
1973 int index,
1974 Object* child_obj,
1975 int field_offset) {
1976 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1977 HeapEntry* child_entry = GetEntry(child_obj);
1978 if (child_entry == NULL) return;
1979 if (IsEssentialObject(child_obj)) {
1980 filler_->SetNamedReference(HeapGraphEdge::kInternal,
1981 parent_entry,
1982 names_->GetName(index),
1983 child_entry);
1984 }
1985 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
1986 }
1987
1988
1989 void V8HeapExplorer::SetHiddenReference(HeapObject* parent_obj,
1990 int parent_entry,
1991 int index,
1992 Object* child_obj) {
1993 DCHECK(parent_entry == GetEntry(parent_obj)->index());
1994 HeapEntry* child_entry = GetEntry(child_obj);
1995 if (child_entry != NULL && IsEssentialObject(child_obj)) {
1996 filler_->SetIndexedReference(HeapGraphEdge::kHidden,
1997 parent_entry,
1998 index,
1999 child_entry);
2000 }
2001 }
2002
2003
2004 void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
2005 int parent_entry,
2006 const char* reference_name,
2007 Object* child_obj,
2008 int field_offset) {
2009 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2010 HeapEntry* child_entry = GetEntry(child_obj);
2011 if (child_entry == NULL) return;
2012 if (IsEssentialObject(child_obj)) {
2013 filler_->SetNamedReference(HeapGraphEdge::kWeak,
2014 parent_entry,
2015 reference_name,
2016 child_entry);
2017 }
2018 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
2019 }
2020
2021
2022 void V8HeapExplorer::SetWeakReference(HeapObject* parent_obj,
2023 int parent_entry,
2024 int index,
2025 Object* child_obj,
2026 int field_offset) {
2027 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2028 HeapEntry* child_entry = GetEntry(child_obj);
2029 if (child_entry == NULL) return;
2030 if (IsEssentialObject(child_obj)) {
2031 filler_->SetNamedReference(HeapGraphEdge::kWeak,
2032 parent_entry,
2033 names_->GetFormatted("%d", index),
2034 child_entry);
2035 }
2036 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
2037 }
2038
2039
2040 void V8HeapExplorer::SetDataOrAccessorPropertyReference(
2041 PropertyKind kind, JSObject* parent_obj, int parent_entry,
2042 Name* reference_name, Object* child_obj, const char* name_format_string,
2043 int field_offset) {
2044 if (kind == kAccessor) {
2045 ExtractAccessorPairProperty(parent_obj, parent_entry, reference_name,
2046 child_obj, field_offset);
2047 } else {
2048 SetPropertyReference(parent_obj, parent_entry, reference_name, child_obj,
2049 name_format_string, field_offset);
2050 }
2051 }
2052
2053
2054 void V8HeapExplorer::SetPropertyReference(HeapObject* parent_obj,
2055 int parent_entry,
2056 Name* reference_name,
2057 Object* child_obj,
2058 const char* name_format_string,
2059 int field_offset) {
2060 DCHECK(parent_entry == GetEntry(parent_obj)->index());
2061 HeapEntry* child_entry = GetEntry(child_obj);
2062 if (child_entry != NULL) {
2063 HeapGraphEdge::Type type =
2064 reference_name->IsSymbol() || String::cast(reference_name)->length() > 0
2065 ? HeapGraphEdge::kProperty : HeapGraphEdge::kInternal;
2066 const char* name = name_format_string != NULL && reference_name->IsString()
2067 ? names_->GetFormatted(
2068 name_format_string,
2069 String::cast(reference_name)->ToCString(
2070 DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL).get()) :
2071 names_->GetName(reference_name);
2072
2073 filler_->SetNamedReference(type,
2074 parent_entry,
2075 name,
2076 child_entry);
2077 IndexedReferencesExtractor::MarkVisitedField(parent_obj, field_offset);
2078 }
2079 }
2080
2081
2082 void V8HeapExplorer::SetRootGcRootsReference() {
2083 filler_->SetIndexedAutoIndexReference(
2084 HeapGraphEdge::kElement,
2085 snapshot_->root()->index(),
2086 snapshot_->gc_roots());
2087 }
2088
2089
2090 void V8HeapExplorer::SetUserGlobalReference(Object* child_obj) {
2091 HeapEntry* child_entry = GetEntry(child_obj);
2092 DCHECK(child_entry != NULL);
2093 filler_->SetNamedAutoIndexReference(
2094 HeapGraphEdge::kShortcut,
2095 snapshot_->root()->index(),
2096 child_entry);
2097 }
2098
2099
2100 void V8HeapExplorer::SetGcRootsReference(VisitorSynchronization::SyncTag tag) {
2101 filler_->SetIndexedAutoIndexReference(
2102 HeapGraphEdge::kElement,
2103 snapshot_->gc_roots()->index(),
2104 snapshot_->gc_subroot(tag));
2105 }
2106
2107
2108 void V8HeapExplorer::SetGcSubrootReference(
2109 VisitorSynchronization::SyncTag tag, bool is_weak, Object* child_obj) {
2110 HeapEntry* child_entry = GetEntry(child_obj);
2111 if (child_entry != NULL) {
2112 const char* name = GetStrongGcSubrootName(child_obj);
2113 if (name != NULL) {
2114 filler_->SetNamedReference(
2115 HeapGraphEdge::kInternal,
2116 snapshot_->gc_subroot(tag)->index(),
2117 name,
2118 child_entry);
2119 } else {
2120 if (is_weak) {
2121 filler_->SetNamedAutoIndexReference(
2122 HeapGraphEdge::kWeak,
2123 snapshot_->gc_subroot(tag)->index(),
2124 child_entry);
2125 } else {
2126 filler_->SetIndexedAutoIndexReference(
2127 HeapGraphEdge::kElement,
2128 snapshot_->gc_subroot(tag)->index(),
2129 child_entry);
2130 }
2131 }
2132
2133 // Add a shortcut to JS global object reference at snapshot root.
2134 if (child_obj->IsNativeContext()) {
2135 Context* context = Context::cast(child_obj);
2136 GlobalObject* global = context->global_object();
2137 if (global->IsJSGlobalObject()) {
2138 bool is_debug_object = false;
2139 is_debug_object = heap_->isolate()->debug()->IsDebugGlobal(global);
2140 if (!is_debug_object && !user_roots_.Contains(global)) {
2141 user_roots_.Insert(global);
2142 SetUserGlobalReference(global);
2143 }
2144 }
2145 }
2146 }
2147 }
2148
2149
2150 const char* V8HeapExplorer::GetStrongGcSubrootName(Object* object) {
2151 if (strong_gc_subroot_names_.is_empty()) {
2152 #define NAME_ENTRY(name) strong_gc_subroot_names_.SetTag(heap_->name(), #name);
2153 #define ROOT_NAME(type, name, camel_name) NAME_ENTRY(name)
2154 STRONG_ROOT_LIST(ROOT_NAME)
2155 #undef ROOT_NAME
2156 #define STRUCT_MAP_NAME(NAME, Name, name) NAME_ENTRY(name##_map)
2157 STRUCT_LIST(STRUCT_MAP_NAME)
2158 #undef STRUCT_MAP_NAME
2159 #define STRING_NAME(name, str) NAME_ENTRY(name)
2160 INTERNALIZED_STRING_LIST(STRING_NAME)
2161 #undef STRING_NAME
2162 #define SYMBOL_NAME(name) NAME_ENTRY(name)
2163 PRIVATE_SYMBOL_LIST(SYMBOL_NAME)
2164 #undef SYMBOL_NAME
2165 #define SYMBOL_NAME(name, description) NAME_ENTRY(name)
2166 PUBLIC_SYMBOL_LIST(SYMBOL_NAME)
2167 #undef SYMBOL_NAME
2168 #undef NAME_ENTRY
2169 CHECK(!strong_gc_subroot_names_.is_empty());
2170 }
2171 return strong_gc_subroot_names_.GetTag(object);
2172 }
2173
2174
2175 void V8HeapExplorer::TagObject(Object* obj, const char* tag) {
2176 if (IsEssentialObject(obj)) {
2177 HeapEntry* entry = GetEntry(obj);
2178 if (entry->name()[0] == '\0') {
2179 entry->set_name(tag);
2180 }
2181 }
2182 }
2183
2184
2185 void V8HeapExplorer::MarkAsWeakContainer(Object* object) {
2186 if (IsEssentialObject(object) && object->IsFixedArray()) {
2187 weak_containers_.Insert(object);
2188 }
2189 }
2190
2191
2192 class GlobalObjectsEnumerator : public ObjectVisitor {
2193 public:
2194 virtual void VisitPointers(Object** start, Object** end) {
2195 for (Object** p = start; p < end; p++) {
2196 if ((*p)->IsNativeContext()) {
2197 Context* context = Context::cast(*p);
2198 JSObject* proxy = context->global_proxy();
2199 if (proxy->IsJSGlobalProxy()) {
2200 Object* global = proxy->map()->prototype();
2201 if (global->IsJSGlobalObject()) {
2202 objects_.Add(Handle<JSGlobalObject>(JSGlobalObject::cast(global)));
2203 }
2204 }
2205 }
2206 }
2207 }
2208 int count() { return objects_.length(); }
2209 Handle<JSGlobalObject>& at(int i) { return objects_[i]; }
2210
2211 private:
2212 List<Handle<JSGlobalObject> > objects_;
2213 };
2214
2215
2216 // Modifies heap. Must not be run during heap traversal.
2217 void V8HeapExplorer::TagGlobalObjects() {
2218 Isolate* isolate = heap_->isolate();
2219 HandleScope scope(isolate);
2220 GlobalObjectsEnumerator enumerator;
2221 isolate->global_handles()->IterateAllRoots(&enumerator);
2222 const char** urls = NewArray<const char*>(enumerator.count());
2223 for (int i = 0, l = enumerator.count(); i < l; ++i) {
2224 if (global_object_name_resolver_) {
2225 HandleScope scope(isolate);
2226 Handle<JSGlobalObject> global_obj = enumerator.at(i);
2227 urls[i] = global_object_name_resolver_->GetName(
2228 Utils::ToLocal(Handle<JSObject>::cast(global_obj)));
2229 } else {
2230 urls[i] = NULL;
2231 }
2232 }
2233
2234 DisallowHeapAllocation no_allocation;
2235 for (int i = 0, l = enumerator.count(); i < l; ++i) {
2236 objects_tags_.SetTag(*enumerator.at(i), urls[i]);
2237 }
2238
2239 DeleteArray(urls);
2240 }
2241
2242
2243 class GlobalHandlesExtractor : public ObjectVisitor {
2244 public:
2245 explicit GlobalHandlesExtractor(NativeObjectsExplorer* explorer)
2246 : explorer_(explorer) {}
2247 virtual ~GlobalHandlesExtractor() {}
2248 virtual void VisitPointers(Object** start, Object** end) {
2249 UNREACHABLE();
2250 }
2251 virtual void VisitEmbedderReference(Object** p, uint16_t class_id) {
2252 explorer_->VisitSubtreeWrapper(p, class_id);
2253 }
2254 private:
2255 NativeObjectsExplorer* explorer_;
2256 };
2257
2258
2259 class BasicHeapEntriesAllocator : public HeapEntriesAllocator {
2260 public:
2261 BasicHeapEntriesAllocator(
2262 HeapSnapshot* snapshot,
2263 HeapEntry::Type entries_type)
2264 : snapshot_(snapshot),
2265 names_(snapshot_->profiler()->names()),
2266 heap_object_map_(snapshot_->profiler()->heap_object_map()),
2267 entries_type_(entries_type) {
2268 }
2269 virtual HeapEntry* AllocateEntry(HeapThing ptr);
2270 private:
2271 HeapSnapshot* snapshot_;
2272 StringsStorage* names_;
2273 HeapObjectsMap* heap_object_map_;
2274 HeapEntry::Type entries_type_;
2275 };
2276
2277
2278 HeapEntry* BasicHeapEntriesAllocator::AllocateEntry(HeapThing ptr) {
2279 v8::RetainedObjectInfo* info = reinterpret_cast<v8::RetainedObjectInfo*>(ptr);
2280 intptr_t elements = info->GetElementCount();
2281 intptr_t size = info->GetSizeInBytes();
2282 const char* name = elements != -1
2283 ? names_->GetFormatted(
2284 "%s / %" V8_PTR_PREFIX "d entries", info->GetLabel(), elements)
2285 : names_->GetCopy(info->GetLabel());
2286 return snapshot_->AddEntry(
2287 entries_type_,
2288 name,
2289 heap_object_map_->GenerateId(info),
2290 size != -1 ? static_cast<int>(size) : 0,
2291 0);
2292 }
2293
2294
2295 NativeObjectsExplorer::NativeObjectsExplorer(
2296 HeapSnapshot* snapshot,
2297 SnapshottingProgressReportingInterface* progress)
2298 : isolate_(snapshot->profiler()->heap_object_map()->heap()->isolate()),
2299 snapshot_(snapshot),
2300 names_(snapshot_->profiler()->names()),
2301 embedder_queried_(false),
2302 objects_by_info_(RetainedInfosMatch),
2303 native_groups_(StringsMatch),
2304 filler_(NULL) {
2305 synthetic_entries_allocator_ =
2306 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kSynthetic);
2307 native_entries_allocator_ =
2308 new BasicHeapEntriesAllocator(snapshot, HeapEntry::kNative);
2309 }
2310
2311
2312 NativeObjectsExplorer::~NativeObjectsExplorer() {
2313 for (HashMap::Entry* p = objects_by_info_.Start();
2314 p != NULL;
2315 p = objects_by_info_.Next(p)) {
2316 v8::RetainedObjectInfo* info =
2317 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2318 info->Dispose();
2319 List<HeapObject*>* objects =
2320 reinterpret_cast<List<HeapObject*>* >(p->value);
2321 delete objects;
2322 }
2323 for (HashMap::Entry* p = native_groups_.Start();
2324 p != NULL;
2325 p = native_groups_.Next(p)) {
2326 v8::RetainedObjectInfo* info =
2327 reinterpret_cast<v8::RetainedObjectInfo*>(p->value);
2328 info->Dispose();
2329 }
2330 delete synthetic_entries_allocator_;
2331 delete native_entries_allocator_;
2332 }
2333
2334
2335 int NativeObjectsExplorer::EstimateObjectsCount() {
2336 FillRetainedObjects();
2337 return objects_by_info_.occupancy();
2338 }
2339
2340
2341 void NativeObjectsExplorer::FillRetainedObjects() {
2342 if (embedder_queried_) return;
2343 Isolate* isolate = isolate_;
2344 const GCType major_gc_type = kGCTypeMarkSweepCompact;
2345 // Record objects that are joined into ObjectGroups.
2346 isolate->heap()->CallGCPrologueCallbacks(
2347 major_gc_type, kGCCallbackFlagConstructRetainedObjectInfos);
2348 List<ObjectGroup*>* groups = isolate->global_handles()->object_groups();
2349 for (int i = 0; i < groups->length(); ++i) {
2350 ObjectGroup* group = groups->at(i);
2351 if (group->info == NULL) continue;
2352 List<HeapObject*>* list = GetListMaybeDisposeInfo(group->info);
2353 for (size_t j = 0; j < group->length; ++j) {
2354 HeapObject* obj = HeapObject::cast(*group->objects[j]);
2355 list->Add(obj);
2356 in_groups_.Insert(obj);
2357 }
2358 group->info = NULL; // Acquire info object ownership.
2359 }
2360 isolate->global_handles()->RemoveObjectGroups();
2361 isolate->heap()->CallGCEpilogueCallbacks(major_gc_type, kNoGCCallbackFlags);
2362 // Record objects that are not in ObjectGroups, but have class ID.
2363 GlobalHandlesExtractor extractor(this);
2364 isolate->global_handles()->IterateAllRootsWithClassIds(&extractor);
2365 embedder_queried_ = true;
2366 }
2367
2368
2369 void NativeObjectsExplorer::FillImplicitReferences() {
2370 Isolate* isolate = isolate_;
2371 List<ImplicitRefGroup*>* groups =
2372 isolate->global_handles()->implicit_ref_groups();
2373 for (int i = 0; i < groups->length(); ++i) {
2374 ImplicitRefGroup* group = groups->at(i);
2375 HeapObject* parent = *group->parent;
2376 int parent_entry =
2377 filler_->FindOrAddEntry(parent, native_entries_allocator_)->index();
2378 DCHECK(parent_entry != HeapEntry::kNoEntry);
2379 Object*** children = group->children;
2380 for (size_t j = 0; j < group->length; ++j) {
2381 Object* child = *children[j];
2382 HeapEntry* child_entry =
2383 filler_->FindOrAddEntry(child, native_entries_allocator_);
2384 filler_->SetNamedReference(
2385 HeapGraphEdge::kInternal,
2386 parent_entry,
2387 "native",
2388 child_entry);
2389 }
2390 }
2391 isolate->global_handles()->RemoveImplicitRefGroups();
2392 }
2393
2394 List<HeapObject*>* NativeObjectsExplorer::GetListMaybeDisposeInfo(
2395 v8::RetainedObjectInfo* info) {
2396 HashMap::Entry* entry = objects_by_info_.LookupOrInsert(info, InfoHash(info));
2397 if (entry->value != NULL) {
2398 info->Dispose();
2399 } else {
2400 entry->value = new List<HeapObject*>(4);
2401 }
2402 return reinterpret_cast<List<HeapObject*>* >(entry->value);
2403 }
2404
2405
2406 bool NativeObjectsExplorer::IterateAndExtractReferences(
2407 SnapshotFiller* filler) {
2408 filler_ = filler;
2409 FillRetainedObjects();
2410 FillImplicitReferences();
2411 if (EstimateObjectsCount() > 0) {
2412 for (HashMap::Entry* p = objects_by_info_.Start();
2413 p != NULL;
2414 p = objects_by_info_.Next(p)) {
2415 v8::RetainedObjectInfo* info =
2416 reinterpret_cast<v8::RetainedObjectInfo*>(p->key);
2417 SetNativeRootReference(info);
2418 List<HeapObject*>* objects =
2419 reinterpret_cast<List<HeapObject*>* >(p->value);
2420 for (int i = 0; i < objects->length(); ++i) {
2421 SetWrapperNativeReferences(objects->at(i), info);
2422 }
2423 }
2424 SetRootNativeRootsReference();
2425 }
2426 filler_ = NULL;
2427 return true;
2428 }
2429
2430
2431 class NativeGroupRetainedObjectInfo : public v8::RetainedObjectInfo {
2432 public:
2433 explicit NativeGroupRetainedObjectInfo(const char* label)
2434 : disposed_(false),
2435 hash_(reinterpret_cast<intptr_t>(label)),
2436 label_(label) {
2437 }
2438
2439 virtual ~NativeGroupRetainedObjectInfo() {}
2440 virtual void Dispose() {
2441 CHECK(!disposed_);
2442 disposed_ = true;
2443 delete this;
2444 }
2445 virtual bool IsEquivalent(RetainedObjectInfo* other) {
2446 return hash_ == other->GetHash() && !strcmp(label_, other->GetLabel());
2447 }
2448 virtual intptr_t GetHash() { return hash_; }
2449 virtual const char* GetLabel() { return label_; }
2450
2451 private:
2452 bool disposed_;
2453 intptr_t hash_;
2454 const char* label_;
2455 };
2456
2457
2458 NativeGroupRetainedObjectInfo* NativeObjectsExplorer::FindOrAddGroupInfo(
2459 const char* label) {
2460 const char* label_copy = names_->GetCopy(label);
2461 uint32_t hash = StringHasher::HashSequentialString(
2462 label_copy,
2463 static_cast<int>(strlen(label_copy)),
2464 isolate_->heap()->HashSeed());
2465 HashMap::Entry* entry =
2466 native_groups_.LookupOrInsert(const_cast<char*>(label_copy), hash);
2467 if (entry->value == NULL) {
2468 entry->value = new NativeGroupRetainedObjectInfo(label);
2469 }
2470 return static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2471 }
2472
2473
2474 void NativeObjectsExplorer::SetNativeRootReference(
2475 v8::RetainedObjectInfo* info) {
2476 HeapEntry* child_entry =
2477 filler_->FindOrAddEntry(info, native_entries_allocator_);
2478 DCHECK(child_entry != NULL);
2479 NativeGroupRetainedObjectInfo* group_info =
2480 FindOrAddGroupInfo(info->GetGroupLabel());
2481 HeapEntry* group_entry =
2482 filler_->FindOrAddEntry(group_info, synthetic_entries_allocator_);
2483 // |FindOrAddEntry| can move and resize the entries backing store. Reload
2484 // potentially-stale pointer.
2485 child_entry = filler_->FindEntry(info);
2486 filler_->SetNamedAutoIndexReference(
2487 HeapGraphEdge::kInternal,
2488 group_entry->index(),
2489 child_entry);
2490 }
2491
2492
2493 void NativeObjectsExplorer::SetWrapperNativeReferences(
2494 HeapObject* wrapper, v8::RetainedObjectInfo* info) {
2495 HeapEntry* wrapper_entry = filler_->FindEntry(wrapper);
2496 DCHECK(wrapper_entry != NULL);
2497 HeapEntry* info_entry =
2498 filler_->FindOrAddEntry(info, native_entries_allocator_);
2499 DCHECK(info_entry != NULL);
2500 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2501 wrapper_entry->index(),
2502 "native",
2503 info_entry);
2504 filler_->SetIndexedAutoIndexReference(HeapGraphEdge::kElement,
2505 info_entry->index(),
2506 wrapper_entry);
2507 }
2508
2509
2510 void NativeObjectsExplorer::SetRootNativeRootsReference() {
2511 for (HashMap::Entry* entry = native_groups_.Start();
2512 entry;
2513 entry = native_groups_.Next(entry)) {
2514 NativeGroupRetainedObjectInfo* group_info =
2515 static_cast<NativeGroupRetainedObjectInfo*>(entry->value);
2516 HeapEntry* group_entry =
2517 filler_->FindOrAddEntry(group_info, native_entries_allocator_);
2518 DCHECK(group_entry != NULL);
2519 filler_->SetIndexedAutoIndexReference(
2520 HeapGraphEdge::kElement,
2521 snapshot_->root()->index(),
2522 group_entry);
2523 }
2524 }
2525
2526
2527 void NativeObjectsExplorer::VisitSubtreeWrapper(Object** p, uint16_t class_id) {
2528 if (in_groups_.Contains(*p)) return;
2529 Isolate* isolate = isolate_;
2530 v8::RetainedObjectInfo* info =
2531 isolate->heap_profiler()->ExecuteWrapperClassCallback(class_id, p);
2532 if (info == NULL) return;
2533 GetListMaybeDisposeInfo(info)->Add(HeapObject::cast(*p));
2534 }
2535
2536
2537 HeapSnapshotGenerator::HeapSnapshotGenerator(
2538 HeapSnapshot* snapshot,
2539 v8::ActivityControl* control,
2540 v8::HeapProfiler::ObjectNameResolver* resolver,
2541 Heap* heap)
2542 : snapshot_(snapshot),
2543 control_(control),
2544 v8_heap_explorer_(snapshot_, this, resolver),
2545 dom_explorer_(snapshot_, this),
2546 heap_(heap) {
2547 }
2548
2549
2550 bool HeapSnapshotGenerator::GenerateSnapshot() {
2551 v8_heap_explorer_.TagGlobalObjects();
2552
2553 // TODO(1562) Profiler assumes that any object that is in the heap after
2554 // full GC is reachable from the root when computing dominators.
2555 // This is not true for weakly reachable objects.
2556 // As a temporary solution we call GC twice.
2557 heap_->CollectAllGarbage(
2558 Heap::kMakeHeapIterableMask,
2559 "HeapSnapshotGenerator::GenerateSnapshot");
2560 heap_->CollectAllGarbage(
2561 Heap::kMakeHeapIterableMask,
2562 "HeapSnapshotGenerator::GenerateSnapshot");
2563
2564 #ifdef VERIFY_HEAP
2565 Heap* debug_heap = heap_;
2566 if (FLAG_verify_heap) {
2567 debug_heap->Verify();
2568 }
2569 #endif
2570
2571 SetProgressTotal(2); // 2 passes.
2572
2573 #ifdef VERIFY_HEAP
2574 if (FLAG_verify_heap) {
2575 debug_heap->Verify();
2576 }
2577 #endif
2578
2579 snapshot_->AddSyntheticRootEntries();
2580
2581 if (!FillReferences()) return false;
2582
2583 snapshot_->FillChildren();
2584 snapshot_->RememberLastJSObjectId();
2585
2586 progress_counter_ = progress_total_;
2587 if (!ProgressReport(true)) return false;
2588 return true;
2589 }
2590
2591
2592 void HeapSnapshotGenerator::ProgressStep() {
2593 ++progress_counter_;
2594 }
2595
2596
2597 bool HeapSnapshotGenerator::ProgressReport(bool force) {
2598 const int kProgressReportGranularity = 10000;
2599 if (control_ != NULL
2600 && (force || progress_counter_ % kProgressReportGranularity == 0)) {
2601 return
2602 control_->ReportProgressValue(progress_counter_, progress_total_) ==
2603 v8::ActivityControl::kContinue;
2604 }
2605 return true;
2606 }
2607
2608
2609 void HeapSnapshotGenerator::SetProgressTotal(int iterations_count) {
2610 if (control_ == NULL) return;
2611 HeapIterator iterator(heap_, HeapIterator::kFilterUnreachable);
2612 progress_total_ = iterations_count * (
2613 v8_heap_explorer_.EstimateObjectsCount(&iterator) +
2614 dom_explorer_.EstimateObjectsCount());
2615 progress_counter_ = 0;
2616 }
2617
2618
2619 bool HeapSnapshotGenerator::FillReferences() {
2620 SnapshotFiller filler(snapshot_, &entries_);
2621 return v8_heap_explorer_.IterateAndExtractReferences(&filler)
2622 && dom_explorer_.IterateAndExtractReferences(&filler);
2623 }
2624
2625
2626 template<int bytes> struct MaxDecimalDigitsIn;
2627 template<> struct MaxDecimalDigitsIn<4> {
2628 static const int kSigned = 11;
2629 static const int kUnsigned = 10;
2630 };
2631 template<> struct MaxDecimalDigitsIn<8> {
2632 static const int kSigned = 20;
2633 static const int kUnsigned = 20;
2634 };
2635
2636
2637 class OutputStreamWriter {
2638 public:
2639 explicit OutputStreamWriter(v8::OutputStream* stream)
2640 : stream_(stream),
2641 chunk_size_(stream->GetChunkSize()),
2642 chunk_(chunk_size_),
2643 chunk_pos_(0),
2644 aborted_(false) {
2645 DCHECK(chunk_size_ > 0);
2646 }
2647 bool aborted() { return aborted_; }
2648 void AddCharacter(char c) {
2649 DCHECK(c != '\0');
2650 DCHECK(chunk_pos_ < chunk_size_);
2651 chunk_[chunk_pos_++] = c;
2652 MaybeWriteChunk();
2653 }
2654 void AddString(const char* s) {
2655 AddSubstring(s, StrLength(s));
2656 }
2657 void AddSubstring(const char* s, int n) {
2658 if (n <= 0) return;
2659 DCHECK(static_cast<size_t>(n) <= strlen(s));
2660 const char* s_end = s + n;
2661 while (s < s_end) {
2662 int s_chunk_size =
2663 Min(chunk_size_ - chunk_pos_, static_cast<int>(s_end - s));
2664 DCHECK(s_chunk_size > 0);
2665 MemCopy(chunk_.start() + chunk_pos_, s, s_chunk_size);
2666 s += s_chunk_size;
2667 chunk_pos_ += s_chunk_size;
2668 MaybeWriteChunk();
2669 }
2670 }
2671 void AddNumber(unsigned n) { AddNumberImpl<unsigned>(n, "%u"); }
2672 void Finalize() {
2673 if (aborted_) return;
2674 DCHECK(chunk_pos_ < chunk_size_);
2675 if (chunk_pos_ != 0) {
2676 WriteChunk();
2677 }
2678 stream_->EndOfStream();
2679 }
2680
2681 private:
2682 template<typename T>
2683 void AddNumberImpl(T n, const char* format) {
2684 // Buffer for the longest value plus trailing \0
2685 static const int kMaxNumberSize =
2686 MaxDecimalDigitsIn<sizeof(T)>::kUnsigned + 1;
2687 if (chunk_size_ - chunk_pos_ >= kMaxNumberSize) {
2688 int result = SNPrintF(
2689 chunk_.SubVector(chunk_pos_, chunk_size_), format, n);
2690 DCHECK(result != -1);
2691 chunk_pos_ += result;
2692 MaybeWriteChunk();
2693 } else {
2694 EmbeddedVector<char, kMaxNumberSize> buffer;
2695 int result = SNPrintF(buffer, format, n);
2696 USE(result);
2697 DCHECK(result != -1);
2698 AddString(buffer.start());
2699 }
2700 }
2701 void MaybeWriteChunk() {
2702 DCHECK(chunk_pos_ <= chunk_size_);
2703 if (chunk_pos_ == chunk_size_) {
2704 WriteChunk();
2705 }
2706 }
2707 void WriteChunk() {
2708 if (aborted_) return;
2709 if (stream_->WriteAsciiChunk(chunk_.start(), chunk_pos_) ==
2710 v8::OutputStream::kAbort) aborted_ = true;
2711 chunk_pos_ = 0;
2712 }
2713
2714 v8::OutputStream* stream_;
2715 int chunk_size_;
2716 ScopedVector<char> chunk_;
2717 int chunk_pos_;
2718 bool aborted_;
2719 };
2720
2721
2722 // type, name|index, to_node.
2723 const int HeapSnapshotJSONSerializer::kEdgeFieldsCount = 3;
2724 // type, name, id, self_size, edge_count, trace_node_id.
2725 const int HeapSnapshotJSONSerializer::kNodeFieldsCount = 6;
2726
2727 void HeapSnapshotJSONSerializer::Serialize(v8::OutputStream* stream) {
2728 if (AllocationTracker* allocation_tracker =
2729 snapshot_->profiler()->allocation_tracker()) {
2730 allocation_tracker->PrepareForSerialization();
2731 }
2732 DCHECK(writer_ == NULL);
2733 writer_ = new OutputStreamWriter(stream);
2734 SerializeImpl();
2735 delete writer_;
2736 writer_ = NULL;
2737 }
2738
2739
2740 void HeapSnapshotJSONSerializer::SerializeImpl() {
2741 DCHECK(0 == snapshot_->root()->index());
2742 writer_->AddCharacter('{');
2743 writer_->AddString("\"snapshot\":{");
2744 SerializeSnapshot();
2745 if (writer_->aborted()) return;
2746 writer_->AddString("},\n");
2747 writer_->AddString("\"nodes\":[");
2748 SerializeNodes();
2749 if (writer_->aborted()) return;
2750 writer_->AddString("],\n");
2751 writer_->AddString("\"edges\":[");
2752 SerializeEdges();
2753 if (writer_->aborted()) return;
2754 writer_->AddString("],\n");
2755
2756 writer_->AddString("\"trace_function_infos\":[");
2757 SerializeTraceNodeInfos();
2758 if (writer_->aborted()) return;
2759 writer_->AddString("],\n");
2760 writer_->AddString("\"trace_tree\":[");
2761 SerializeTraceTree();
2762 if (writer_->aborted()) return;
2763 writer_->AddString("],\n");
2764
2765 writer_->AddString("\"samples\":[");
2766 SerializeSamples();
2767 if (writer_->aborted()) return;
2768 writer_->AddString("],\n");
2769
2770 writer_->AddString("\"strings\":[");
2771 SerializeStrings();
2772 if (writer_->aborted()) return;
2773 writer_->AddCharacter(']');
2774 writer_->AddCharacter('}');
2775 writer_->Finalize();
2776 }
2777
2778
2779 int HeapSnapshotJSONSerializer::GetStringId(const char* s) {
2780 HashMap::Entry* cache_entry =
2781 strings_.LookupOrInsert(const_cast<char*>(s), StringHash(s));
2782 if (cache_entry->value == NULL) {
2783 cache_entry->value = reinterpret_cast<void*>(next_string_id_++);
2784 }
2785 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2786 }
2787
2788
2789 namespace {
2790
2791 template<size_t size> struct ToUnsigned;
2792
2793 template<> struct ToUnsigned<4> {
2794 typedef uint32_t Type;
2795 };
2796
2797 template<> struct ToUnsigned<8> {
2798 typedef uint64_t Type;
2799 };
2800
2801 } // namespace
2802
2803
2804 template<typename T>
2805 static int utoa_impl(T value, const Vector<char>& buffer, int buffer_pos) {
2806 STATIC_ASSERT(static_cast<T>(-1) > 0); // Check that T is unsigned
2807 int number_of_digits = 0;
2808 T t = value;
2809 do {
2810 ++number_of_digits;
2811 } while (t /= 10);
2812
2813 buffer_pos += number_of_digits;
2814 int result = buffer_pos;
2815 do {
2816 int last_digit = static_cast<int>(value % 10);
2817 buffer[--buffer_pos] = '0' + last_digit;
2818 value /= 10;
2819 } while (value);
2820 return result;
2821 }
2822
2823
2824 template<typename T>
2825 static int utoa(T value, const Vector<char>& buffer, int buffer_pos) {
2826 typename ToUnsigned<sizeof(value)>::Type unsigned_value = value;
2827 STATIC_ASSERT(sizeof(value) == sizeof(unsigned_value));
2828 return utoa_impl(unsigned_value, buffer, buffer_pos);
2829 }
2830
2831
2832 void HeapSnapshotJSONSerializer::SerializeEdge(HeapGraphEdge* edge,
2833 bool first_edge) {
2834 // The buffer needs space for 3 unsigned ints, 3 commas, \n and \0
2835 static const int kBufferSize =
2836 MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned * 3 + 3 + 2; // NOLINT
2837 EmbeddedVector<char, kBufferSize> buffer;
2838 int edge_name_or_index = edge->type() == HeapGraphEdge::kElement
2839 || edge->type() == HeapGraphEdge::kHidden
2840 ? edge->index() : GetStringId(edge->name());
2841 int buffer_pos = 0;
2842 if (!first_edge) {
2843 buffer[buffer_pos++] = ',';
2844 }
2845 buffer_pos = utoa(edge->type(), buffer, buffer_pos);
2846 buffer[buffer_pos++] = ',';
2847 buffer_pos = utoa(edge_name_or_index, buffer, buffer_pos);
2848 buffer[buffer_pos++] = ',';
2849 buffer_pos = utoa(entry_index(edge->to()), buffer, buffer_pos);
2850 buffer[buffer_pos++] = '\n';
2851 buffer[buffer_pos++] = '\0';
2852 writer_->AddString(buffer.start());
2853 }
2854
2855
2856 void HeapSnapshotJSONSerializer::SerializeEdges() {
2857 List<HeapGraphEdge*>& edges = snapshot_->children();
2858 for (int i = 0; i < edges.length(); ++i) {
2859 DCHECK(i == 0 ||
2860 edges[i - 1]->from()->index() <= edges[i]->from()->index());
2861 SerializeEdge(edges[i], i == 0);
2862 if (writer_->aborted()) return;
2863 }
2864 }
2865
2866
2867 void HeapSnapshotJSONSerializer::SerializeNode(HeapEntry* entry) {
2868 // The buffer needs space for 4 unsigned ints, 1 size_t, 5 commas, \n and \0
2869 static const int kBufferSize =
2870 5 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
2871 + MaxDecimalDigitsIn<sizeof(size_t)>::kUnsigned // NOLINT
2872 + 6 + 1 + 1;
2873 EmbeddedVector<char, kBufferSize> buffer;
2874 int buffer_pos = 0;
2875 if (entry_index(entry) != 0) {
2876 buffer[buffer_pos++] = ',';
2877 }
2878 buffer_pos = utoa(entry->type(), buffer, buffer_pos);
2879 buffer[buffer_pos++] = ',';
2880 buffer_pos = utoa(GetStringId(entry->name()), buffer, buffer_pos);
2881 buffer[buffer_pos++] = ',';
2882 buffer_pos = utoa(entry->id(), buffer, buffer_pos);
2883 buffer[buffer_pos++] = ',';
2884 buffer_pos = utoa(entry->self_size(), buffer, buffer_pos);
2885 buffer[buffer_pos++] = ',';
2886 buffer_pos = utoa(entry->children_count(), buffer, buffer_pos);
2887 buffer[buffer_pos++] = ',';
2888 buffer_pos = utoa(entry->trace_node_id(), buffer, buffer_pos);
2889 buffer[buffer_pos++] = '\n';
2890 buffer[buffer_pos++] = '\0';
2891 writer_->AddString(buffer.start());
2892 }
2893
2894
2895 void HeapSnapshotJSONSerializer::SerializeNodes() {
2896 List<HeapEntry>& entries = snapshot_->entries();
2897 for (int i = 0; i < entries.length(); ++i) {
2898 SerializeNode(&entries[i]);
2899 if (writer_->aborted()) return;
2900 }
2901 }
2902
2903
2904 void HeapSnapshotJSONSerializer::SerializeSnapshot() {
2905 writer_->AddString("\"meta\":");
2906 // The object describing node serialization layout.
2907 // We use a set of macros to improve readability.
2908 #define JSON_A(s) "[" s "]"
2909 #define JSON_O(s) "{" s "}"
2910 #define JSON_S(s) "\"" s "\""
2911 writer_->AddString(JSON_O(
2912 JSON_S("node_fields") ":" JSON_A(
2913 JSON_S("type") ","
2914 JSON_S("name") ","
2915 JSON_S("id") ","
2916 JSON_S("self_size") ","
2917 JSON_S("edge_count") ","
2918 JSON_S("trace_node_id")) ","
2919 JSON_S("node_types") ":" JSON_A(
2920 JSON_A(
2921 JSON_S("hidden") ","
2922 JSON_S("array") ","
2923 JSON_S("string") ","
2924 JSON_S("object") ","
2925 JSON_S("code") ","
2926 JSON_S("closure") ","
2927 JSON_S("regexp") ","
2928 JSON_S("number") ","
2929 JSON_S("native") ","
2930 JSON_S("synthetic") ","
2931 JSON_S("concatenated string") ","
2932 JSON_S("sliced string")) ","
2933 JSON_S("string") ","
2934 JSON_S("number") ","
2935 JSON_S("number") ","
2936 JSON_S("number") ","
2937 JSON_S("number") ","
2938 JSON_S("number")) ","
2939 JSON_S("edge_fields") ":" JSON_A(
2940 JSON_S("type") ","
2941 JSON_S("name_or_index") ","
2942 JSON_S("to_node")) ","
2943 JSON_S("edge_types") ":" JSON_A(
2944 JSON_A(
2945 JSON_S("context") ","
2946 JSON_S("element") ","
2947 JSON_S("property") ","
2948 JSON_S("internal") ","
2949 JSON_S("hidden") ","
2950 JSON_S("shortcut") ","
2951 JSON_S("weak")) ","
2952 JSON_S("string_or_number") ","
2953 JSON_S("node")) ","
2954 JSON_S("trace_function_info_fields") ":" JSON_A(
2955 JSON_S("function_id") ","
2956 JSON_S("name") ","
2957 JSON_S("script_name") ","
2958 JSON_S("script_id") ","
2959 JSON_S("line") ","
2960 JSON_S("column")) ","
2961 JSON_S("trace_node_fields") ":" JSON_A(
2962 JSON_S("id") ","
2963 JSON_S("function_info_index") ","
2964 JSON_S("count") ","
2965 JSON_S("size") ","
2966 JSON_S("children")) ","
2967 JSON_S("sample_fields") ":" JSON_A(
2968 JSON_S("timestamp_us") ","
2969 JSON_S("last_assigned_id"))));
2970 #undef JSON_S
2971 #undef JSON_O
2972 #undef JSON_A
2973 writer_->AddString(",\"node_count\":");
2974 writer_->AddNumber(snapshot_->entries().length());
2975 writer_->AddString(",\"edge_count\":");
2976 writer_->AddNumber(snapshot_->edges().length());
2977 writer_->AddString(",\"trace_function_count\":");
2978 uint32_t count = 0;
2979 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
2980 if (tracker) {
2981 count = tracker->function_info_list().length();
2982 }
2983 writer_->AddNumber(count);
2984 }
2985
2986
2987 static void WriteUChar(OutputStreamWriter* w, unibrow::uchar u) {
2988 static const char hex_chars[] = "0123456789ABCDEF";
2989 w->AddString("\\u");
2990 w->AddCharacter(hex_chars[(u >> 12) & 0xf]);
2991 w->AddCharacter(hex_chars[(u >> 8) & 0xf]);
2992 w->AddCharacter(hex_chars[(u >> 4) & 0xf]);
2993 w->AddCharacter(hex_chars[u & 0xf]);
2994 }
2995
2996
2997 void HeapSnapshotJSONSerializer::SerializeTraceTree() {
2998 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
2999 if (!tracker) return;
3000 AllocationTraceTree* traces = tracker->trace_tree();
3001 SerializeTraceNode(traces->root());
3002 }
3003
3004
3005 void HeapSnapshotJSONSerializer::SerializeTraceNode(AllocationTraceNode* node) {
3006 // The buffer needs space for 4 unsigned ints, 4 commas, [ and \0
3007 const int kBufferSize =
3008 4 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
3009 + 4 + 1 + 1;
3010 EmbeddedVector<char, kBufferSize> buffer;
3011 int buffer_pos = 0;
3012 buffer_pos = utoa(node->id(), buffer, buffer_pos);
3013 buffer[buffer_pos++] = ',';
3014 buffer_pos = utoa(node->function_info_index(), buffer, buffer_pos);
3015 buffer[buffer_pos++] = ',';
3016 buffer_pos = utoa(node->allocation_count(), buffer, buffer_pos);
3017 buffer[buffer_pos++] = ',';
3018 buffer_pos = utoa(node->allocation_size(), buffer, buffer_pos);
3019 buffer[buffer_pos++] = ',';
3020 buffer[buffer_pos++] = '[';
3021 buffer[buffer_pos++] = '\0';
3022 writer_->AddString(buffer.start());
3023
3024 Vector<AllocationTraceNode*> children = node->children();
3025 for (int i = 0; i < children.length(); i++) {
3026 if (i > 0) {
3027 writer_->AddCharacter(',');
3028 }
3029 SerializeTraceNode(children[i]);
3030 }
3031 writer_->AddCharacter(']');
3032 }
3033
3034
3035 // 0-based position is converted to 1-based during the serialization.
3036 static int SerializePosition(int position, const Vector<char>& buffer,
3037 int buffer_pos) {
3038 if (position == -1) {
3039 buffer[buffer_pos++] = '0';
3040 } else {
3041 DCHECK(position >= 0);
3042 buffer_pos = utoa(static_cast<unsigned>(position + 1), buffer, buffer_pos);
3043 }
3044 return buffer_pos;
3045 }
3046
3047
3048 void HeapSnapshotJSONSerializer::SerializeTraceNodeInfos() {
3049 AllocationTracker* tracker = snapshot_->profiler()->allocation_tracker();
3050 if (!tracker) return;
3051 // The buffer needs space for 6 unsigned ints, 6 commas, \n and \0
3052 const int kBufferSize =
3053 6 * MaxDecimalDigitsIn<sizeof(unsigned)>::kUnsigned // NOLINT
3054 + 6 + 1 + 1;
3055 EmbeddedVector<char, kBufferSize> buffer;
3056 const List<AllocationTracker::FunctionInfo*>& list =
3057 tracker->function_info_list();
3058 for (int i = 0; i < list.length(); i++) {
3059 AllocationTracker::FunctionInfo* info = list[i];
3060 int buffer_pos = 0;
3061 if (i > 0) {
3062 buffer[buffer_pos++] = ',';
3063 }
3064 buffer_pos = utoa(info->function_id, buffer, buffer_pos);
3065 buffer[buffer_pos++] = ',';
3066 buffer_pos = utoa(GetStringId(info->name), buffer, buffer_pos);
3067 buffer[buffer_pos++] = ',';
3068 buffer_pos = utoa(GetStringId(info->script_name), buffer, buffer_pos);
3069 buffer[buffer_pos++] = ',';
3070 // The cast is safe because script id is a non-negative Smi.
3071 buffer_pos = utoa(static_cast<unsigned>(info->script_id), buffer,
3072 buffer_pos);
3073 buffer[buffer_pos++] = ',';
3074 buffer_pos = SerializePosition(info->line, buffer, buffer_pos);
3075 buffer[buffer_pos++] = ',';
3076 buffer_pos = SerializePosition(info->column, buffer, buffer_pos);
3077 buffer[buffer_pos++] = '\n';
3078 buffer[buffer_pos++] = '\0';
3079 writer_->AddString(buffer.start());
3080 }
3081 }
3082
3083
3084 void HeapSnapshotJSONSerializer::SerializeSamples() {
3085 const List<HeapObjectsMap::TimeInterval>& samples =
3086 snapshot_->profiler()->heap_object_map()->samples();
3087 if (samples.is_empty()) return;
3088 base::TimeTicks start_time = samples[0].timestamp;
3089 // The buffer needs space for 2 unsigned ints, 2 commas, \n and \0
3090 const int kBufferSize = MaxDecimalDigitsIn<sizeof(
3091 base::TimeDelta().InMicroseconds())>::kUnsigned +
3092 MaxDecimalDigitsIn<sizeof(samples[0].id)>::kUnsigned +
3093 2 + 1 + 1;
3094 EmbeddedVector<char, kBufferSize> buffer;
3095 for (int i = 0; i < samples.length(); i++) {
3096 HeapObjectsMap::TimeInterval& sample = samples[i];
3097 int buffer_pos = 0;
3098 if (i > 0) {
3099 buffer[buffer_pos++] = ',';
3100 }
3101 base::TimeDelta time_delta = sample.timestamp - start_time;
3102 buffer_pos = utoa(time_delta.InMicroseconds(), buffer, buffer_pos);
3103 buffer[buffer_pos++] = ',';
3104 buffer_pos = utoa(sample.last_assigned_id(), buffer, buffer_pos);
3105 buffer[buffer_pos++] = '\n';
3106 buffer[buffer_pos++] = '\0';
3107 writer_->AddString(buffer.start());
3108 }
3109 }
3110
3111
3112 void HeapSnapshotJSONSerializer::SerializeString(const unsigned char* s) {
3113 writer_->AddCharacter('\n');
3114 writer_->AddCharacter('\"');
3115 for ( ; *s != '\0'; ++s) {
3116 switch (*s) {
3117 case '\b':
3118 writer_->AddString("\\b");
3119 continue;
3120 case '\f':
3121 writer_->AddString("\\f");
3122 continue;
3123 case '\n':
3124 writer_->AddString("\\n");
3125 continue;
3126 case '\r':
3127 writer_->AddString("\\r");
3128 continue;
3129 case '\t':
3130 writer_->AddString("\\t");
3131 continue;
3132 case '\"':
3133 case '\\':
3134 writer_->AddCharacter('\\');
3135 writer_->AddCharacter(*s);
3136 continue;
3137 default:
3138 if (*s > 31 && *s < 128) {
3139 writer_->AddCharacter(*s);
3140 } else if (*s <= 31) {
3141 // Special character with no dedicated literal.
3142 WriteUChar(writer_, *s);
3143 } else {
3144 // Convert UTF-8 into \u UTF-16 literal.
3145 size_t length = 1, cursor = 0;
3146 for ( ; length <= 4 && *(s + length) != '\0'; ++length) { }
3147 unibrow::uchar c = unibrow::Utf8::CalculateValue(s, length, &cursor);
3148 if (c != unibrow::Utf8::kBadChar) {
3149 WriteUChar(writer_, c);
3150 DCHECK(cursor != 0);
3151 s += cursor - 1;
3152 } else {
3153 writer_->AddCharacter('?');
3154 }
3155 }
3156 }
3157 }
3158 writer_->AddCharacter('\"');
3159 }
3160
3161
3162 void HeapSnapshotJSONSerializer::SerializeStrings() {
3163 ScopedVector<const unsigned char*> sorted_strings(
3164 strings_.occupancy() + 1);
3165 for (HashMap::Entry* entry = strings_.Start();
3166 entry != NULL;
3167 entry = strings_.Next(entry)) {
3168 int index = static_cast<int>(reinterpret_cast<uintptr_t>(entry->value));
3169 sorted_strings[index] = reinterpret_cast<const unsigned char*>(entry->key);
3170 }
3171 writer_->AddString("\"<dummy>\"");
3172 for (int i = 1; i < sorted_strings.length(); ++i) {
3173 writer_->AddCharacter(',');
3174 SerializeString(sorted_strings[i]);
3175 if (writer_->aborted()) return;
3176 }
3177 }
3178
3179
3180 } // namespace internal
3181 } // namespace v8
OLDNEW
« no previous file with comments | « src/heap-snapshot-generator.h ('k') | src/heap-snapshot-generator-inl.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698