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