blob: a4d9a828dd4ea7b5b05fada3f0d391c7b9002c0b [file] [log] [blame]
fschneider@chromium.org086aac62010-03-17 13:18:24 +00001// Copyright 2010 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
ricow@chromium.orgc9c80822010-04-21 08:22:37 +000028#ifdef ENABLE_LOGGING_AND_PROFILING
lrn@chromium.org25156de2010-04-06 13:10:27 +000029
fschneider@chromium.org086aac62010-03-17 13:18:24 +000030#include "v8.h"
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000031#include "global-handles.h"
ager@chromium.org2cc82ae2010-06-14 07:35:38 +000032#include "scopeinfo.h"
33#include "top.h"
erik.corry@gmail.comd88afa22010-09-15 12:33:05 +000034#include "unicode.h"
ager@chromium.org2cc82ae2010-06-14 07:35:38 +000035#include "zone-inl.h"
fschneider@chromium.org086aac62010-03-17 13:18:24 +000036
37#include "profile-generator-inl.h"
38
fschneider@chromium.org086aac62010-03-17 13:18:24 +000039namespace v8 {
40namespace internal {
41
42
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000043TokenEnumerator::TokenEnumerator()
44 : token_locations_(4),
45 token_removed_(4) {
46}
47
48
49TokenEnumerator::~TokenEnumerator() {
50 for (int i = 0; i < token_locations_.length(); ++i) {
51 if (!token_removed_[i]) {
52 GlobalHandles::ClearWeakness(token_locations_[i]);
53 GlobalHandles::Destroy(token_locations_[i]);
54 }
55 }
56}
57
58
59int TokenEnumerator::GetTokenId(Object* token) {
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +000060 if (token == NULL) return TokenEnumerator::kNoSecurityToken;
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000061 for (int i = 0; i < token_locations_.length(); ++i) {
62 if (*token_locations_[i] == token && !token_removed_[i]) return i;
63 }
64 Handle<Object> handle = GlobalHandles::Create(token);
65 // handle.location() points to a memory cell holding a pointer
66 // to a token object in the V8's heap.
67 GlobalHandles::MakeWeak(handle.location(), this, TokenRemovedCallback);
68 token_locations_.Add(handle.location());
69 token_removed_.Add(false);
70 return token_locations_.length() - 1;
71}
72
73
74void TokenEnumerator::TokenRemovedCallback(v8::Persistent<v8::Value> handle,
75 void* parameter) {
76 reinterpret_cast<TokenEnumerator*>(parameter)->TokenRemoved(
77 Utils::OpenHandle(*handle).location());
fschneider@chromium.orged78ffd2010-07-21 11:05:19 +000078 handle.Dispose();
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000079}
80
81
82void TokenEnumerator::TokenRemoved(Object** token_location) {
83 for (int i = 0; i < token_locations_.length(); ++i) {
84 if (token_locations_[i] == token_location && !token_removed_[i]) {
85 token_removed_[i] = true;
86 return;
87 }
88 }
89}
90
91
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +000092StringsStorage::StringsStorage()
93 : names_(StringsMatch) {
94}
95
96
vegorov@chromium.org42841962010-10-18 11:18:59 +000097static void DeleteIndexName(char** name_ptr) {
98 DeleteArray(*name_ptr);
99}
100
101
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000102StringsStorage::~StringsStorage() {
103 for (HashMap::Entry* p = names_.Start();
104 p != NULL;
105 p = names_.Next(p)) {
106 DeleteArray(reinterpret_cast<const char*>(p->value));
107 }
vegorov@chromium.org42841962010-10-18 11:18:59 +0000108 index_names_.Iterate(DeleteIndexName);
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000109}
110
111
112const char* StringsStorage::GetName(String* name) {
113 if (name->IsString()) {
114 char* c_name =
115 name->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL).Detach();
116 HashMap::Entry* cache_entry = names_.Lookup(c_name, name->Hash(), true);
117 if (cache_entry->value == NULL) {
118 // New entry added.
119 cache_entry->value = c_name;
120 } else {
121 DeleteArray(c_name);
122 }
123 return reinterpret_cast<const char*>(cache_entry->value);
124 }
125 return "";
126}
127
128
vegorov@chromium.org42841962010-10-18 11:18:59 +0000129const char* StringsStorage::GetName(int index) {
130 ASSERT(index >= 0);
131 if (index_names_.length() <= index) {
132 index_names_.AddBlock(
133 NULL, index - index_names_.length() + 1);
134 }
135 if (index_names_[index] == NULL) {
136 const int kMaximumNameLength = 32;
137 char* name = NewArray<char>(kMaximumNameLength);
138 OS::SNPrintF(Vector<char>(name, kMaximumNameLength), "%d", index);
139 index_names_[index] = name;
140 }
141 return index_names_[index];
142}
143
144
lrn@chromium.org25156de2010-04-06 13:10:27 +0000145const char* CodeEntry::kEmptyNamePrefix = "";
lrn@chromium.org25156de2010-04-06 13:10:27 +0000146
147
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000148void CodeEntry::CopyData(const CodeEntry& source) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000149 tag_ = source.tag_;
150 name_prefix_ = source.name_prefix_;
151 name_ = source.name_;
152 resource_name_ = source.resource_name_;
153 line_number_ = source.line_number_;
154}
155
156
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000157uint32_t CodeEntry::GetCallUid() const {
158 uint32_t hash = ComputeIntegerHash(tag_);
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000159 hash ^= ComputeIntegerHash(
160 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name_prefix_)));
161 hash ^= ComputeIntegerHash(
162 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(name_)));
163 hash ^= ComputeIntegerHash(
164 static_cast<uint32_t>(reinterpret_cast<uintptr_t>(resource_name_)));
165 hash ^= ComputeIntegerHash(line_number_);
fschneider@chromium.orgc20610a2010-09-22 09:44:58 +0000166 return hash;
167}
168
169
170bool CodeEntry::IsSameAs(CodeEntry* entry) const {
171 return this == entry
172 || (tag_ == entry->tag_
173 && name_prefix_ == entry->name_prefix_
174 && name_ == entry->name_
175 && resource_name_ == entry->resource_name_
176 && line_number_ == entry->line_number_);
177}
178
179
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000180ProfileNode* ProfileNode::FindChild(CodeEntry* entry) {
181 HashMap::Entry* map_entry =
182 children_.Lookup(entry, CodeEntryHash(entry), false);
183 return map_entry != NULL ?
184 reinterpret_cast<ProfileNode*>(map_entry->value) : NULL;
185}
186
187
188ProfileNode* ProfileNode::FindOrAddChild(CodeEntry* entry) {
189 HashMap::Entry* map_entry =
190 children_.Lookup(entry, CodeEntryHash(entry), true);
191 if (map_entry->value == NULL) {
192 // New node added.
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000193 ProfileNode* new_node = new ProfileNode(tree_, entry);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000194 map_entry->value = new_node;
195 children_list_.Add(new_node);
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000196 }
197 return reinterpret_cast<ProfileNode*>(map_entry->value);
198}
199
200
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000201double ProfileNode::GetSelfMillis() const {
202 return tree_->TicksToMillis(self_ticks_);
203}
204
205
206double ProfileNode::GetTotalMillis() const {
207 return tree_->TicksToMillis(total_ticks_);
208}
209
210
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000211void ProfileNode::Print(int indent) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000212 OS::Print("%5u %5u %*c %s%s [%d]",
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000213 total_ticks_, self_ticks_,
214 indent, ' ',
ager@chromium.org357bf652010-04-12 11:30:10 +0000215 entry_->name_prefix(),
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000216 entry_->name(),
217 entry_->security_token_id());
ager@chromium.org357bf652010-04-12 11:30:10 +0000218 if (entry_->resource_name()[0] != '\0')
219 OS::Print(" %s:%d", entry_->resource_name(), entry_->line_number());
220 OS::Print("\n");
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000221 for (HashMap::Entry* p = children_.Start();
222 p != NULL;
223 p = children_.Next(p)) {
224 reinterpret_cast<ProfileNode*>(p->value)->Print(indent + 2);
225 }
226}
227
228
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000229class DeleteNodesCallback {
230 public:
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000231 void BeforeTraversingChild(ProfileNode*, ProfileNode*) { }
232
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000233 void AfterAllChildrenTraversed(ProfileNode* node) {
234 delete node;
235 }
236
237 void AfterChildTraversed(ProfileNode*, ProfileNode*) { }
238};
239
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000240
ager@chromium.org357bf652010-04-12 11:30:10 +0000241ProfileTree::ProfileTree()
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000242 : root_entry_(Logger::FUNCTION_TAG,
243 "",
244 "(root)",
245 "",
246 0,
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000247 TokenEnumerator::kNoSecurityToken),
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000248 root_(new ProfileNode(this, &root_entry_)) {
ager@chromium.org357bf652010-04-12 11:30:10 +0000249}
250
251
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000252ProfileTree::~ProfileTree() {
253 DeleteNodesCallback cb;
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000254 TraverseDepthFirst(&cb);
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000255}
256
257
258void ProfileTree::AddPathFromEnd(const Vector<CodeEntry*>& path) {
259 ProfileNode* node = root_;
260 for (CodeEntry** entry = path.start() + path.length() - 1;
261 entry != path.start() - 1;
262 --entry) {
263 if (*entry != NULL) {
264 node = node->FindOrAddChild(*entry);
265 }
266 }
267 node->IncrementSelfTicks();
268}
269
270
271void ProfileTree::AddPathFromStart(const Vector<CodeEntry*>& path) {
272 ProfileNode* node = root_;
273 for (CodeEntry** entry = path.start();
274 entry != path.start() + path.length();
275 ++entry) {
276 if (*entry != NULL) {
277 node = node->FindOrAddChild(*entry);
278 }
279 }
280 node->IncrementSelfTicks();
281}
282
283
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000284struct NodesPair {
285 NodesPair(ProfileNode* src, ProfileNode* dst)
286 : src(src), dst(dst) { }
287 ProfileNode* src;
288 ProfileNode* dst;
289};
290
291
292class FilteredCloneCallback {
293 public:
294 explicit FilteredCloneCallback(ProfileNode* dst_root, int security_token_id)
295 : stack_(10),
296 security_token_id_(security_token_id) {
297 stack_.Add(NodesPair(NULL, dst_root));
298 }
299
300 void BeforeTraversingChild(ProfileNode* parent, ProfileNode* child) {
301 if (IsTokenAcceptable(child->entry()->security_token_id(),
302 parent->entry()->security_token_id())) {
303 ProfileNode* clone = stack_.last().dst->FindOrAddChild(child->entry());
304 clone->IncreaseSelfTicks(child->self_ticks());
305 stack_.Add(NodesPair(child, clone));
306 } else {
307 // Attribute ticks to parent node.
308 stack_.last().dst->IncreaseSelfTicks(child->self_ticks());
309 }
310 }
311
312 void AfterAllChildrenTraversed(ProfileNode* parent) { }
313
314 void AfterChildTraversed(ProfileNode*, ProfileNode* child) {
315 if (stack_.last().src == child) {
316 stack_.RemoveLast();
317 }
318 }
319
320 private:
321 bool IsTokenAcceptable(int token, int parent_token) {
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000322 if (token == TokenEnumerator::kNoSecurityToken
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000323 || token == security_token_id_) return true;
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000324 if (token == TokenEnumerator::kInheritsSecurityToken) {
325 ASSERT(parent_token != TokenEnumerator::kInheritsSecurityToken);
326 return parent_token == TokenEnumerator::kNoSecurityToken
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000327 || parent_token == security_token_id_;
328 }
329 return false;
330 }
331
332 List<NodesPair> stack_;
333 int security_token_id_;
334};
335
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000336void ProfileTree::FilteredClone(ProfileTree* src, int security_token_id) {
337 ms_to_ticks_scale_ = src->ms_to_ticks_scale_;
338 FilteredCloneCallback cb(root_, security_token_id);
339 src->TraverseDepthFirst(&cb);
340 CalculateTotalTicks();
341}
342
343
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000344void ProfileTree::SetTickRatePerMs(double ticks_per_ms) {
345 ms_to_ticks_scale_ = ticks_per_ms > 0 ? 1.0 / ticks_per_ms : 1.0;
346}
347
348
lrn@chromium.org25156de2010-04-06 13:10:27 +0000349class Position {
350 public:
351 explicit Position(ProfileNode* node)
352 : node(node), child_idx_(0) { }
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000353 INLINE(ProfileNode* current_child()) {
lrn@chromium.org25156de2010-04-06 13:10:27 +0000354 return node->children()->at(child_idx_);
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000355 }
lrn@chromium.org25156de2010-04-06 13:10:27 +0000356 INLINE(bool has_current_child()) {
357 return child_idx_ < node->children()->length();
358 }
359 INLINE(void next_child()) { ++child_idx_; }
360
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000361 ProfileNode* node;
lrn@chromium.org25156de2010-04-06 13:10:27 +0000362 private:
363 int child_idx_;
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000364};
365
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000366
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000367// Non-recursive implementation of a depth-first post-order tree traversal.
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000368template <typename Callback>
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000369void ProfileTree::TraverseDepthFirst(Callback* callback) {
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000370 List<Position> stack(10);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000371 stack.Add(Position(root_));
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000372 while (stack.length() > 0) {
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000373 Position& current = stack.last();
lrn@chromium.org25156de2010-04-06 13:10:27 +0000374 if (current.has_current_child()) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000375 callback->BeforeTraversingChild(current.node, current.current_child());
lrn@chromium.org25156de2010-04-06 13:10:27 +0000376 stack.Add(Position(current.current_child()));
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000377 } else {
378 callback->AfterAllChildrenTraversed(current.node);
379 if (stack.length() > 1) {
380 Position& parent = stack[stack.length() - 2];
381 callback->AfterChildTraversed(parent.node, current.node);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000382 parent.next_child();
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000383 }
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000384 // Remove child from the stack.
385 stack.RemoveLast();
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000386 }
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000387 }
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000388}
389
390
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000391class CalculateTotalTicksCallback {
392 public:
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000393 void BeforeTraversingChild(ProfileNode*, ProfileNode*) { }
394
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000395 void AfterAllChildrenTraversed(ProfileNode* node) {
396 node->IncreaseTotalTicks(node->self_ticks());
397 }
398
399 void AfterChildTraversed(ProfileNode* parent, ProfileNode* child) {
400 parent->IncreaseTotalTicks(child->total_ticks());
401 }
402};
403
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000404
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000405void ProfileTree::CalculateTotalTicks() {
406 CalculateTotalTicksCallback cb;
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000407 TraverseDepthFirst(&cb);
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000408}
409
410
411void ProfileTree::ShortPrint() {
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000412 OS::Print("root: %u %u %.2fms %.2fms\n",
413 root_->total_ticks(), root_->self_ticks(),
414 root_->GetTotalMillis(), root_->GetSelfMillis());
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000415}
416
417
418void CpuProfile::AddPath(const Vector<CodeEntry*>& path) {
419 top_down_.AddPathFromEnd(path);
420 bottom_up_.AddPathFromStart(path);
421}
422
423
424void CpuProfile::CalculateTotalTicks() {
425 top_down_.CalculateTotalTicks();
426 bottom_up_.CalculateTotalTicks();
427}
428
429
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000430void CpuProfile::SetActualSamplingRate(double actual_sampling_rate) {
431 top_down_.SetTickRatePerMs(actual_sampling_rate);
432 bottom_up_.SetTickRatePerMs(actual_sampling_rate);
433}
434
435
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000436CpuProfile* CpuProfile::FilteredClone(int security_token_id) {
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000437 ASSERT(security_token_id != TokenEnumerator::kNoSecurityToken);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000438 CpuProfile* clone = new CpuProfile(title_, uid_);
439 clone->top_down_.FilteredClone(&top_down_, security_token_id);
440 clone->bottom_up_.FilteredClone(&bottom_up_, security_token_id);
441 return clone;
442}
443
444
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000445void CpuProfile::ShortPrint() {
446 OS::Print("top down ");
447 top_down_.ShortPrint();
448 OS::Print("bottom up ");
449 bottom_up_.ShortPrint();
450}
451
452
453void CpuProfile::Print() {
454 OS::Print("[Top down]:\n");
455 top_down_.Print();
456 OS::Print("[Bottom up]:\n");
457 bottom_up_.Print();
458}
459
460
461const CodeMap::CodeTreeConfig::Key CodeMap::CodeTreeConfig::kNoKey = NULL;
462const CodeMap::CodeTreeConfig::Value CodeMap::CodeTreeConfig::kNoValue =
463 CodeMap::CodeEntryInfo(NULL, 0);
464
465
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000466void CodeMap::AddAlias(Address start, CodeEntry* entry, Address code_start) {
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000467 CodeTree::Locator locator;
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000468 if (tree_.Find(code_start, &locator)) {
469 const CodeEntryInfo& code_info = locator.value();
whesse@chromium.org4a1fe7d2010-09-27 12:32:04 +0000470 if (tree_.Insert(start, &locator)) {
471 entry->CopyData(*code_info.entry);
472 locator.set_value(CodeEntryInfo(entry, code_info.size));
473 }
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000474 }
475}
476
477
478CodeEntry* CodeMap::FindEntry(Address addr) {
479 CodeTree::Locator locator;
480 if (tree_.FindGreatestLessThan(addr, &locator)) {
481 // locator.key() <= addr. Need to check that addr is within entry.
482 const CodeEntryInfo& entry = locator.value();
483 if (addr < (locator.key() + entry.size))
484 return entry.entry;
485 }
486 return NULL;
487}
488
489
lrn@chromium.org25156de2010-04-06 13:10:27 +0000490void CodeMap::CodeTreePrinter::Call(
491 const Address& key, const CodeMap::CodeEntryInfo& value) {
492 OS::Print("%p %5d %s\n", key, value.size, value.entry->name());
493}
494
495
496void CodeMap::Print() {
497 CodeTreePrinter printer;
498 tree_.ForEach(&printer);
499}
500
501
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000502CpuProfilesCollection::CpuProfilesCollection()
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000503 : profiles_uids_(UidsMatch),
lrn@chromium.org25156de2010-04-06 13:10:27 +0000504 current_profiles_semaphore_(OS::CreateSemaphore(1)) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000505 // Create list of unabridged profiles.
506 profiles_by_token_.Add(new List<CpuProfile*>());
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000507}
508
509
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000510static void DeleteCodeEntry(CodeEntry** entry_ptr) {
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000511 delete *entry_ptr;
512}
513
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000514static void DeleteCpuProfile(CpuProfile** profile_ptr) {
515 delete *profile_ptr;
516}
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000517
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000518static void DeleteProfilesList(List<CpuProfile*>** list_ptr) {
519 (*list_ptr)->Iterate(DeleteCpuProfile);
520 delete *list_ptr;
521}
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000522
523CpuProfilesCollection::~CpuProfilesCollection() {
lrn@chromium.org25156de2010-04-06 13:10:27 +0000524 delete current_profiles_semaphore_;
525 current_profiles_.Iterate(DeleteCpuProfile);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000526 profiles_by_token_.Iterate(DeleteProfilesList);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000527 code_entries_.Iterate(DeleteCodeEntry);
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000528}
529
530
lrn@chromium.org25156de2010-04-06 13:10:27 +0000531bool CpuProfilesCollection::StartProfiling(const char* title, unsigned uid) {
532 ASSERT(uid > 0);
533 current_profiles_semaphore_->Wait();
ricow@chromium.orgd236f4d2010-09-01 06:52:08 +0000534 if (current_profiles_.length() >= kMaxSimultaneousProfiles) {
535 current_profiles_semaphore_->Signal();
536 return false;
537 }
lrn@chromium.org25156de2010-04-06 13:10:27 +0000538 for (int i = 0; i < current_profiles_.length(); ++i) {
539 if (strcmp(current_profiles_[i]->title(), title) == 0) {
540 // Ignore attempts to start profile with the same title.
541 current_profiles_semaphore_->Signal();
542 return false;
543 }
544 }
545 current_profiles_.Add(new CpuProfile(title, uid));
546 current_profiles_semaphore_->Signal();
547 return true;
548}
549
550
551bool CpuProfilesCollection::StartProfiling(String* title, unsigned uid) {
552 return StartProfiling(GetName(title), uid);
553}
554
555
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000556CpuProfile* CpuProfilesCollection::StopProfiling(int security_token_id,
557 const char* title,
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000558 double actual_sampling_rate) {
whesse@chromium.orgb6e43bb2010-04-14 09:36:28 +0000559 const int title_len = StrLength(title);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000560 CpuProfile* profile = NULL;
561 current_profiles_semaphore_->Wait();
562 for (int i = current_profiles_.length() - 1; i >= 0; --i) {
563 if (title_len == 0 || strcmp(current_profiles_[i]->title(), title) == 0) {
564 profile = current_profiles_.Remove(i);
565 break;
566 }
567 }
568 current_profiles_semaphore_->Signal();
569
570 if (profile != NULL) {
571 profile->CalculateTotalTicks();
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000572 profile->SetActualSamplingRate(actual_sampling_rate);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000573 List<CpuProfile*>* unabridged_list =
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000574 profiles_by_token_[TokenToIndex(TokenEnumerator::kNoSecurityToken)];
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000575 unabridged_list->Add(profile);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000576 HashMap::Entry* entry =
577 profiles_uids_.Lookup(reinterpret_cast<void*>(profile->uid()),
578 static_cast<uint32_t>(profile->uid()),
579 true);
580 ASSERT(entry->value == NULL);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000581 entry->value = reinterpret_cast<void*>(unabridged_list->length() - 1);
582 return GetProfile(security_token_id, profile->uid());
lrn@chromium.org25156de2010-04-06 13:10:27 +0000583 }
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000584 return NULL;
lrn@chromium.org25156de2010-04-06 13:10:27 +0000585}
586
587
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000588CpuProfile* CpuProfilesCollection::GetProfile(int security_token_id,
589 unsigned uid) {
lrn@chromium.org25156de2010-04-06 13:10:27 +0000590 HashMap::Entry* entry = profiles_uids_.Lookup(reinterpret_cast<void*>(uid),
591 static_cast<uint32_t>(uid),
592 false);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000593 int index;
594 if (entry != NULL) {
595 index = static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
596 } else {
597 return NULL;
598 }
599 List<CpuProfile*>* unabridged_list =
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000600 profiles_by_token_[TokenToIndex(TokenEnumerator::kNoSecurityToken)];
601 if (security_token_id == TokenEnumerator::kNoSecurityToken) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000602 return unabridged_list->at(index);
603 }
604 List<CpuProfile*>* list = GetProfilesList(security_token_id);
605 if (list->at(index) == NULL) {
606 list->at(index) =
607 unabridged_list->at(index)->FilteredClone(security_token_id);
608 }
609 return list->at(index);
610}
611
612
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000613bool CpuProfilesCollection::IsLastProfile(const char* title) {
614 // Called from VM thread, and only it can mutate the list,
615 // so no locking is needed here.
616 if (current_profiles_.length() != 1) return false;
617 return StrLength(title) == 0
618 || strcmp(current_profiles_[0]->title(), title) == 0;
619}
620
621
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000622int CpuProfilesCollection::TokenToIndex(int security_token_id) {
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000623 ASSERT(TokenEnumerator::kNoSecurityToken == -1);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000624 return security_token_id + 1; // kNoSecurityToken -> 0, 0 -> 1, ...
625}
626
627
628List<CpuProfile*>* CpuProfilesCollection::GetProfilesList(
629 int security_token_id) {
630 const int index = TokenToIndex(security_token_id);
ricow@chromium.org30ce4112010-05-31 10:38:25 +0000631 const int lists_to_add = index - profiles_by_token_.length() + 1;
632 if (lists_to_add > 0) profiles_by_token_.AddBlock(NULL, lists_to_add);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000633 List<CpuProfile*>* unabridged_list =
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000634 profiles_by_token_[TokenToIndex(TokenEnumerator::kNoSecurityToken)];
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000635 const int current_count = unabridged_list->length();
636 if (profiles_by_token_[index] == NULL) {
637 profiles_by_token_[index] = new List<CpuProfile*>(current_count);
638 }
639 List<CpuProfile*>* list = profiles_by_token_[index];
ricow@chromium.org30ce4112010-05-31 10:38:25 +0000640 const int profiles_to_add = current_count - list->length();
641 if (profiles_to_add > 0) list->AddBlock(NULL, profiles_to_add);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000642 return list;
643}
644
645
646List<CpuProfile*>* CpuProfilesCollection::Profiles(int security_token_id) {
647 List<CpuProfile*>* unabridged_list =
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000648 profiles_by_token_[TokenToIndex(TokenEnumerator::kNoSecurityToken)];
649 if (security_token_id == TokenEnumerator::kNoSecurityToken) {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000650 return unabridged_list;
651 }
652 List<CpuProfile*>* list = GetProfilesList(security_token_id);
653 const int current_count = unabridged_list->length();
654 for (int i = 0; i < current_count; ++i) {
655 if (list->at(i) == NULL) {
656 list->at(i) = unabridged_list->at(i)->FilteredClone(security_token_id);
657 }
658 }
659 return list;
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000660}
661
662
663CodeEntry* CpuProfilesCollection::NewCodeEntry(Logger::LogEventsAndTags tag,
664 String* name,
665 String* resource_name,
666 int line_number) {
667 CodeEntry* entry = new CodeEntry(tag,
lrn@chromium.org25156de2010-04-06 13:10:27 +0000668 CodeEntry::kEmptyNamePrefix,
ager@chromium.org357bf652010-04-12 11:30:10 +0000669 GetFunctionName(name),
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000670 GetName(resource_name),
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000671 line_number,
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000672 TokenEnumerator::kNoSecurityToken);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000673 code_entries_.Add(entry);
674 return entry;
675}
676
677
678CodeEntry* CpuProfilesCollection::NewCodeEntry(Logger::LogEventsAndTags tag,
679 const char* name) {
lrn@chromium.org25156de2010-04-06 13:10:27 +0000680 CodeEntry* entry = new CodeEntry(tag,
681 CodeEntry::kEmptyNamePrefix,
ager@chromium.org357bf652010-04-12 11:30:10 +0000682 GetFunctionName(name),
lrn@chromium.org25156de2010-04-06 13:10:27 +0000683 "",
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000684 v8::CpuProfileNode::kNoLineNumberInfo,
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000685 TokenEnumerator::kNoSecurityToken);
lrn@chromium.org25156de2010-04-06 13:10:27 +0000686 code_entries_.Add(entry);
687 return entry;
688}
689
690
691CodeEntry* CpuProfilesCollection::NewCodeEntry(Logger::LogEventsAndTags tag,
692 const char* name_prefix,
693 String* name) {
694 CodeEntry* entry = new CodeEntry(tag,
695 name_prefix,
696 GetName(name),
697 "",
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000698 v8::CpuProfileNode::kNoLineNumberInfo,
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000699 TokenEnumerator::kInheritsSecurityToken);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000700 code_entries_.Add(entry);
701 return entry;
702}
703
704
705CodeEntry* CpuProfilesCollection::NewCodeEntry(Logger::LogEventsAndTags tag,
706 int args_count) {
lrn@chromium.org25156de2010-04-06 13:10:27 +0000707 CodeEntry* entry = new CodeEntry(tag,
708 "args_count: ",
709 GetName(args_count),
710 "",
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000711 v8::CpuProfileNode::kNoLineNumberInfo,
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000712 TokenEnumerator::kInheritsSecurityToken);
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000713 code_entries_.Add(entry);
714 return entry;
715}
716
717
718CodeEntry* CpuProfilesCollection::NewCodeEntry(int security_token_id) {
719 CodeEntry* entry = new CodeEntry(security_token_id);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000720 code_entries_.Add(entry);
721 return entry;
722}
723
724
lrn@chromium.org25156de2010-04-06 13:10:27 +0000725void CpuProfilesCollection::AddPathToCurrentProfiles(
726 const Vector<CodeEntry*>& path) {
727 // As starting / stopping profiles is rare relatively to this
728 // method, we don't bother minimizing the duration of lock holding,
729 // e.g. copying contents of the list to a local vector.
730 current_profiles_semaphore_->Wait();
731 for (int i = 0; i < current_profiles_.length(); ++i) {
732 current_profiles_[i]->AddPath(path);
733 }
734 current_profiles_semaphore_->Signal();
735}
736
737
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000738void SampleRateCalculator::Tick() {
739 if (--wall_time_query_countdown_ == 0)
740 UpdateMeasurements(OS::TimeCurrentMillis());
741}
742
743
744void SampleRateCalculator::UpdateMeasurements(double current_time) {
745 if (measurements_count_++ != 0) {
746 const double measured_ticks_per_ms =
747 (kWallTimeQueryIntervalMs * ticks_per_ms_) /
748 (current_time - last_wall_time_);
749 // Update the average value.
750 ticks_per_ms_ +=
751 (measured_ticks_per_ms - ticks_per_ms_) / measurements_count_;
752 // Update the externally accessible result.
753 result_ = static_cast<AtomicWord>(ticks_per_ms_ * kResultScale);
754 }
755 last_wall_time_ = current_time;
756 wall_time_query_countdown_ =
757 static_cast<unsigned>(kWallTimeQueryIntervalMs * ticks_per_ms_);
758}
759
760
ager@chromium.org357bf652010-04-12 11:30:10 +0000761const char* ProfileGenerator::kAnonymousFunctionName = "(anonymous function)";
762const char* ProfileGenerator::kProgramEntryName = "(program)";
763const char* ProfileGenerator::kGarbageCollectorEntryName =
764 "(garbage collector)";
765
766
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000767ProfileGenerator::ProfileGenerator(CpuProfilesCollection* profiles)
ager@chromium.org357bf652010-04-12 11:30:10 +0000768 : profiles_(profiles),
769 program_entry_(
770 profiles->NewCodeEntry(Logger::FUNCTION_TAG, kProgramEntryName)),
771 gc_entry_(
772 profiles->NewCodeEntry(Logger::BUILTIN_TAG,
773 kGarbageCollectorEntryName)) {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000774}
775
776
777void ProfileGenerator::RecordTickSample(const TickSample& sample) {
ager@chromium.org357bf652010-04-12 11:30:10 +0000778 // Allocate space for stack frames + pc + function + vm-state.
779 ScopedVector<CodeEntry*> entries(sample.frames_count + 3);
780 // As actual number of decoded code entries may vary, initialize
781 // entries vector with NULL values.
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000782 CodeEntry** entry = entries.start();
ager@chromium.org357bf652010-04-12 11:30:10 +0000783 memset(entry, 0, entries.length() * sizeof(*entry));
784 if (sample.pc != NULL) {
785 *entry++ = code_map_.FindEntry(sample.pc);
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000786
ager@chromium.org357bf652010-04-12 11:30:10 +0000787 if (sample.function != NULL) {
788 *entry = code_map_.FindEntry(sample.function);
789 if (*entry != NULL && !(*entry)->is_js_function()) {
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000790 *entry = NULL;
ager@chromium.org357bf652010-04-12 11:30:10 +0000791 } else {
792 CodeEntry* pc_entry = *entries.start();
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000793 if (pc_entry == NULL) {
ager@chromium.org357bf652010-04-12 11:30:10 +0000794 *entry = NULL;
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +0000795 } else if (pc_entry->is_js_function()) {
796 // Use function entry in favor of pc entry, as function
797 // entry has security token.
798 *entries.start() = NULL;
799 }
ager@chromium.org357bf652010-04-12 11:30:10 +0000800 }
801 entry++;
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000802 }
ager@chromium.org357bf652010-04-12 11:30:10 +0000803
804 for (const Address *stack_pos = sample.stack,
805 *stack_end = stack_pos + sample.frames_count;
806 stack_pos != stack_end;
807 ++stack_pos) {
808 *entry++ = code_map_.FindEntry(*stack_pos);
809 }
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000810 }
811
ager@chromium.org357bf652010-04-12 11:30:10 +0000812 if (FLAG_prof_browser_mode) {
ricow@chromium.orgc9c80822010-04-21 08:22:37 +0000813 bool no_symbolized_entries = true;
814 for (CodeEntry** e = entries.start(); e != entry; ++e) {
815 if (*e != NULL) {
816 no_symbolized_entries = false;
817 break;
818 }
819 }
820 // If no frames were symbolized, put the VM state entry in.
821 if (no_symbolized_entries) {
822 *entry++ = EntryForVMState(sample.state);
823 }
whesse@chromium.orgcec079d2010-03-22 14:44:04 +0000824 }
825
lrn@chromium.org25156de2010-04-06 13:10:27 +0000826 profiles_->AddPathToCurrentProfiles(entries);
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000827}
828
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000829
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000830void HeapGraphEdge::Init(
831 int child_index, Type type, const char* name, HeapEntry* to) {
832 ASSERT(type == kContextVariable || type == kProperty || type == kInternal);
833 child_index_ = child_index;
834 type_ = type;
835 name_ = name;
836 to_ = to;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000837}
838
839
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000840void HeapGraphEdge::Init(int child_index, int index, HeapEntry* to) {
841 child_index_ = child_index;
842 type_ = kElement;
843 index_ = index;
844 to_ = to;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000845}
846
847
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000848HeapEntry* HeapGraphEdge::From() {
849 return reinterpret_cast<HeapEntry*>(this - child_index_) - 1;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000850}
851
852
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000853void HeapEntry::Init(HeapSnapshot* snapshot,
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000854 Type type,
855 const char* name,
856 uint64_t id,
857 int self_size,
858 int children_count,
859 int retainers_count) {
860 snapshot_ = snapshot;
861 type_ = type;
862 painted_ = kUnpainted;
863 calculated_data_index_ = kNoCalculatedData;
864 name_ = name;
865 id_ = id;
866 self_size_ = self_size;
867 children_count_ = children_count;
868 retainers_count_ = retainers_count;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000869}
870
871
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000872void HeapEntry::SetNamedReference(HeapGraphEdge::Type type,
873 int child_index,
874 const char* name,
875 HeapEntry* entry,
876 int retainer_index) {
877 children_arr()[child_index].Init(child_index, type, name, entry);
878 entry->retainers_arr()[retainer_index] = children_arr() + child_index;
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +0000879}
880
881
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000882void HeapEntry::SetElementReference(
883 int child_index, int index, HeapEntry* entry, int retainer_index) {
884 children_arr()[child_index].Init(child_index, index, entry);
885 entry->retainers_arr()[retainer_index] = children_arr() + child_index;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000886}
887
888
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000889void HeapEntry::SetUnidirElementReference(
890 int child_index, int index, HeapEntry* entry) {
891 children_arr()[child_index].Init(child_index, index, entry);
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +0000892}
893
894
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000895int HeapEntry::ReachableSize() {
896 if (calculated_data_index_ == kNoCalculatedData) {
897 calculated_data_index_ = snapshot_->AddCalculatedData();
898 }
899 return snapshot_->GetCalculatedData(
900 calculated_data_index_).ReachableSize(this);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000901}
902
903
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000904int HeapEntry::RetainedSize() {
905 if (calculated_data_index_ == kNoCalculatedData) {
906 calculated_data_index_ = snapshot_->AddCalculatedData();
907 }
908 return snapshot_->GetCalculatedData(
909 calculated_data_index_).RetainedSize(this);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000910}
911
912
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000913List<HeapGraphPath*>* HeapEntry::GetRetainingPaths() {
914 if (calculated_data_index_ == kNoCalculatedData) {
915 calculated_data_index_ = snapshot_->AddCalculatedData();
916 }
917 return snapshot_->GetCalculatedData(
918 calculated_data_index_).GetRetainingPaths(this);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000919}
920
921
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000922template<class Visitor>
923void HeapEntry::ApplyAndPaintAllReachable(Visitor* visitor) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000924 List<HeapEntry*> list(10);
925 list.Add(this);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000926 this->paint_reachable();
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000927 visitor->Apply(this);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000928 while (!list.is_empty()) {
929 HeapEntry* entry = list.RemoveLast();
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000930 Vector<HeapGraphEdge> children = entry->children();
931 for (int i = 0; i < children.length(); ++i) {
932 HeapEntry* child = children[i].to();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000933 if (!child->painted_reachable()) {
934 list.Add(child);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000935 child->paint_reachable();
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000936 visitor->Apply(child);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000937 }
938 }
939 }
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000940}
941
942
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000943class NullClass {
944 public:
945 void Apply(HeapEntry* entry) { }
946};
947
948void HeapEntry::PaintAllReachable() {
949 NullClass null;
950 ApplyAndPaintAllReachable(&null);
951}
952
953
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000954void HeapEntry::Print(int max_depth, int indent) {
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +0000955 OS::Print("%6d %6d %6d [%llu] ",
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000956 self_size(), ReachableSize(), RetainedSize(), id_);
957 if (type() != kString) {
958 OS::Print("%s %.40s\n", TypeAsString(), name_);
959 } else {
960 OS::Print("\"");
961 const char* c = name_;
962 while (*c && (c - name_) <= 40) {
963 if (*c != '\n')
964 OS::Print("%c", *c);
965 else
966 OS::Print("\\n");
967 ++c;
968 }
969 OS::Print("\"\n");
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000970 }
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000971 if (--max_depth == 0) return;
972 Vector<HeapGraphEdge> ch = children();
973 for (int i = 0; i < ch.length(); ++i) {
974 HeapGraphEdge& edge = ch[i];
975 switch (edge.type()) {
976 case HeapGraphEdge::kContextVariable:
977 OS::Print(" %*c #%s: ", indent, ' ', edge.name());
978 break;
979 case HeapGraphEdge::kElement:
980 OS::Print(" %*c %d: ", indent, ' ', edge.index());
981 break;
982 case HeapGraphEdge::kInternal:
983 OS::Print(" %*c $%s: ", indent, ' ', edge.name());
984 break;
985 case HeapGraphEdge::kProperty:
986 OS::Print(" %*c %s: ", indent, ' ', edge.name());
987 break;
988 default:
989 OS::Print("!!! unknown edge type: %d ", edge.type());
990 }
991 edge.to()->Print(max_depth, indent + 2);
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000992 }
ricow@chromium.org4980dff2010-07-19 08:33:45 +0000993}
994
ager@chromium.org2cc82ae2010-06-14 07:35:38 +0000995
vegorov@chromium.org26c16f82010-08-11 13:41:03 +0000996const char* HeapEntry::TypeAsString() {
997 switch (type()) {
998 case kInternal: return "/internal/";
999 case kObject: return "/object/";
1000 case kClosure: return "/closure/";
1001 case kString: return "/string/";
1002 case kCode: return "/code/";
1003 case kArray: return "/array/";
vegorov@chromium.org42841962010-10-18 11:18:59 +00001004 case kRegExp: return "/regexp/";
1005 case kHeapNumber: return "/number/";
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001006 default: return "???";
1007 }
1008}
1009
1010
1011int HeapEntry::EntriesSize(int entries_count,
1012 int children_count,
1013 int retainers_count) {
1014 return sizeof(HeapEntry) * entries_count // NOLINT
1015 + sizeof(HeapGraphEdge) * children_count // NOLINT
1016 + sizeof(HeapGraphEdge*) * retainers_count; // NOLINT
1017}
1018
1019
1020static void DeleteHeapGraphPath(HeapGraphPath** path_ptr) {
1021 delete *path_ptr;
1022}
1023
1024void HeapEntryCalculatedData::Dispose() {
1025 if (retaining_paths_ != NULL) retaining_paths_->Iterate(DeleteHeapGraphPath);
1026 delete retaining_paths_;
1027}
1028
1029
1030int HeapEntryCalculatedData::ReachableSize(HeapEntry* entry) {
1031 if (reachable_size_ == kUnknownSize) CalculateSizes(entry);
1032 return reachable_size_;
1033}
1034
1035
1036int HeapEntryCalculatedData::RetainedSize(HeapEntry* entry) {
1037 if (retained_size_ == kUnknownSize) CalculateSizes(entry);
1038 return retained_size_;
1039}
1040
1041
1042class ReachableSizeCalculator {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001043 public:
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001044 ReachableSizeCalculator()
1045 : reachable_size_(0) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001046 }
1047
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001048 int reachable_size() const { return reachable_size_; }
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001049
1050 void Apply(HeapEntry* entry) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001051 reachable_size_ += entry->self_size();
1052 }
1053
1054 private:
1055 int reachable_size_;
1056};
1057
1058class RetainedSizeCalculator {
1059 public:
1060 RetainedSizeCalculator()
1061 : retained_size_(0) {
1062 }
1063
1064 int reained_size() const { return retained_size_; }
1065
1066 void Apply(HeapEntry** entry_ptr) {
1067 if ((*entry_ptr)->painted_reachable()) {
1068 retained_size_ += (*entry_ptr)->self_size();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001069 }
1070 }
1071
1072 private:
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001073 int retained_size_;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001074};
1075
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001076void HeapEntryCalculatedData::CalculateSizes(HeapEntry* entry) {
1077 // To calculate retained size, first we paint all reachable nodes in
1078 // one color (and calculate reachable size as a byproduct), then we
1079 // paint (or re-paint) all nodes reachable from other nodes with a
1080 // different color. Then we consider only nodes painted with the
1081 // first color for calculating the retained size.
1082 entry->snapshot()->ClearPaint();
1083 ReachableSizeCalculator rch_size_calc;
1084 entry->ApplyAndPaintAllReachable(&rch_size_calc);
1085 reachable_size_ = rch_size_calc.reachable_size();
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001086
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001087 List<HeapEntry*> list(10);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001088 HeapEntry* root = entry->snapshot()->root();
1089 if (entry != root) {
1090 list.Add(root);
1091 root->paint_reachable_from_others();
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001092 }
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001093 while (!list.is_empty()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001094 HeapEntry* curr = list.RemoveLast();
1095 Vector<HeapGraphEdge> children = curr->children();
1096 for (int i = 0; i < children.length(); ++i) {
1097 HeapEntry* child = children[i].to();
1098 if (child != entry && child->not_painted_reachable_from_others()) {
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001099 list.Add(child);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001100 child->paint_reachable_from_others();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001101 }
1102 }
1103 }
1104
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001105 RetainedSizeCalculator ret_size_calc;
1106 entry->snapshot()->IterateEntries(&ret_size_calc);
1107 retained_size_ = ret_size_calc.reained_size();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001108}
1109
1110
1111class CachedHeapGraphPath {
1112 public:
1113 CachedHeapGraphPath()
1114 : nodes_(NodesMatch) { }
1115 CachedHeapGraphPath(const CachedHeapGraphPath& src)
1116 : nodes_(NodesMatch, &HashMap::DefaultAllocator, src.nodes_.capacity()),
1117 path_(src.path_.length() + 1) {
1118 for (HashMap::Entry* p = src.nodes_.Start();
1119 p != NULL;
1120 p = src.nodes_.Next(p)) {
1121 nodes_.Lookup(p->key, p->hash, true);
1122 }
1123 path_.AddAll(src.path_);
1124 }
1125 void Add(HeapGraphEdge* edge) {
1126 nodes_.Lookup(edge->to(), Hash(edge->to()), true);
1127 path_.Add(edge);
1128 }
1129 bool ContainsNode(HeapEntry* node) {
1130 return nodes_.Lookup(node, Hash(node), false) != NULL;
1131 }
1132 const List<HeapGraphEdge*>* path() const { return &path_; }
1133
1134 private:
1135 static uint32_t Hash(HeapEntry* entry) {
1136 return static_cast<uint32_t>(reinterpret_cast<intptr_t>(entry));
1137 }
1138 static bool NodesMatch(void* key1, void* key2) { return key1 == key2; }
1139
1140 HashMap nodes_;
1141 List<HeapGraphEdge*> path_;
1142};
1143
1144
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001145List<HeapGraphPath*>* HeapEntryCalculatedData::GetRetainingPaths(
1146 HeapEntry* entry) {
1147 if (retaining_paths_ == NULL) retaining_paths_ = new List<HeapGraphPath*>(4);
1148 if (retaining_paths_->length() == 0 && entry->retainers().length() != 0) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001149 CachedHeapGraphPath path;
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001150 FindRetainingPaths(entry, &path);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001151 }
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001152 return retaining_paths_;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001153}
1154
1155
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001156void HeapEntryCalculatedData::FindRetainingPaths(
1157 HeapEntry* entry,
1158 CachedHeapGraphPath* prev_path) {
1159 Vector<HeapGraphEdge*> retainers = entry->retainers();
1160 for (int i = 0; i < retainers.length(); ++i) {
1161 HeapGraphEdge* ret_edge = retainers[i];
1162 if (prev_path->ContainsNode(ret_edge->From())) continue;
1163 if (ret_edge->From() != entry->snapshot()->root()) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001164 CachedHeapGraphPath path(*prev_path);
1165 path.Add(ret_edge);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001166 FindRetainingPaths(ret_edge->From(), &path);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001167 } else {
1168 HeapGraphPath* ret_path = new HeapGraphPath(*prev_path->path());
1169 ret_path->Set(0, ret_edge);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001170 retaining_paths_->Add(ret_path);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001171 }
1172 }
1173}
1174
1175
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001176HeapGraphPath::HeapGraphPath(const List<HeapGraphEdge*>& path)
1177 : path_(path.length() + 1) {
1178 Add(NULL);
1179 for (int i = path.length() - 1; i >= 0; --i) {
1180 Add(path[i]);
1181 }
1182}
1183
1184
1185void HeapGraphPath::Print() {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001186 path_[0]->From()->Print(1, 0);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001187 for (int i = 0; i < path_.length(); ++i) {
1188 OS::Print(" -> ");
1189 HeapGraphEdge* edge = path_[i];
1190 switch (edge->type()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001191 case HeapGraphEdge::kContextVariable:
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001192 OS::Print("[#%s] ", edge->name());
1193 break;
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001194 case HeapGraphEdge::kElement:
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001195 OS::Print("[%d] ", edge->index());
1196 break;
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001197 case HeapGraphEdge::kInternal:
ricow@chromium.org5ad5ace2010-06-23 09:06:43 +00001198 OS::Print("[$%s] ", edge->name());
1199 break;
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001200 case HeapGraphEdge::kProperty:
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001201 OS::Print("[%s] ", edge->name());
1202 break;
1203 default:
1204 OS::Print("!!! unknown edge type: %d ", edge->type());
1205 }
1206 edge->to()->Print(1, 0);
1207 }
1208 OS::Print("\n");
1209}
1210
1211
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001212HeapObject *const HeapSnapshot::kInternalRootObject =
1213 reinterpret_cast<HeapObject*>(1);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001214
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001215
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001216// It is very important to keep objects that form a heap snapshot
1217// as small as possible.
1218namespace { // Avoid littering the global namespace.
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001219
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001220template <size_t ptr_size> struct SnapshotSizeConstants;
1221
1222template <> struct SnapshotSizeConstants<4> {
1223 static const int kExpectedHeapGraphEdgeSize = 12;
1224 static const int kExpectedHeapEntrySize = 32;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001225};
1226
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001227template <> struct SnapshotSizeConstants<8> {
1228 static const int kExpectedHeapGraphEdgeSize = 24;
1229 static const int kExpectedHeapEntrySize = 40;
1230};
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001231
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001232} // namespace
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001233
1234HeapSnapshot::HeapSnapshot(HeapSnapshotsCollection* collection,
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001235 HeapSnapshot::Type type,
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001236 const char* title,
1237 unsigned uid)
1238 : collection_(collection),
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001239 type_(type),
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001240 title_(title),
1241 uid_(uid),
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00001242 root_entry_(NULL),
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001243 raw_entries_(NULL),
1244 entries_sorted_(false) {
1245 STATIC_ASSERT(
1246 sizeof(HeapGraphEdge) ==
1247 SnapshotSizeConstants<sizeof(void*)>::kExpectedHeapGraphEdgeSize); // NOLINT
1248 STATIC_ASSERT(
1249 sizeof(HeapEntry) ==
1250 SnapshotSizeConstants<sizeof(void*)>::kExpectedHeapEntrySize); // NOLINT
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001251}
1252
1253
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001254static void DisposeCalculatedData(HeapEntryCalculatedData* cdata) {
1255 cdata->Dispose();
1256}
1257
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001258HeapSnapshot::~HeapSnapshot() {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001259 DeleteArray(raw_entries_);
1260 calculated_data_.Iterate(DisposeCalculatedData);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001261}
1262
1263
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001264void HeapSnapshot::AllocateEntries(int entries_count,
1265 int children_count,
1266 int retainers_count) {
1267 ASSERT(raw_entries_ == NULL);
1268 raw_entries_ = NewArray<char>(
1269 HeapEntry::EntriesSize(entries_count, children_count, retainers_count));
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001270#ifdef DEBUG
1271 raw_entries_size_ =
1272 HeapEntry::EntriesSize(entries_count, children_count, retainers_count);
1273#endif
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001274}
1275
1276
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001277HeapEntry* HeapSnapshot::AddEntry(HeapObject* object,
1278 int children_count,
1279 int retainers_count) {
1280 if (object == kInternalRootObject) {
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00001281 ASSERT(root_entry_ == NULL);
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001282 ASSERT(retainers_count == 0);
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00001283 root_entry_ = AddEntry(
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001284 HeapEntry::kInternal, "", 0, 0, children_count, retainers_count);
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00001285 return root_entry_;
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001286 } else if (object->IsJSFunction()) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001287 JSFunction* func = JSFunction::cast(object);
1288 SharedFunctionInfo* shared = func->shared();
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001289 return AddEntry(object,
1290 HeapEntry::kClosure,
vegorov@chromium.org42841962010-10-18 11:18:59 +00001291 collection_->GetName(String::cast(shared->name())),
1292 children_count,
1293 retainers_count);
1294 } else if (object->IsJSRegExp()) {
1295 JSRegExp* re = JSRegExp::cast(object);
1296 return AddEntry(object,
1297 HeapEntry::kRegExp,
1298 collection_->GetName(re->Pattern()),
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001299 children_count,
1300 retainers_count);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001301 } else if (object->IsJSObject()) {
1302 return AddEntry(object,
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001303 HeapEntry::kObject,
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001304 collection_->GetName(
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001305 JSObject::cast(object)->constructor_name()),
1306 children_count,
1307 retainers_count);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001308 } else if (object->IsString()) {
1309 return AddEntry(object,
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001310 HeapEntry::kString,
1311 collection_->GetName(String::cast(object)),
1312 children_count,
1313 retainers_count);
whesse@chromium.org2c186ca2010-06-16 11:32:39 +00001314 } else if (object->IsCode()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001315 return AddEntry(object,
1316 HeapEntry::kCode,
1317 "",
1318 children_count,
1319 retainers_count);
whesse@chromium.org2c186ca2010-06-16 11:32:39 +00001320 } else if (object->IsSharedFunctionInfo()) {
1321 SharedFunctionInfo* shared = SharedFunctionInfo::cast(object);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001322 return AddEntry(object,
1323 HeapEntry::kCode,
lrn@chromium.org303ada72010-10-27 09:33:13 +00001324 collection_->GetName(String::cast(shared->name())),
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001325 children_count,
1326 retainers_count);
whesse@chromium.org2c186ca2010-06-16 11:32:39 +00001327 } else if (object->IsScript()) {
1328 Script* script = Script::cast(object);
1329 return AddEntry(object,
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001330 HeapEntry::kCode,
whesse@chromium.org2c186ca2010-06-16 11:32:39 +00001331 script->name()->IsString() ?
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001332 collection_->GetName(String::cast(script->name())) : "",
1333 children_count,
1334 retainers_count);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001335 } else if (object->IsFixedArray()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001336 return AddEntry(object,
1337 HeapEntry::kArray,
1338 "",
1339 children_count,
1340 retainers_count);
vegorov@chromium.org42841962010-10-18 11:18:59 +00001341 } else if (object->IsHeapNumber()) {
1342 return AddEntry(object,
1343 HeapEntry::kHeapNumber,
1344 "number",
1345 children_count,
1346 retainers_count);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001347 }
1348 // No interest in this object.
1349 return NULL;
1350}
1351
1352
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001353bool HeapSnapshot::WillAddEntry(HeapObject* object) {
1354 return object == kInternalRootObject
1355 || object->IsJSFunction()
vegorov@chromium.org42841962010-10-18 11:18:59 +00001356 || object->IsJSRegExp()
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001357 || object->IsJSObject()
1358 || object->IsString()
1359 || object->IsCode()
1360 || object->IsSharedFunctionInfo()
1361 || object->IsScript()
vegorov@chromium.org42841962010-10-18 11:18:59 +00001362 || object->IsFixedArray()
1363 || object->IsHeapNumber();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001364}
1365
1366
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001367static void HeapEntryClearPaint(HeapEntry** entry_ptr) {
1368 (*entry_ptr)->clear_paint();
1369}
1370
1371void HeapSnapshot::ClearPaint() {
1372 entries_.Iterate(HeapEntryClearPaint);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001373}
1374
1375
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001376int HeapSnapshot::AddCalculatedData() {
1377 calculated_data_.Add(HeapEntryCalculatedData());
1378 return calculated_data_.length() - 1;
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001379}
1380
1381
1382HeapEntry* HeapSnapshot::AddEntry(HeapObject* object,
1383 HeapEntry::Type type,
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001384 const char* name,
1385 int children_count,
1386 int retainers_count) {
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001387 return AddEntry(type,
1388 name,
1389 collection_->GetObjectId(object->address()),
1390 GetObjectSize(object),
1391 children_count,
1392 retainers_count);
1393}
1394
1395
1396HeapEntry* HeapSnapshot::AddEntry(HeapEntry::Type type,
1397 const char* name,
1398 uint64_t id,
1399 int size,
1400 int children_count,
1401 int retainers_count) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001402 HeapEntry* entry = GetNextEntryToInit();
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001403 entry->Init(this, type, name, id, size, children_count, retainers_count);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001404 return entry;
1405}
1406
1407
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001408HeapEntry* HeapSnapshot::GetNextEntryToInit() {
1409 if (entries_.length() > 0) {
1410 HeapEntry* last_entry = entries_.last();
1411 entries_.Add(reinterpret_cast<HeapEntry*>(
1412 reinterpret_cast<char*>(last_entry) + last_entry->EntrySize()));
1413 } else {
1414 entries_.Add(reinterpret_cast<HeapEntry*>(raw_entries_));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001415 }
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001416 ASSERT(reinterpret_cast<char*>(entries_.last()) <
1417 (raw_entries_ + raw_entries_size_));
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001418 return entries_.last();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001419}
1420
1421
1422int HeapSnapshot::GetObjectSize(HeapObject* obj) {
1423 return obj->IsJSObject() ?
1424 CalculateNetworkSize(JSObject::cast(obj)) : obj->Size();
1425}
1426
1427
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001428int HeapSnapshot::CalculateNetworkSize(JSObject* obj) {
1429 int size = obj->Size();
1430 // If 'properties' and 'elements' are non-empty (thus, non-shared),
1431 // take their size into account.
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001432 if (obj->properties() != Heap::empty_fixed_array()) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001433 size += obj->properties()->Size();
1434 }
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001435 if (obj->elements() != Heap::empty_fixed_array()) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001436 size += obj->elements()->Size();
1437 }
1438 // For functions, also account non-empty context and literals sizes.
1439 if (obj->IsJSFunction()) {
1440 JSFunction* f = JSFunction::cast(obj);
1441 if (f->unchecked_context()->IsContext()) {
1442 size += f->context()->Size();
1443 }
1444 if (f->literals()->length() != 0) {
1445 size += f->literals()->Size();
1446 }
1447 }
1448 return size;
1449}
1450
1451
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001452HeapSnapshotsDiff* HeapSnapshot::CompareWith(HeapSnapshot* snapshot) {
1453 return collection_->CompareSnapshots(this, snapshot);
1454}
1455
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001456
1457template<class T>
1458static int SortByIds(const T* entry1_ptr,
1459 const T* entry2_ptr) {
1460 if ((*entry1_ptr)->id() == (*entry2_ptr)->id()) return 0;
1461 return (*entry1_ptr)->id() < (*entry2_ptr)->id() ? -1 : 1;
1462}
1463
1464List<HeapEntry*>* HeapSnapshot::GetSortedEntriesList() {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001465 if (!entries_sorted_) {
1466 entries_.Sort(SortByIds);
1467 entries_sorted_ = true;
1468 }
1469 return &entries_;
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001470}
1471
1472
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001473void HeapSnapshot::Print(int max_depth) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001474 root()->Print(max_depth, 0);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001475}
1476
1477
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001478HeapObjectsMap::HeapObjectsMap()
1479 : initial_fill_mode_(true),
1480 next_id_(1),
1481 entries_map_(AddressesMatch),
1482 entries_(new List<EntryInfo>()) { }
1483
1484
1485HeapObjectsMap::~HeapObjectsMap() {
1486 delete entries_;
1487}
1488
1489
1490void HeapObjectsMap::SnapshotGenerationFinished() {
1491 initial_fill_mode_ = false;
1492 RemoveDeadEntries();
1493}
1494
1495
1496uint64_t HeapObjectsMap::FindObject(Address addr) {
1497 if (!initial_fill_mode_) {
1498 uint64_t existing = FindEntry(addr);
1499 if (existing != 0) return existing;
1500 }
1501 uint64_t id = next_id_++;
1502 AddEntry(addr, id);
1503 return id;
1504}
1505
1506
1507void HeapObjectsMap::MoveObject(Address from, Address to) {
1508 if (from == to) return;
1509 HashMap::Entry* entry = entries_map_.Lookup(from, AddressHash(from), false);
1510 if (entry != NULL) {
1511 void* value = entry->value;
1512 entries_map_.Remove(from, AddressHash(from));
1513 entry = entries_map_.Lookup(to, AddressHash(to), true);
1514 // We can have an entry at the new location, it is OK, as GC can overwrite
1515 // dead objects with alive objects being moved.
1516 entry->value = value;
1517 }
1518}
1519
1520
1521void HeapObjectsMap::AddEntry(Address addr, uint64_t id) {
1522 HashMap::Entry* entry = entries_map_.Lookup(addr, AddressHash(addr), true);
1523 ASSERT(entry->value == NULL);
1524 entry->value = reinterpret_cast<void*>(entries_->length());
1525 entries_->Add(EntryInfo(id));
1526}
1527
1528
1529uint64_t HeapObjectsMap::FindEntry(Address addr) {
1530 HashMap::Entry* entry = entries_map_.Lookup(addr, AddressHash(addr), false);
1531 if (entry != NULL) {
1532 int entry_index =
1533 static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
1534 EntryInfo& entry_info = entries_->at(entry_index);
1535 entry_info.accessed = true;
1536 return entry_info.id;
1537 } else {
1538 return 0;
1539 }
1540}
1541
1542
1543void HeapObjectsMap::RemoveDeadEntries() {
1544 List<EntryInfo>* new_entries = new List<EntryInfo>();
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001545 List<void*> dead_entries;
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001546 for (HashMap::Entry* entry = entries_map_.Start();
1547 entry != NULL;
1548 entry = entries_map_.Next(entry)) {
1549 int entry_index =
1550 static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
1551 EntryInfo& entry_info = entries_->at(entry_index);
1552 if (entry_info.accessed) {
1553 entry->value = reinterpret_cast<void*>(new_entries->length());
1554 new_entries->Add(EntryInfo(entry_info.id, false));
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001555 } else {
1556 dead_entries.Add(entry->key);
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001557 }
1558 }
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001559 for (int i = 0; i < dead_entries.length(); ++i) {
1560 void* raw_entry = dead_entries[i];
1561 entries_map_.Remove(
1562 raw_entry, AddressHash(reinterpret_cast<Address>(raw_entry)));
1563 }
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001564 delete entries_;
1565 entries_ = new_entries;
1566}
1567
1568
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001569HeapSnapshotsCollection::HeapSnapshotsCollection()
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001570 : is_tracking_objects_(false),
1571 snapshots_uids_(HeapSnapshotsMatch),
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001572 token_enumerator_(new TokenEnumerator()) {
1573}
1574
1575
1576static void DeleteHeapSnapshot(HeapSnapshot** snapshot_ptr) {
1577 delete *snapshot_ptr;
1578}
1579
1580
1581HeapSnapshotsCollection::~HeapSnapshotsCollection() {
1582 delete token_enumerator_;
1583 snapshots_.Iterate(DeleteHeapSnapshot);
1584}
1585
1586
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001587HeapSnapshot* HeapSnapshotsCollection::NewSnapshot(HeapSnapshot::Type type,
1588 const char* name,
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001589 unsigned uid) {
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001590 is_tracking_objects_ = true; // Start watching for heap objects moves.
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001591 HeapSnapshot* snapshot = new HeapSnapshot(this, type, name, uid);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001592 snapshots_.Add(snapshot);
1593 HashMap::Entry* entry =
1594 snapshots_uids_.Lookup(reinterpret_cast<void*>(snapshot->uid()),
1595 static_cast<uint32_t>(snapshot->uid()),
1596 true);
1597 ASSERT(entry->value == NULL);
1598 entry->value = snapshot;
1599 return snapshot;
1600}
1601
1602
1603HeapSnapshot* HeapSnapshotsCollection::GetSnapshot(unsigned uid) {
1604 HashMap::Entry* entry = snapshots_uids_.Lookup(reinterpret_cast<void*>(uid),
1605 static_cast<uint32_t>(uid),
1606 false);
1607 return entry != NULL ? reinterpret_cast<HeapSnapshot*>(entry->value) : NULL;
1608}
1609
1610
ricow@chromium.org4980dff2010-07-19 08:33:45 +00001611HeapSnapshotsDiff* HeapSnapshotsCollection::CompareSnapshots(
1612 HeapSnapshot* snapshot1,
1613 HeapSnapshot* snapshot2) {
1614 return comparator_.Compare(snapshot1, snapshot2);
1615}
1616
1617
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001618HeapEntry *const HeapEntriesMap::kHeapEntryPlaceholder =
1619 reinterpret_cast<HeapEntry*>(1);
1620
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001621HeapEntriesMap::HeapEntriesMap()
1622 : entries_(HeapObjectsMatch),
1623 entries_count_(0),
1624 total_children_count_(0),
1625 total_retainers_count_(0) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001626}
1627
1628
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001629HeapEntriesMap::~HeapEntriesMap() {
1630 for (HashMap::Entry* p = entries_.Start(); p != NULL; p = entries_.Next(p)) {
1631 if (!IsAlias(p->value)) delete reinterpret_cast<EntryInfo*>(p->value);
1632 }
1633}
1634
1635
1636void HeapEntriesMap::Alias(HeapObject* from, HeapObject* to) {
1637 HashMap::Entry* from_cache_entry = entries_.Lookup(from, Hash(from), true);
1638 HashMap::Entry* to_cache_entry = entries_.Lookup(to, Hash(to), false);
1639 if (from_cache_entry->value == NULL) {
1640 ASSERT(to_cache_entry != NULL);
1641 from_cache_entry->value = MakeAlias(to_cache_entry->value);
1642 }
1643}
1644
1645
1646HeapEntry* HeapEntriesMap::Map(HeapObject* object) {
1647 HashMap::Entry* cache_entry = entries_.Lookup(object, Hash(object), false);
1648 if (cache_entry != NULL) {
1649 EntryInfo* entry_info =
1650 reinterpret_cast<EntryInfo*>(Unalias(cache_entry->value));
1651 return entry_info->entry;
1652 } else {
1653 return NULL;
1654 }
1655}
1656
1657
1658void HeapEntriesMap::Pair(HeapObject* object, HeapEntry* entry) {
1659 HashMap::Entry* cache_entry = entries_.Lookup(object, Hash(object), true);
1660 ASSERT(cache_entry->value == NULL);
1661 cache_entry->value = new EntryInfo(entry);
1662 ++entries_count_;
1663}
1664
1665
1666void HeapEntriesMap::CountReference(HeapObject* from, HeapObject* to,
1667 int* prev_children_count,
1668 int* prev_retainers_count) {
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001669 HashMap::Entry* from_cache_entry = entries_.Lookup(from, Hash(from), false);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001670 HashMap::Entry* to_cache_entry = entries_.Lookup(to, Hash(to), false);
1671 ASSERT(from_cache_entry != NULL);
1672 ASSERT(to_cache_entry != NULL);
1673 EntryInfo* from_entry_info =
1674 reinterpret_cast<EntryInfo*>(Unalias(from_cache_entry->value));
1675 EntryInfo* to_entry_info =
1676 reinterpret_cast<EntryInfo*>(Unalias(to_cache_entry->value));
1677 if (prev_children_count)
1678 *prev_children_count = from_entry_info->children_count;
1679 if (prev_retainers_count)
1680 *prev_retainers_count = to_entry_info->retainers_count;
1681 ++from_entry_info->children_count;
1682 ++to_entry_info->retainers_count;
1683 ++total_children_count_;
1684 ++total_retainers_count_;
1685}
1686
1687
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001688HeapSnapshotGenerator::HeapSnapshotGenerator(HeapSnapshot* snapshot)
1689 : snapshot_(snapshot),
1690 collection_(snapshot->collection()),
1691 filler_(NULL) {
1692}
1693
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001694class SnapshotCounter : public HeapSnapshotGenerator::SnapshotFillerInterface {
1695 public:
1696 explicit SnapshotCounter(HeapEntriesMap* entries)
1697 : entries_(entries) { }
1698 HeapEntry* AddEntry(HeapObject* obj) {
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00001699 entries_->Pair(obj, HeapEntriesMap::kHeapEntryPlaceholder);
1700 return HeapEntriesMap::kHeapEntryPlaceholder;
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001701 }
1702 void SetElementReference(HeapObject* parent_obj,
1703 HeapEntry*,
1704 int,
1705 Object* child_obj,
1706 HeapEntry*) {
1707 entries_->CountReference(parent_obj, HeapObject::cast(child_obj));
1708 }
1709 void SetNamedReference(HeapGraphEdge::Type,
1710 HeapObject* parent_obj,
1711 HeapEntry*,
1712 const char*,
1713 Object* child_obj,
1714 HeapEntry*) {
1715 entries_->CountReference(parent_obj, HeapObject::cast(child_obj));
1716 }
1717 void SetRootReference(Object* child_obj, HeapEntry*) {
1718 entries_->CountReference(
1719 HeapSnapshot::kInternalRootObject, HeapObject::cast(child_obj));
1720 }
1721 private:
1722 HeapEntriesMap* entries_;
1723};
1724
1725
1726class SnapshotFiller : public HeapSnapshotGenerator::SnapshotFillerInterface {
1727 public:
1728 explicit SnapshotFiller(HeapSnapshot* snapshot, HeapEntriesMap* entries)
1729 : snapshot_(snapshot),
1730 collection_(snapshot->collection()),
1731 entries_(entries) { }
1732 HeapEntry* AddEntry(HeapObject* obj) {
1733 UNREACHABLE();
1734 return NULL;
1735 }
1736 void SetElementReference(HeapObject* parent_obj,
1737 HeapEntry* parent_entry,
1738 int index,
1739 Object* child_obj,
1740 HeapEntry* child_entry) {
1741 int child_index, retainer_index;
1742 entries_->CountReference(parent_obj, HeapObject::cast(child_obj),
1743 &child_index, &retainer_index);
1744 parent_entry->SetElementReference(
1745 child_index, index, child_entry, retainer_index);
1746 }
1747 void SetNamedReference(HeapGraphEdge::Type type,
1748 HeapObject* parent_obj,
1749 HeapEntry* parent_entry,
1750 const char* reference_name,
1751 Object* child_obj,
1752 HeapEntry* child_entry) {
1753 int child_index, retainer_index;
1754 entries_->CountReference(parent_obj, HeapObject::cast(child_obj),
1755 &child_index, &retainer_index);
1756 parent_entry->SetNamedReference(type,
1757 child_index,
1758 reference_name,
1759 child_entry,
1760 retainer_index);
1761 }
1762 void SetRootReference(Object* child_obj, HeapEntry* child_entry) {
1763 int child_index, retainer_index;
1764 entries_->CountReference(
1765 HeapSnapshot::kInternalRootObject, HeapObject::cast(child_obj),
1766 &child_index, &retainer_index);
1767 snapshot_->root()->SetElementReference(
1768 child_index, child_index + 1, child_entry, retainer_index);
1769 }
1770 private:
1771 HeapSnapshot* snapshot_;
1772 HeapSnapshotsCollection* collection_;
1773 HeapEntriesMap* entries_;
1774};
1775
1776class SnapshotAllocator {
1777 public:
1778 explicit SnapshotAllocator(HeapSnapshot* snapshot)
1779 : snapshot_(snapshot) { }
1780 HeapEntry* GetEntry(
1781 HeapObject* obj, int children_count, int retainers_count) {
1782 HeapEntry* entry =
1783 snapshot_->AddEntry(obj, children_count, retainers_count);
1784 ASSERT(entry != NULL);
1785 return entry;
1786 }
1787 private:
1788 HeapSnapshot* snapshot_;
1789};
1790
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001791void HeapSnapshotGenerator::GenerateSnapshot() {
1792 AssertNoAllocation no_alloc;
1793
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001794 // Pass 1. Iterate heap contents to count entries and references.
1795 SnapshotCounter counter(&entries_);
1796 filler_ = &counter;
1797 filler_->AddEntry(HeapSnapshot::kInternalRootObject);
1798 HeapIterator iterator1;
1799 for (HeapObject* obj = iterator1.next();
1800 obj != NULL;
1801 obj = iterator1.next()) {
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001802 ExtractReferences(obj);
1803 }
1804
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001805 // Allocate and fill entries in the snapshot, allocate references.
1806 snapshot_->AllocateEntries(entries_.entries_count(),
1807 entries_.total_children_count(),
1808 entries_.total_retainers_count());
1809 SnapshotAllocator allocator(snapshot_);
1810 entries_.UpdateEntries(&allocator);
1811
1812 // Pass 2. Fill references.
1813 SnapshotFiller filler(snapshot_, &entries_);
1814 filler_ = &filler;
1815 HeapIterator iterator2;
1816 for (HeapObject* obj = iterator2.next();
1817 obj != NULL;
1818 obj = iterator2.next()) {
1819 ExtractReferences(obj);
1820 }
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001821}
1822
1823
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001824HeapEntry* HeapSnapshotGenerator::GetEntry(Object* obj) {
1825 if (!obj->IsHeapObject()) return NULL;
1826 HeapObject* object = HeapObject::cast(obj);
1827 HeapEntry* entry = entries_.Map(object);
1828
1829 // A new entry.
1830 if (entry == NULL) {
1831 if (obj->IsJSGlobalPropertyCell()) {
1832 Object* cell_target = JSGlobalPropertyCell::cast(obj)->value();
1833 entry = GetEntry(cell_target);
1834 // If GPC references an object that we have interest in (see
1835 // HeapSnapshot::AddEntry, WillAddEntry), add the object. We
1836 // don't store HeapEntries for GPCs. Instead, we make our hash
1837 // map to point to object's HeapEntry by GPCs address.
1838 if (entry != NULL) {
1839 entries_.Alias(object, HeapObject::cast(cell_target));
1840 }
1841 return entry;
1842 }
1843
1844 if (snapshot_->WillAddEntry(object)) entry = filler_->AddEntry(object);
1845 }
1846
1847 return entry;
1848}
1849
1850
1851int HeapSnapshotGenerator::GetGlobalSecurityToken() {
1852 return collection_->token_enumerator()->GetTokenId(
1853 Top::context()->global()->global_context()->security_token());
1854}
1855
1856
1857int HeapSnapshotGenerator::GetObjectSecurityToken(HeapObject* obj) {
1858 if (obj->IsGlobalContext()) {
1859 return collection_->token_enumerator()->GetTokenId(
1860 Context::cast(obj)->security_token());
1861 } else {
1862 return TokenEnumerator::kNoSecurityToken;
1863 }
1864}
1865
1866
1867class IndexedReferencesExtractor : public ObjectVisitor {
1868 public:
1869 IndexedReferencesExtractor(HeapSnapshotGenerator* generator,
1870 HeapObject* parent_obj,
1871 HeapEntry* parent_entry)
1872 : generator_(generator),
1873 parent_obj_(parent_obj),
1874 parent_(parent_entry),
1875 next_index_(1) {
1876 }
1877
1878 void VisitPointer(Object** o) {
1879 generator_->SetElementReference(parent_obj_, parent_, next_index_++, *o);
1880 }
1881
1882 void VisitPointers(Object** start, Object** end) {
1883 for (Object** p = start; p < end; p++) VisitPointer(p);
1884 }
1885
1886 private:
1887 HeapSnapshotGenerator* generator_;
1888 HeapObject* parent_obj_;
1889 HeapEntry* parent_;
1890 int next_index_;
1891};
1892
1893
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001894void HeapSnapshotGenerator::ExtractReferences(HeapObject* obj) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001895 // We need to reference JS global objects from snapshot's root.
1896 // We also need to only include global objects from the current
1897 // security context. And we don't want to add the global proxy,
1898 // as we don't have a special type for it.
1899 if (obj->IsJSGlobalProxy()) {
1900 int global_security_token = GetGlobalSecurityToken();
1901 JSGlobalProxy* proxy = JSGlobalProxy::cast(obj);
1902 int object_security_token =
1903 collection_->token_enumerator()->GetTokenId(
1904 Context::cast(proxy->context())->security_token());
1905 if (object_security_token == TokenEnumerator::kNoSecurityToken
1906 || object_security_token == global_security_token) {
1907 SetRootReference(proxy->map()->prototype());
1908 }
1909 return;
1910 }
1911
1912 HeapEntry* entry = GetEntry(obj);
1913 if (entry == NULL) return; // No interest in this object.
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001914
1915 if (obj->IsJSObject()) {
1916 JSObject* js_obj = JSObject::cast(obj);
1917 ExtractClosureReferences(js_obj, entry);
1918 ExtractPropertyReferences(js_obj, entry);
1919 ExtractElementReferences(js_obj, entry);
vegorov@chromium.org42841962010-10-18 11:18:59 +00001920 ExtractInternalReferences(js_obj, entry);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001921 SetPropertyReference(
vegorov@chromium.org42841962010-10-18 11:18:59 +00001922 obj, entry, Heap::Proto_symbol(), js_obj->GetPrototype());
1923 if (obj->IsJSFunction()) {
1924 JSFunction* js_fun = JSFunction::cast(obj);
1925 if (js_fun->has_prototype()) {
1926 SetPropertyReference(
1927 obj, entry, Heap::prototype_symbol(), js_fun->prototype());
1928 }
1929 }
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001930 } else if (obj->IsString()) {
1931 if (obj->IsConsString()) {
1932 ConsString* cs = ConsString::cast(obj);
vegorov@chromium.org42841962010-10-18 11:18:59 +00001933 SetInternalReference(obj, entry, "1", cs->first());
1934 SetInternalReference(obj, entry, "2", cs->second());
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001935 }
1936 } else if (obj->IsCode() || obj->IsSharedFunctionInfo() || obj->IsScript()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001937 IndexedReferencesExtractor refs_extractor(this, obj, entry);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001938 obj->Iterate(&refs_extractor);
1939 } else if (obj->IsFixedArray()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001940 IndexedReferencesExtractor refs_extractor(this, obj, entry);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001941 obj->Iterate(&refs_extractor);
1942 }
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001943}
1944
1945
1946void HeapSnapshotGenerator::ExtractClosureReferences(JSObject* js_obj,
1947 HeapEntry* entry) {
1948 if (js_obj->IsJSFunction()) {
1949 HandleScope hs;
1950 JSFunction* func = JSFunction::cast(js_obj);
1951 Context* context = func->context();
1952 ZoneScope zscope(DELETE_ON_EXIT);
ager@chromium.orgb5737492010-07-15 09:29:43 +00001953 SerializedScopeInfo* serialized_scope_info =
1954 context->closure()->shared()->scope_info();
1955 ScopeInfo<ZoneListAllocationPolicy> zone_scope_info(serialized_scope_info);
ager@chromium.org6a2b0aa2010-07-13 20:58:03 +00001956 int locals_number = zone_scope_info.NumberOfLocals();
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001957 for (int i = 0; i < locals_number; ++i) {
ager@chromium.org6a2b0aa2010-07-13 20:58:03 +00001958 String* local_name = *zone_scope_info.LocalName(i);
ager@chromium.orgb5737492010-07-15 09:29:43 +00001959 int idx = serialized_scope_info->ContextSlotIndex(local_name, NULL);
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001960 if (idx >= 0 && idx < context->length()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001961 SetClosureReference(js_obj, entry, local_name, context->get(idx));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001962 }
1963 }
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001964 SetInternalReference(js_obj, entry, "code", func->shared());
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001965 }
1966}
1967
1968
1969void HeapSnapshotGenerator::ExtractPropertyReferences(JSObject* js_obj,
1970 HeapEntry* entry) {
1971 if (js_obj->HasFastProperties()) {
1972 DescriptorArray* descs = js_obj->map()->instance_descriptors();
1973 for (int i = 0; i < descs->number_of_descriptors(); i++) {
1974 switch (descs->GetType(i)) {
1975 case FIELD: {
1976 int index = descs->GetFieldIndex(i);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001977 SetPropertyReference(
1978 js_obj, entry, descs->GetKey(i), js_obj->FastPropertyAt(index));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001979 break;
1980 }
1981 case CONSTANT_FUNCTION:
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001982 SetPropertyReference(
1983 js_obj, entry, descs->GetKey(i), descs->GetConstantFunction(i));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001984 break;
1985 default: ;
1986 }
1987 }
1988 } else {
1989 StringDictionary* dictionary = js_obj->property_dictionary();
1990 int length = dictionary->Capacity();
1991 for (int i = 0; i < length; ++i) {
1992 Object* k = dictionary->KeyAt(i);
1993 if (dictionary->IsKey(k)) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00001994 SetPropertyReference(
1995 js_obj, entry, String::cast(k), dictionary->ValueAt(i));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00001996 }
1997 }
1998 }
1999}
2000
2001
2002void HeapSnapshotGenerator::ExtractElementReferences(JSObject* js_obj,
2003 HeapEntry* entry) {
2004 if (js_obj->HasFastElements()) {
2005 FixedArray* elements = FixedArray::cast(js_obj->elements());
2006 int length = js_obj->IsJSArray() ?
2007 Smi::cast(JSArray::cast(js_obj)->length())->value() :
2008 elements->length();
2009 for (int i = 0; i < length; ++i) {
2010 if (!elements->get(i)->IsTheHole()) {
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002011 SetElementReference(js_obj, entry, i, elements->get(i));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00002012 }
2013 }
2014 } else if (js_obj->HasDictionaryElements()) {
2015 NumberDictionary* dictionary = js_obj->element_dictionary();
2016 int length = dictionary->Capacity();
2017 for (int i = 0; i < length; ++i) {
2018 Object* k = dictionary->KeyAt(i);
2019 if (dictionary->IsKey(k)) {
2020 ASSERT(k->IsNumber());
2021 uint32_t index = static_cast<uint32_t>(k->Number());
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002022 SetElementReference(js_obj, entry, index, dictionary->ValueAt(i));
ager@chromium.org2cc82ae2010-06-14 07:35:38 +00002023 }
2024 }
2025 }
2026}
2027
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002028
vegorov@chromium.org42841962010-10-18 11:18:59 +00002029void HeapSnapshotGenerator::ExtractInternalReferences(JSObject* js_obj,
2030 HeapEntry* entry) {
2031 int length = js_obj->GetInternalFieldCount();
2032 for (int i = 0; i < length; ++i) {
2033 Object* o = js_obj->GetInternalField(i);
2034 SetInternalReference(js_obj, entry, i, o);
2035 }
2036}
2037
2038
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002039void HeapSnapshotGenerator::SetClosureReference(HeapObject* parent_obj,
2040 HeapEntry* parent_entry,
2041 String* reference_name,
2042 Object* child_obj) {
2043 HeapEntry* child_entry = GetEntry(child_obj);
2044 if (child_entry != NULL) {
2045 filler_->SetNamedReference(HeapGraphEdge::kContextVariable,
2046 parent_obj,
2047 parent_entry,
2048 collection_->GetName(reference_name),
2049 child_obj,
2050 child_entry);
2051 }
2052}
2053
2054
2055void HeapSnapshotGenerator::SetElementReference(HeapObject* parent_obj,
2056 HeapEntry* parent_entry,
2057 int index,
2058 Object* child_obj) {
2059 HeapEntry* child_entry = GetEntry(child_obj);
2060 if (child_entry != NULL) {
2061 filler_->SetElementReference(
2062 parent_obj, parent_entry, index, child_obj, child_entry);
2063 }
2064}
2065
2066
2067void HeapSnapshotGenerator::SetInternalReference(HeapObject* parent_obj,
2068 HeapEntry* parent_entry,
2069 const char* reference_name,
2070 Object* child_obj) {
2071 HeapEntry* child_entry = GetEntry(child_obj);
2072 if (child_entry != NULL) {
2073 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2074 parent_obj,
2075 parent_entry,
2076 reference_name,
2077 child_obj,
2078 child_entry);
2079 }
2080}
2081
2082
vegorov@chromium.org42841962010-10-18 11:18:59 +00002083void HeapSnapshotGenerator::SetInternalReference(HeapObject* parent_obj,
2084 HeapEntry* parent_entry,
2085 int index,
2086 Object* child_obj) {
2087 HeapEntry* child_entry = GetEntry(child_obj);
2088 if (child_entry != NULL) {
2089 filler_->SetNamedReference(HeapGraphEdge::kInternal,
2090 parent_obj,
2091 parent_entry,
2092 collection_->GetName(index),
2093 child_obj,
2094 child_entry);
2095 }
2096}
2097
2098
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002099void HeapSnapshotGenerator::SetPropertyReference(HeapObject* parent_obj,
2100 HeapEntry* parent_entry,
2101 String* reference_name,
2102 Object* child_obj) {
2103 HeapEntry* child_entry = GetEntry(child_obj);
2104 if (child_entry != NULL) {
vegorov@chromium.org42841962010-10-18 11:18:59 +00002105 HeapGraphEdge::Type type = reference_name->length() > 0 ?
2106 HeapGraphEdge::kProperty : HeapGraphEdge::kInternal;
2107 filler_->SetNamedReference(type,
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002108 parent_obj,
2109 parent_entry,
2110 collection_->GetName(reference_name),
2111 child_obj,
2112 child_entry);
2113 }
2114}
2115
2116
2117void HeapSnapshotGenerator::SetRootReference(Object* child_obj) {
2118 HeapEntry* child_entry = GetEntry(child_obj);
2119 ASSERT(child_entry != NULL);
2120 filler_->SetRootReference(child_obj, child_entry);
2121}
2122
2123
2124void HeapSnapshotsDiff::CreateRoots(int additions_count, int deletions_count) {
2125 raw_additions_root_ =
2126 NewArray<char>(HeapEntry::EntriesSize(1, additions_count, 0));
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00002127 additions_root()->Init(
2128 snapshot2_, HeapEntry::kInternal, "", 0, 0, additions_count, 0);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002129 raw_deletions_root_ =
2130 NewArray<char>(HeapEntry::EntriesSize(1, deletions_count, 0));
erik.corry@gmail.com145eff52010-08-23 11:36:18 +00002131 deletions_root()->Init(
2132 snapshot1_, HeapEntry::kInternal, "", 0, 0, deletions_count, 0);
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002133}
2134
2135
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002136static void DeleteHeapSnapshotsDiff(HeapSnapshotsDiff** diff_ptr) {
2137 delete *diff_ptr;
2138}
2139
2140HeapSnapshotsComparator::~HeapSnapshotsComparator() {
2141 diffs_.Iterate(DeleteHeapSnapshotsDiff);
2142}
2143
2144
2145HeapSnapshotsDiff* HeapSnapshotsComparator::Compare(HeapSnapshot* snapshot1,
2146 HeapSnapshot* snapshot2) {
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00002147 snapshot1->ClearPaint();
2148 snapshot1->root()->PaintAllReachable();
2149 snapshot2->ClearPaint();
2150 snapshot2->root()->PaintAllReachable();
2151
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002152 List<HeapEntry*>* entries1 = snapshot1->GetSortedEntriesList();
2153 List<HeapEntry*>* entries2 = snapshot2->GetSortedEntriesList();
2154 int i = 0, j = 0;
2155 List<HeapEntry*> added_entries, deleted_entries;
2156 while (i < entries1->length() && j < entries2->length()) {
2157 uint64_t id1 = entries1->at(i)->id();
2158 uint64_t id2 = entries2->at(j)->id();
2159 if (id1 == id2) {
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00002160 HeapEntry* entry1 = entries1->at(i++);
2161 HeapEntry* entry2 = entries2->at(j++);
2162 if (entry1->painted_reachable() != entry2->painted_reachable()) {
2163 if (entry1->painted_reachable())
2164 deleted_entries.Add(entry1);
2165 else
2166 added_entries.Add(entry2);
2167 }
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002168 } else if (id1 < id2) {
2169 HeapEntry* entry = entries1->at(i++);
2170 deleted_entries.Add(entry);
2171 } else {
2172 HeapEntry* entry = entries2->at(j++);
2173 added_entries.Add(entry);
2174 }
2175 }
2176 while (i < entries1->length()) {
2177 HeapEntry* entry = entries1->at(i++);
2178 deleted_entries.Add(entry);
2179 }
2180 while (j < entries2->length()) {
2181 HeapEntry* entry = entries2->at(j++);
2182 added_entries.Add(entry);
2183 }
2184
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002185 HeapSnapshotsDiff* diff = new HeapSnapshotsDiff(snapshot1, snapshot2);
2186 diffs_.Add(diff);
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00002187 diff->CreateRoots(added_entries.length(), deleted_entries.length());
vegorov@chromium.org26c16f82010-08-11 13:41:03 +00002188
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002189 for (int i = 0; i < deleted_entries.length(); ++i) {
2190 HeapEntry* entry = deleted_entries[i];
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00002191 diff->AddDeletedEntry(i, i + 1, entry);
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002192 }
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002193 for (int i = 0; i < added_entries.length(); ++i) {
2194 HeapEntry* entry = added_entries[i];
ricow@chromium.orgeb7c1442010-10-04 08:54:21 +00002195 diff->AddAddedEntry(i, i + 1, entry);
ricow@chromium.org4980dff2010-07-19 08:33:45 +00002196 }
2197 return diff;
2198}
2199
erik.corry@gmail.comd88afa22010-09-15 12:33:05 +00002200
2201class OutputStreamWriter {
2202 public:
2203 explicit OutputStreamWriter(v8::OutputStream* stream)
2204 : stream_(stream),
2205 chunk_size_(stream->GetChunkSize()),
2206 chunk_(chunk_size_),
2207 chunk_pos_(0),
2208 aborted_(false) {
2209 ASSERT(chunk_size_ > 0);
2210 }
2211 bool aborted() { return aborted_; }
2212 void AddCharacter(char c) {
2213 ASSERT(c != '\0');
2214 ASSERT(chunk_pos_ < chunk_size_);
2215 chunk_[chunk_pos_++] = c;
2216 MaybeWriteChunk();
2217 }
2218 void AddString(const char* s) {
2219 AddSubstring(s, StrLength(s));
2220 }
2221 void AddSubstring(const char* s, int n) {
2222 if (n <= 0) return;
2223 ASSERT(static_cast<size_t>(n) <= strlen(s));
2224 const char* s_end = s + n;
2225 while (s < s_end) {
2226 int s_chunk_size = Min(
2227 chunk_size_ - chunk_pos_, static_cast<int>(s_end - s));
2228 ASSERT(s_chunk_size > 0);
2229 memcpy(chunk_.start() + chunk_pos_, s, s_chunk_size);
2230 s += s_chunk_size;
2231 chunk_pos_ += s_chunk_size;
2232 MaybeWriteChunk();
2233 }
2234 }
2235 void AddNumber(int n) { AddNumberImpl<int>(n, "%d"); }
2236 void AddNumber(unsigned n) { AddNumberImpl<unsigned>(n, "%u"); }
2237 void AddNumber(uint64_t n) { AddNumberImpl<uint64_t>(n, "%llu"); }
2238 void Finalize() {
2239 if (aborted_) return;
2240 ASSERT(chunk_pos_ < chunk_size_);
2241 if (chunk_pos_ != 0) {
2242 WriteChunk();
2243 }
2244 stream_->EndOfStream();
2245 }
2246
2247 private:
2248 template<typename T>
2249 void AddNumberImpl(T n, const char* format) {
2250 ScopedVector<char> buffer(32);
2251 int result = OS::SNPrintF(buffer, format, n);
2252 USE(result);
2253 ASSERT(result != -1);
2254 AddString(buffer.start());
2255 }
2256 void MaybeWriteChunk() {
2257 ASSERT(chunk_pos_ <= chunk_size_);
2258 if (chunk_pos_ == chunk_size_) {
2259 WriteChunk();
2260 chunk_pos_ = 0;
2261 }
2262 }
2263 void WriteChunk() {
2264 if (aborted_) return;
2265 if (stream_->WriteAsciiChunk(chunk_.start(), chunk_pos_) ==
2266 v8::OutputStream::kAbort) aborted_ = true;
2267 }
2268
2269 v8::OutputStream* stream_;
2270 int chunk_size_;
2271 ScopedVector<char> chunk_;
2272 int chunk_pos_;
2273 bool aborted_;
2274};
2275
2276void HeapSnapshotJSONSerializer::Serialize(v8::OutputStream* stream) {
2277 ASSERT(writer_ == NULL);
2278 writer_ = new OutputStreamWriter(stream);
2279
2280 // Since nodes graph is cyclic, we need the first pass to enumerate
2281 // them. Strings can be serialized in one pass.
2282 EnumerateNodes();
2283 SerializeImpl();
2284
2285 delete writer_;
2286 writer_ = NULL;
2287}
2288
2289
2290void HeapSnapshotJSONSerializer::SerializeImpl() {
2291 writer_->AddCharacter('{');
2292 writer_->AddString("\"snapshot\":{");
2293 SerializeSnapshot();
2294 if (writer_->aborted()) return;
2295 writer_->AddString("},\n");
2296 writer_->AddString("\"nodes\":[");
2297 SerializeNodes();
2298 if (writer_->aborted()) return;
2299 writer_->AddString("],\n");
2300 writer_->AddString("\"strings\":[");
2301 SerializeStrings();
2302 if (writer_->aborted()) return;
2303 writer_->AddCharacter(']');
2304 writer_->AddCharacter('}');
2305 writer_->Finalize();
2306}
2307
2308
2309class HeapSnapshotJSONSerializerEnumerator {
2310 public:
2311 explicit HeapSnapshotJSONSerializerEnumerator(HeapSnapshotJSONSerializer* s)
2312 : s_(s) {
2313 }
2314 void Apply(HeapEntry** entry) {
2315 s_->GetNodeId(*entry);
2316 }
2317 private:
2318 HeapSnapshotJSONSerializer* s_;
2319};
2320
2321void HeapSnapshotJSONSerializer::EnumerateNodes() {
2322 GetNodeId(snapshot_->root()); // Make sure root gets the first id.
2323 HeapSnapshotJSONSerializerEnumerator iter(this);
2324 snapshot_->IterateEntries(&iter);
2325}
2326
2327
2328int HeapSnapshotJSONSerializer::GetNodeId(HeapEntry* entry) {
2329 HashMap::Entry* cache_entry = nodes_.Lookup(entry, ObjectHash(entry), true);
2330 if (cache_entry->value == NULL) {
2331 cache_entry->value = reinterpret_cast<void*>(next_node_id_++);
2332 }
2333 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2334}
2335
2336
2337int HeapSnapshotJSONSerializer::GetStringId(const char* s) {
2338 HashMap::Entry* cache_entry = strings_.Lookup(
2339 const_cast<char*>(s), ObjectHash(s), true);
2340 if (cache_entry->value == NULL) {
2341 cache_entry->value = reinterpret_cast<void*>(next_string_id_++);
2342 }
2343 return static_cast<int>(reinterpret_cast<intptr_t>(cache_entry->value));
2344}
2345
2346
2347void HeapSnapshotJSONSerializer::SerializeEdge(HeapGraphEdge* edge) {
2348 writer_->AddCharacter(',');
2349 writer_->AddNumber(edge->type());
2350 writer_->AddCharacter(',');
2351 if (edge->type() == HeapGraphEdge::kElement) {
2352 writer_->AddNumber(edge->index());
2353 } else {
2354 writer_->AddNumber(GetStringId(edge->name()));
2355 }
2356 writer_->AddCharacter(',');
2357 writer_->AddNumber(GetNodeId(edge->to()));
2358}
2359
2360
2361void HeapSnapshotJSONSerializer::SerializeNode(HeapEntry* entry) {
2362 writer_->AddCharacter('\n');
2363 writer_->AddCharacter(',');
2364 writer_->AddNumber(entry->type());
2365 writer_->AddCharacter(',');
2366 writer_->AddNumber(GetStringId(entry->name()));
2367 writer_->AddCharacter(',');
2368 writer_->AddNumber(entry->id());
2369 writer_->AddCharacter(',');
2370 writer_->AddNumber(entry->self_size());
2371 Vector<HeapGraphEdge> children = entry->children();
2372 writer_->AddCharacter(',');
2373 writer_->AddNumber(children.length());
2374 for (int i = 0; i < children.length(); ++i) {
2375 SerializeEdge(&children[i]);
2376 if (writer_->aborted()) return;
2377 }
2378}
2379
2380
2381void HeapSnapshotJSONSerializer::SerializeNodes() {
2382 // The first (zero) item of nodes array is a JSON-ified object
2383 // describing node serialization layout.
2384 // We use a set of macros to improve readability.
2385#define JSON_A(s) "["s"]"
2386#define JSON_O(s) "{"s"}"
2387#define JSON_S(s) "\\\""s"\\\""
2388 writer_->AddString("\"" JSON_O(
2389 JSON_S("fields") ":" JSON_A(
2390 JSON_S("type")
2391 "," JSON_S("name")
2392 "," JSON_S("id")
2393 "," JSON_S("self_size")
2394 "," JSON_S("children_count")
2395 "," JSON_S("children"))
2396 "," JSON_S("types") ":" JSON_A(
2397 JSON_A(
2398 JSON_S("internal")
2399 "," JSON_S("array")
2400 "," JSON_S("string")
2401 "," JSON_S("object")
2402 "," JSON_S("code")
vegorov@chromium.org42841962010-10-18 11:18:59 +00002403 "," JSON_S("closure")
2404 "," JSON_S("regexp")
2405 "," JSON_S("number"))
erik.corry@gmail.comd88afa22010-09-15 12:33:05 +00002406 "," JSON_S("string")
2407 "," JSON_S("number")
2408 "," JSON_S("number")
2409 "," JSON_S("number")
2410 "," JSON_O(
2411 JSON_S("fields") ":" JSON_A(
2412 JSON_S("type")
2413 "," JSON_S("name_or_index")
2414 "," JSON_S("to_node"))
2415 "," JSON_S("types") ":" JSON_A(
2416 JSON_A(
2417 JSON_S("context")
2418 "," JSON_S("element")
2419 "," JSON_S("property")
2420 "," JSON_S("internal"))
2421 "," JSON_S("string_or_number")
2422 "," JSON_S("node"))))) "\"");
2423#undef JSON_S
2424#undef JSON_O
2425#undef JSON_A
2426
2427 const int node_fields_count = 5; // type,name,id,self_size,children_count.
2428 const int edge_fields_count = 3; // type,name|index,to_node.
2429 List<HashMap::Entry*> sorted_nodes;
2430 SortHashMap(&nodes_, &sorted_nodes);
2431 // Rewrite node ids, so they refer to actual array positions.
2432 if (sorted_nodes.length() > 1) {
2433 // Nodes start from array index 1.
2434 int prev_value = 1;
2435 sorted_nodes[0]->value = reinterpret_cast<void*>(prev_value);
2436 for (int i = 1; i < sorted_nodes.length(); ++i) {
2437 HeapEntry* prev_heap_entry =
2438 reinterpret_cast<HeapEntry*>(sorted_nodes[i-1]->key);
2439 prev_value += node_fields_count +
2440 prev_heap_entry->children().length() * edge_fields_count;
2441 sorted_nodes[i]->value = reinterpret_cast<void*>(prev_value);
2442 }
2443 }
2444 for (int i = 0; i < sorted_nodes.length(); ++i) {
2445 SerializeNode(reinterpret_cast<HeapEntry*>(sorted_nodes[i]->key));
2446 if (writer_->aborted()) return;
2447 }
2448}
2449
2450
2451void HeapSnapshotJSONSerializer::SerializeSnapshot() {
2452 writer_->AddString("\"title\":\"");
2453 writer_->AddString(snapshot_->title());
2454 writer_->AddString("\"");
2455 writer_->AddString(",\"uid\":");
2456 writer_->AddNumber(snapshot_->uid());
2457}
2458
2459
2460static void WriteUChar(OutputStreamWriter* w, unibrow::uchar u) {
2461 static const char hex_chars[] = "0123456789ABCDEF";
2462 w->AddString("\\u");
2463 w->AddCharacter(hex_chars[(u >> 12) & 0xf]);
2464 w->AddCharacter(hex_chars[(u >> 8) & 0xf]);
2465 w->AddCharacter(hex_chars[(u >> 4) & 0xf]);
2466 w->AddCharacter(hex_chars[u & 0xf]);
2467}
2468
2469void HeapSnapshotJSONSerializer::SerializeString(const unsigned char* s) {
2470 writer_->AddCharacter('\n');
2471 writer_->AddCharacter('\"');
2472 for ( ; *s != '\0'; ++s) {
2473 switch (*s) {
2474 case '\b':
2475 writer_->AddString("\\b");
2476 continue;
2477 case '\f':
2478 writer_->AddString("\\f");
2479 continue;
2480 case '\n':
2481 writer_->AddString("\\n");
2482 continue;
2483 case '\r':
2484 writer_->AddString("\\r");
2485 continue;
2486 case '\t':
2487 writer_->AddString("\\t");
2488 continue;
2489 case '\"':
2490 case '\\':
2491 writer_->AddCharacter('\\');
2492 writer_->AddCharacter(*s);
2493 continue;
2494 default:
2495 if (*s > 31 && *s < 128) {
2496 writer_->AddCharacter(*s);
2497 } else if (*s <= 31) {
2498 // Special character with no dedicated literal.
2499 WriteUChar(writer_, *s);
2500 } else {
2501 // Convert UTF-8 into \u UTF-16 literal.
2502 unsigned length = 1, cursor = 0;
2503 for ( ; length <= 4 && *(s + length) != '\0'; ++length) { }
2504 unibrow::uchar c = unibrow::Utf8::CalculateValue(s, length, &cursor);
2505 if (c != unibrow::Utf8::kBadChar) {
2506 WriteUChar(writer_, c);
2507 ASSERT(cursor != 0);
2508 s += cursor - 1;
2509 } else {
2510 writer_->AddCharacter('?');
2511 }
2512 }
2513 }
2514 }
2515 writer_->AddCharacter('\"');
2516}
2517
2518
2519void HeapSnapshotJSONSerializer::SerializeStrings() {
2520 List<HashMap::Entry*> sorted_strings;
2521 SortHashMap(&strings_, &sorted_strings);
2522 writer_->AddString("\"<dummy>\"");
2523 for (int i = 0; i < sorted_strings.length(); ++i) {
2524 writer_->AddCharacter(',');
2525 SerializeString(
2526 reinterpret_cast<const unsigned char*>(sorted_strings[i]->key));
2527 if (writer_->aborted()) return;
2528 }
2529}
2530
2531
2532template<typename T>
2533inline static int SortUsingEntryValue(const T* x, const T* y) {
2534 uintptr_t x_uint = reinterpret_cast<uintptr_t>((*x)->value);
2535 uintptr_t y_uint = reinterpret_cast<uintptr_t>((*y)->value);
2536 if (x_uint > y_uint) {
2537 return 1;
2538 } else if (x_uint == y_uint) {
2539 return 0;
2540 } else {
2541 return -1;
2542 }
2543}
2544
2545
2546void HeapSnapshotJSONSerializer::SortHashMap(
2547 HashMap* map, List<HashMap::Entry*>* sorted_entries) {
2548 for (HashMap::Entry* p = map->Start(); p != NULL; p = map->Next(p))
2549 sorted_entries->Add(p);
2550 sorted_entries->Sort(SortUsingEntryValue);
2551}
2552
fschneider@chromium.org086aac62010-03-17 13:18:24 +00002553} } // namespace v8::internal
lrn@chromium.org25156de2010-04-06 13:10:27 +00002554
ricow@chromium.orgc9c80822010-04-21 08:22:37 +00002555#endif // ENABLE_LOGGING_AND_PROFILING