test-heap-profiler.cc 101 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 28 29
//
// Tests for heap profiler

30 31
#include <ctype.h>

32
#include "src/v8.h"
33

34 35 36 37 38 39 40 41
#include "include/v8-profiler.h"
#include "src/allocation-tracker.h"
#include "src/debug.h"
#include "src/hashmap.h"
#include "src/heap-profiler.h"
#include "src/snapshot.h"
#include "src/utils-inl.h"
#include "test/cctest/cctest.h"
42

43 44 45 46 47 48
using i::AllocationTraceNode;
using i::AllocationTraceTree;
using i::AllocationTracker;
using i::HashMap;
using i::Vector;

49 50 51 52 53
namespace {

class NamedEntriesDetector {
 public:
  NamedEntriesDetector()
54
      : has_A2(false), has_B2(false), has_C2(false) {
55 56
  }

57 58 59 60
  void CheckEntry(i::HeapEntry* entry) {
    if (strcmp(entry->name(), "A2") == 0) has_A2 = true;
    if (strcmp(entry->name(), "B2") == 0) has_B2 = true;
    if (strcmp(entry->name(), "C2") == 0) has_C2 = true;
61 62
  }

63 64 65 66
  static bool AddressesMatch(void* key1, void* key2) {
    return key1 == key2;
  }

67
  void CheckAllReachables(i::HeapEntry* root) {
68
    i::HashMap visited(AddressesMatch);
69 70 71 72 73
    i::List<i::HeapEntry*> list(10);
    list.Add(root);
    CheckEntry(root);
    while (!list.is_empty()) {
      i::HeapEntry* entry = list.RemoveLast();
74
      i::Vector<i::HeapGraphEdge*> children = entry->children();
75
      for (int i = 0; i < children.length(); ++i) {
76 77
        if (children[i]->type() == i::HeapGraphEdge::kShortcut) continue;
        i::HeapEntry* child = children[i]->to();
78 79 80 81 82 83 84 85 86
        i::HashMap::Entry* entry = visited.Lookup(
            reinterpret_cast<void*>(child),
            static_cast<uint32_t>(reinterpret_cast<uintptr_t>(child)),
            true);
        if (entry->value)
          continue;
        entry->value = reinterpret_cast<void*>(1);
        list.Add(child);
        CheckEntry(child);
87 88
      }
    }
89 90 91 92 93 94 95 96 97
  }

  bool has_A2;
  bool has_B2;
  bool has_C2;
};

}  // namespace

98 99 100

static const v8::HeapGraphNode* GetGlobalObject(
    const v8::HeapSnapshot* snapshot) {
101
  CHECK_EQ(2, snapshot->GetRoot()->GetChildrenCount());
102
  // The 0th-child is (GC Roots), 1st is the user root.
103
  const v8::HeapGraphNode* global_obj =
104
      snapshot->GetRoot()->GetChild(1)->GetToNode();
105 106
  CHECK_EQ(0, strncmp("Object", const_cast<i::HeapEntry*>(
      reinterpret_cast<const i::HeapEntry*>(global_obj))->name(), 6));
107
  return global_obj;
108 109 110 111 112 113 114 115
}


static const v8::HeapGraphNode* GetProperty(const v8::HeapGraphNode* node,
                                            v8::HeapGraphEdge::Type type,
                                            const char* name) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = node->GetChild(i);
116
    v8::String::Utf8Value prop_name(prop->GetName());
117 118 119 120 121 122 123 124 125 126 127
    if (prop->GetType() == type && strcmp(name, *prop_name) == 0)
      return prop->GetToNode();
  }
  return NULL;
}


static bool HasString(const v8::HeapGraphNode* node, const char* contents) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = node->GetChild(i);
    const v8::HeapGraphNode* node = prop->GetToNode();
128
    if (node->GetType() == v8::HeapGraphNode::kString) {
129
      v8::String::Utf8Value node_name(node->GetName());
130 131 132 133 134 135 136
      if (strcmp(contents, *node_name) == 0) return true;
    }
  }
  return false;
}


137 138 139 140 141 142
static bool AddressesMatch(void* key1, void* key2) {
  return key1 == key2;
}


// Check that snapshot has no unretained entries except root.
143
static bool ValidateSnapshot(const v8::HeapSnapshot* snapshot, int depth = 3) {
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  i::HeapSnapshot* heap_snapshot = const_cast<i::HeapSnapshot*>(
      reinterpret_cast<const i::HeapSnapshot*>(snapshot));

  i::HashMap visited(AddressesMatch);
  i::List<i::HeapGraphEdge>& edges = heap_snapshot->edges();
  for (int i = 0; i < edges.length(); ++i) {
    i::HashMap::Entry* entry = visited.Lookup(
        reinterpret_cast<void*>(edges[i].to()),
        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(edges[i].to())),
        true);
    uint32_t ref_count = static_cast<uint32_t>(
        reinterpret_cast<uintptr_t>(entry->value));
    entry->value = reinterpret_cast<void*>(ref_count + 1);
  }
  uint32_t unretained_entries_count = 0;
  i::List<i::HeapEntry>& entries = heap_snapshot->entries();
  for (int i = 0; i < entries.length(); ++i) {
    i::HashMap::Entry* entry = visited.Lookup(
        reinterpret_cast<void*>(&entries[i]),
        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(&entries[i])),
        false);
    if (!entry && entries[i].id() != 1) {
        entries[i].Print("entry with no retainer", "", depth, 0);
        ++unretained_entries_count;
    }
  }
170
  return unretained_entries_count == 0;
171 172 173
}


174
TEST(HeapSnapshot) {
175
  LocalContext env2;
176
  v8::HandleScope scope(env2->GetIsolate());
177
  v8::HeapProfiler* heap_profiler = env2->GetIsolate()->GetHeapProfiler();
178

179
  CompileRun(
180 181 182 183 184 185 186
      "function A2() {}\n"
      "function B2(x) { return function() { return typeof x; }; }\n"
      "function C2(x) { this.x1 = x; this.x2 = x; this[1] = x; }\n"
      "var a2 = new A2();\n"
      "var b2_1 = new B2(a2), b2_2 = new B2(a2);\n"
      "var c2 = new C2(a2);");
  const v8::HeapSnapshot* snapshot_env2 =
187
      heap_profiler->TakeHeapSnapshot(v8_str("env2"));
188
  CHECK(ValidateSnapshot(snapshot_env2));
189
  const v8::HeapGraphNode* global_env2 = GetGlobalObject(snapshot_env2);
190

191
  // Verify, that JS global object of env2 has '..2' properties.
192
  const v8::HeapGraphNode* a2_node =
193
      GetProperty(global_env2, v8::HeapGraphEdge::kProperty, "a2");
194
  CHECK_NE(NULL, a2_node);
195
  CHECK_NE(
196
      NULL, GetProperty(global_env2, v8::HeapGraphEdge::kProperty, "b2_1"));
197
  CHECK_NE(
198 199
      NULL, GetProperty(global_env2, v8::HeapGraphEdge::kProperty, "b2_2"));
  CHECK_NE(NULL, GetProperty(global_env2, v8::HeapGraphEdge::kProperty, "c2"));
200 201

  NamedEntriesDetector det;
202 203
  det.CheckAllReachables(const_cast<i::HeapEntry*>(
      reinterpret_cast<const i::HeapEntry*>(global_env2)));
204 205 206 207 208
  CHECK(det.has_A2);
  CHECK(det.has_B2);
  CHECK(det.has_C2);
}

209

210 211
TEST(HeapSnapshotObjectSizes) {
  LocalContext env;
212
  v8::HandleScope scope(env->GetIsolate());
213
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
214 215 216

  //   -a-> X1 --a
  // x -b-> X2 <-|
217
  CompileRun(
218 219
      "function X(a, b) { this.a = a; this.b = b; }\n"
      "x = new X(new X(), new X());\n"
220
      "dummy = new X();\n"
221
      "(function() { x.a.a = x.b; })();");
222
  const v8::HeapSnapshot* snapshot =
223
      heap_profiler->TakeHeapSnapshot(v8_str("sizes"));
224
  CHECK(ValidateSnapshot(snapshot));
225 226
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* x =
227
      GetProperty(global, v8::HeapGraphEdge::kProperty, "x");
228 229 230 231 232 233 234
  CHECK_NE(NULL, x);
  const v8::HeapGraphNode* x1 =
      GetProperty(x, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, x1);
  const v8::HeapGraphNode* x2 =
      GetProperty(x, v8::HeapGraphEdge::kProperty, "b");
  CHECK_NE(NULL, x2);
235

236
  // Test sizes.
237 238 239
  CHECK_NE(0, static_cast<int>(x->GetShallowSize()));
  CHECK_NE(0, static_cast<int>(x1->GetShallowSize()));
  CHECK_NE(0, static_cast<int>(x2->GetShallowSize()));
240 241 242
}


243 244
TEST(BoundFunctionInSnapshot) {
  LocalContext env;
245
  v8::HandleScope scope(env->GetIsolate());
246
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
247 248 249 250 251
  CompileRun(
      "function myFunction(a, b) { this.a = a; this.b = b; }\n"
      "function AAAAA() {}\n"
      "boundFunction = myFunction.bind(new AAAAA(), 20, new Number(12)); \n");
  const v8::HeapSnapshot* snapshot =
252
      heap_profiler->TakeHeapSnapshot(v8_str("sizes"));
253
  CHECK(ValidateSnapshot(snapshot));
254 255
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* f =
256
      GetProperty(global, v8::HeapGraphEdge::kProperty, "boundFunction");
257
  CHECK(f);
258 259
  CHECK_EQ(v8::String::NewFromUtf8(env->GetIsolate(), "native_bind"),
           f->GetName());
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  const v8::HeapGraphNode* bindings =
      GetProperty(f, v8::HeapGraphEdge::kInternal, "bindings");
  CHECK_NE(NULL, bindings);
  CHECK_EQ(v8::HeapGraphNode::kArray, bindings->GetType());
  CHECK_EQ(4, bindings->GetChildrenCount());

  const v8::HeapGraphNode* bound_this = GetProperty(
      f, v8::HeapGraphEdge::kShortcut, "bound_this");
  CHECK(bound_this);
  CHECK_EQ(v8::HeapGraphNode::kObject, bound_this->GetType());

  const v8::HeapGraphNode* bound_function = GetProperty(
      f, v8::HeapGraphEdge::kShortcut, "bound_function");
  CHECK(bound_function);
  CHECK_EQ(v8::HeapGraphNode::kClosure, bound_function->GetType());

  const v8::HeapGraphNode* bound_argument = GetProperty(
      f, v8::HeapGraphEdge::kShortcut, "bound_argument_1");
  CHECK(bound_argument);
  CHECK_EQ(v8::HeapGraphNode::kObject, bound_argument->GetType());
}


283 284
TEST(HeapSnapshotEntryChildren) {
  LocalContext env;
285
  v8::HandleScope scope(env->GetIsolate());
286
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
287

288
  CompileRun(
289 290 291
      "function A() { }\n"
      "a = new A;");
  const v8::HeapSnapshot* snapshot =
292
      heap_profiler->TakeHeapSnapshot(v8_str("children"));
293
  CHECK(ValidateSnapshot(snapshot));
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  for (int i = 0, count = global->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = global->GetChild(i);
    CHECK_EQ(global, prop->GetFromNode());
  }
  const v8::HeapGraphNode* a =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a);
  for (int i = 0, count = a->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = a->GetChild(i);
    CHECK_EQ(a, prop->GetFromNode());
  }
}


309
TEST(HeapSnapshotCodeObjects) {
310
  LocalContext env;
311
  v8::HandleScope scope(env->GetIsolate());
312
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
313

314
  CompileRun(
315 316
      "function lazy(x) { return x - 1; }\n"
      "function compiled(x) { return x + 1; }\n"
317
      "var anonymous = (function() { return function() { return 0; } })();\n"
318 319
      "compiled(1)");
  const v8::HeapSnapshot* snapshot =
320
      heap_profiler->TakeHeapSnapshot(v8_str("code"));
321
  CHECK(ValidateSnapshot(snapshot));
322 323 324

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* compiled =
325
      GetProperty(global, v8::HeapGraphEdge::kProperty, "compiled");
326
  CHECK_NE(NULL, compiled);
327
  CHECK_EQ(v8::HeapGraphNode::kClosure, compiled->GetType());
328
  const v8::HeapGraphNode* lazy =
329
      GetProperty(global, v8::HeapGraphEdge::kProperty, "lazy");
330
  CHECK_NE(NULL, lazy);
331
  CHECK_EQ(v8::HeapGraphNode::kClosure, lazy->GetType());
332
  const v8::HeapGraphNode* anonymous =
333
      GetProperty(global, v8::HeapGraphEdge::kProperty, "anonymous");
334 335
  CHECK_NE(NULL, anonymous);
  CHECK_EQ(v8::HeapGraphNode::kClosure, anonymous->GetType());
336
  v8::String::Utf8Value anonymous_name(anonymous->GetName());
337
  CHECK_EQ("", *anonymous_name);
338 339 340

  // Find references to code.
  const v8::HeapGraphNode* compiled_code =
341
      GetProperty(compiled, v8::HeapGraphEdge::kInternal, "shared");
342 343
  CHECK_NE(NULL, compiled_code);
  const v8::HeapGraphNode* lazy_code =
344
      GetProperty(lazy, v8::HeapGraphEdge::kInternal, "shared");
345 346
  CHECK_NE(NULL, lazy_code);

347 348 349 350 351 352 353 354 355
  // Check that there's no strong next_code_link. There might be a weak one
  // but might be not, so we can't check that fact.
  const v8::HeapGraphNode* code =
      GetProperty(compiled_code, v8::HeapGraphEdge::kInternal, "code");
  CHECK_NE(NULL, code);
  const v8::HeapGraphNode* next_code_link =
      GetProperty(code, v8::HeapGraphEdge::kInternal, "code");
  CHECK_EQ(NULL, next_code_link);

356
  // Verify that non-compiled code doesn't contain references to "x"
357 358
  // literal, while compiled code does. The scope info is stored in FixedArray
  // objects attached to the SharedFunctionInfo.
359 360 361 362
  bool compiled_references_x = false, lazy_references_x = false;
  for (int i = 0, count = compiled_code->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = compiled_code->GetChild(i);
    const v8::HeapGraphNode* node = prop->GetToNode();
363
    if (node->GetType() == v8::HeapGraphNode::kArray) {
364 365 366 367 368 369 370 371 372
      if (HasString(node, "x")) {
        compiled_references_x = true;
        break;
      }
    }
  }
  for (int i = 0, count = lazy_code->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = lazy_code->GetChild(i);
    const v8::HeapGraphNode* node = prop->GetToNode();
373
    if (node->GetType() == v8::HeapGraphNode::kArray) {
374 375 376 377 378 379 380 381 382 383
      if (HasString(node, "x")) {
        lazy_references_x = true;
        break;
      }
    }
  }
  CHECK(compiled_references_x);
  CHECK(!lazy_references_x);
}

384

385 386
TEST(HeapSnapshotHeapNumbers) {
  LocalContext env;
387
  v8::HandleScope scope(env->GetIsolate());
388
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
389 390 391 392
  CompileRun(
      "a = 1;    // a is Smi\n"
      "b = 2.5;  // b is HeapNumber");
  const v8::HeapSnapshot* snapshot =
393
      heap_profiler->TakeHeapSnapshot(v8_str("numbers"));
394
  CHECK(ValidateSnapshot(snapshot));
395
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
396
  CHECK_EQ(NULL, GetProperty(global, v8::HeapGraphEdge::kProperty, "a"));
397
  const v8::HeapGraphNode* b =
398
      GetProperty(global, v8::HeapGraphEdge::kProperty, "b");
399 400 401 402
  CHECK_NE(NULL, b);
  CHECK_EQ(v8::HeapGraphNode::kHeapNumber, b->GetType());
}

403

404 405
TEST(HeapSnapshotSlicedString) {
  LocalContext env;
406
  v8::HandleScope scope(env->GetIsolate());
407
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
408 409 410 411 412 413 414
  CompileRun(
      "parent_string = \"123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789.\";"
      "child_string = parent_string.slice(100);");
  const v8::HeapSnapshot* snapshot =
415
      heap_profiler->TakeHeapSnapshot(v8_str("strings"));
416
  CHECK(ValidateSnapshot(snapshot));
417 418
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* parent_string =
419
      GetProperty(global, v8::HeapGraphEdge::kProperty, "parent_string");
420 421
  CHECK_NE(NULL, parent_string);
  const v8::HeapGraphNode* child_string =
422
      GetProperty(global, v8::HeapGraphEdge::kProperty, "child_string");
423
  CHECK_NE(NULL, child_string);
424
  CHECK_EQ(v8::HeapGraphNode::kSlicedString, child_string->GetType());
425 426 427
  const v8::HeapGraphNode* parent =
      GetProperty(child_string, v8::HeapGraphEdge::kInternal, "parent");
  CHECK_EQ(parent_string, parent);
428
  heap_profiler->DeleteAllHeapSnapshots();
429
}
430

431

432
TEST(HeapSnapshotConsString) {
433
  v8::Isolate* isolate = CcTest::isolate();
434
  v8::HandleScope scope(isolate);
435 436
  v8::Local<v8::ObjectTemplate> global_template =
      v8::ObjectTemplate::New(isolate);
437 438 439 440 441 442
  global_template->SetInternalFieldCount(1);
  LocalContext env(NULL, global_template);
  v8::Handle<v8::Object> global_proxy = env->Global();
  v8::Handle<v8::Object> global = global_proxy->GetPrototype().As<v8::Object>();
  CHECK_EQ(1, global->InternalFieldCount());

443
  i::Factory* factory = CcTest::i_isolate()->factory();
444 445
  i::Handle<i::String> first = factory->NewStringFromStaticChars("0123456789");
  i::Handle<i::String> second = factory->NewStringFromStaticChars("0123456789");
446 447
  i::Handle<i::String> cons_string =
      factory->NewConsString(first, second).ToHandleChecked();
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473

  global->SetInternalField(0, v8::ToApiHandle<v8::String>(cons_string));

  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("cons_strings"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global_node = GetGlobalObject(snapshot);

  const v8::HeapGraphNode* string_node =
      GetProperty(global_node, v8::HeapGraphEdge::kInternal, "0");
  CHECK_NE(NULL, string_node);
  CHECK_EQ(v8::HeapGraphNode::kConsString, string_node->GetType());

  const v8::HeapGraphNode* first_node =
      GetProperty(string_node, v8::HeapGraphEdge::kInternal, "first");
  CHECK_EQ(v8::HeapGraphNode::kString, first_node->GetType());

  const v8::HeapGraphNode* second_node =
      GetProperty(string_node, v8::HeapGraphEdge::kInternal, "second");
  CHECK_EQ(v8::HeapGraphNode::kString, second_node->GetType());

  heap_profiler->DeleteAllHeapSnapshots();
}


474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
TEST(HeapSnapshotSymbol) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun("a = Symbol('mySymbol');\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("Symbol"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* a =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a);
  CHECK_EQ(a->GetType(), v8::HeapGraphNode::kSymbol);
  CHECK_EQ(v8_str("symbol"), a->GetName());
  const v8::HeapGraphNode* name =
      GetProperty(a, v8::HeapGraphEdge::kInternal, "name");
  CHECK_NE(NULL, name);
  CHECK_EQ(v8_str("mySymbol"), name->GetName());
}

495

496 497 498 499 500
TEST(HeapSnapshotWeakCollection) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

501 502 503 504
  CompileRun(
      "k = {}; v = {}; s = 'str';\n"
      "ws = new WeakSet(); ws.add(k); ws.add(v); ws[s] = s;\n"
      "wm = new WeakMap(); wm.set(k, v); wm[s] = s;\n");
505 506 507 508 509 510 511 512 513 514
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("WeakCollections"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* k =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "k");
  CHECK_NE(NULL, k);
  const v8::HeapGraphNode* v =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "v");
  CHECK_NE(NULL, v);
515 516 517
  const v8::HeapGraphNode* s =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "s");
  CHECK_NE(NULL, s);
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

  const v8::HeapGraphNode* ws =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "ws");
  CHECK_NE(NULL, ws);
  CHECK_EQ(v8::HeapGraphNode::kObject, ws->GetType());
  CHECK_EQ(v8_str("WeakSet"), ws->GetName());

  const v8::HeapGraphNode* ws_table =
      GetProperty(ws, v8::HeapGraphEdge::kInternal, "table");
  CHECK_EQ(v8::HeapGraphNode::kArray, ws_table->GetType());
  CHECK_GT(ws_table->GetChildrenCount(), 0);
  int weak_entries = 0;
  for (int i = 0, count = ws_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = ws_table->GetChild(i);
    if (prop->GetType() != v8::HeapGraphEdge::kWeak) continue;
    if (k->GetId() == prop->GetToNode()->GetId()) {
      ++weak_entries;
    }
  }
  CHECK_EQ(1, weak_entries);
538 539 540 541
  const v8::HeapGraphNode* ws_s =
      GetProperty(ws, v8::HeapGraphEdge::kProperty, "str");
  CHECK_NE(NULL, ws_s);
  CHECK_EQ(static_cast<int>(s->GetId()), static_cast<int>(ws_s->GetId()));
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

  const v8::HeapGraphNode* wm =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "wm");
  CHECK_NE(NULL, wm);
  CHECK_EQ(v8::HeapGraphNode::kObject, wm->GetType());
  CHECK_EQ(v8_str("WeakMap"), wm->GetName());

  const v8::HeapGraphNode* wm_table =
      GetProperty(wm, v8::HeapGraphEdge::kInternal, "table");
  CHECK_EQ(v8::HeapGraphNode::kArray, wm_table->GetType());
  CHECK_GT(wm_table->GetChildrenCount(), 0);
  weak_entries = 0;
  for (int i = 0, count = wm_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = wm_table->GetChild(i);
    if (prop->GetType() != v8::HeapGraphEdge::kWeak) continue;
    const v8::SnapshotObjectId to_node_id = prop->GetToNode()->GetId();
    if (to_node_id == k->GetId() || to_node_id == v->GetId()) {
      ++weak_entries;
    }
  }
  CHECK_EQ(2, weak_entries);
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
  const v8::HeapGraphNode* wm_s =
      GetProperty(wm, v8::HeapGraphEdge::kProperty, "str");
  CHECK_NE(NULL, wm_s);
  CHECK_EQ(static_cast<int>(s->GetId()), static_cast<int>(wm_s->GetId()));
}


TEST(HeapSnapshotCollection) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun(
      "k = {}; v = {}; s = 'str';\n"
      "set = new Set(); set.add(k); set.add(v); set[s] = s;\n"
      "map = new Map(); map.set(k, v); map[s] = s;\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("Collections"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* k =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "k");
  CHECK_NE(NULL, k);
  const v8::HeapGraphNode* v =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "v");
  CHECK_NE(NULL, v);
  const v8::HeapGraphNode* s =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "s");
  CHECK_NE(NULL, s);

  const v8::HeapGraphNode* set =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "set");
  CHECK_NE(NULL, set);
  CHECK_EQ(v8::HeapGraphNode::kObject, set->GetType());
  CHECK_EQ(v8_str("Set"), set->GetName());

  const v8::HeapGraphNode* set_table =
      GetProperty(set, v8::HeapGraphEdge::kInternal, "table");
  CHECK_EQ(v8::HeapGraphNode::kArray, set_table->GetType());
  CHECK_GT(set_table->GetChildrenCount(), 0);
  int entries = 0;
  for (int i = 0, count = set_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = set_table->GetChild(i);
    const v8::SnapshotObjectId to_node_id = prop->GetToNode()->GetId();
    if (to_node_id == k->GetId() || to_node_id == v->GetId()) {
      ++entries;
    }
  }
  CHECK_EQ(2, entries);
  const v8::HeapGraphNode* set_s =
      GetProperty(set, v8::HeapGraphEdge::kProperty, "str");
  CHECK_NE(NULL, set_s);
  CHECK_EQ(static_cast<int>(s->GetId()), static_cast<int>(set_s->GetId()));

  const v8::HeapGraphNode* map =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "map");
  CHECK_NE(NULL, map);
  CHECK_EQ(v8::HeapGraphNode::kObject, map->GetType());
  CHECK_EQ(v8_str("Map"), map->GetName());

  const v8::HeapGraphNode* map_table =
      GetProperty(map, v8::HeapGraphEdge::kInternal, "table");
  CHECK_EQ(v8::HeapGraphNode::kArray, map_table->GetType());
  CHECK_GT(map_table->GetChildrenCount(), 0);
  entries = 0;
  for (int i = 0, count = map_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = map_table->GetChild(i);
    const v8::SnapshotObjectId to_node_id = prop->GetToNode()->GetId();
    if (to_node_id == k->GetId() || to_node_id == v->GetId()) {
      ++entries;
    }
  }
  CHECK_EQ(2, entries);
  const v8::HeapGraphNode* map_s =
      GetProperty(map, v8::HeapGraphEdge::kProperty, "str");
  CHECK_NE(NULL, map_s);
  CHECK_EQ(static_cast<int>(s->GetId()), static_cast<int>(map_s->GetId()));
640 641 642
}


643
TEST(HeapSnapshotInternalReferences) {
644
  v8::Isolate* isolate = CcTest::isolate();
645
  v8::HandleScope scope(isolate);
646 647
  v8::Local<v8::ObjectTemplate> global_template =
      v8::ObjectTemplate::New(isolate);
648 649 650 651 652
  global_template->SetInternalFieldCount(2);
  LocalContext env(NULL, global_template);
  v8::Handle<v8::Object> global_proxy = env->Global();
  v8::Handle<v8::Object> global = global_proxy->GetPrototype().As<v8::Object>();
  CHECK_EQ(2, global->InternalFieldCount());
653
  v8::Local<v8::Object> obj = v8::Object::New(isolate);
654 655
  global->SetInternalField(0, v8_num(17));
  global->SetInternalField(1, obj);
656
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
657
  const v8::HeapSnapshot* snapshot =
658
      heap_profiler->TakeHeapSnapshot(v8_str("internals"));
659
  CHECK(ValidateSnapshot(snapshot));
660 661 662 663 664 665 666 667
  const v8::HeapGraphNode* global_node = GetGlobalObject(snapshot);
  // The first reference will not present, because it's a Smi.
  CHECK_EQ(NULL, GetProperty(global_node, v8::HeapGraphEdge::kInternal, "0"));
  // The second reference is to an object.
  CHECK_NE(NULL, GetProperty(global_node, v8::HeapGraphEdge::kInternal, "1"));
}


668
// Trying to introduce a check helper for uint32_t causes many
669 670
// overloading ambiguities, so it seems easier just to cast
// them to a signed type.
671 672 673
#define CHECK_EQ_SNAPSHOT_OBJECT_ID(a, b) \
  CHECK_EQ(static_cast<int32_t>(a), static_cast<int32_t>(b))
#define CHECK_NE_SNAPSHOT_OBJECT_ID(a, b) \
674
  CHECK((a) != (b))  // NOLINT
675

676 677
TEST(HeapSnapshotAddressReuse) {
  LocalContext env;
678
  v8::HandleScope scope(env->GetIsolate());
679
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
680 681 682 683 684 685 686

  CompileRun(
      "function A() {}\n"
      "var a = [];\n"
      "for (var i = 0; i < 10000; ++i)\n"
      "  a[i] = new A();\n");
  const v8::HeapSnapshot* snapshot1 =
687
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot1"));
688
  CHECK(ValidateSnapshot(snapshot1));
689 690 691 692 693
  v8::SnapshotObjectId maxId1 = snapshot1->GetMaxSnapshotJSObjectId();

  CompileRun(
      "for (var i = 0; i < 10000; ++i)\n"
      "  a[i] = new A();\n");
694
  CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
695 696

  const v8::HeapSnapshot* snapshot2 =
697
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot2"));
698
  CHECK(ValidateSnapshot(snapshot2));
699 700 701 702 703 704 705 706 707 708 709 710 711 712
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);

  const v8::HeapGraphNode* array_node =
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, array_node);
  int wrong_count = 0;
  for (int i = 0, count = array_node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = array_node->GetChild(i);
    if (prop->GetType() != v8::HeapGraphEdge::kElement)
      continue;
    v8::SnapshotObjectId id = prop->GetToNode()->GetId();
    if (id < maxId1)
      ++wrong_count;
  }
713
  CHECK_EQ(0, wrong_count);
714 715 716
}


717 718
TEST(HeapEntryIdsAndArrayShift) {
  LocalContext env;
719
  v8::HandleScope scope(env->GetIsolate());
720
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
721 722 723 724 725 726 727 728 729 730

  CompileRun(
      "function AnObject() {\n"
      "    this.first = 'first';\n"
      "    this.second = 'second';\n"
      "}\n"
      "var a = new Array();\n"
      "for (var i = 0; i < 10; ++i)\n"
      "  a.push(new AnObject());\n");
  const v8::HeapSnapshot* snapshot1 =
731
      heap_profiler->TakeHeapSnapshot(v8_str("s1"));
732
  CHECK(ValidateSnapshot(snapshot1));
733 734 735 736 737

  CompileRun(
      "for (var i = 0; i < 1; ++i)\n"
      "  a.shift();\n");

738
  CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
739 740

  const v8::HeapSnapshot* snapshot2 =
741
      heap_profiler->TakeHeapSnapshot(v8_str("s2"));
742
  CHECK(ValidateSnapshot(snapshot2));
743 744 745

  const v8::HeapGraphNode* global1 = GetGlobalObject(snapshot1);
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);
746 747
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, global1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(global1->GetId(), global2->GetId());
748 749 750 751 752

  const v8::HeapGraphNode* a1 =
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a1);
  const v8::HeapGraphNode* k1 =
753
      GetProperty(a1, v8::HeapGraphEdge::kInternal, "elements");
754 755 756 757 758
  CHECK_NE(NULL, k1);
  const v8::HeapGraphNode* a2 =
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a2);
  const v8::HeapGraphNode* k2 =
759
      GetProperty(a2, v8::HeapGraphEdge::kInternal, "elements");
760 761
  CHECK_NE(NULL, k2);

762 763
  CHECK_EQ_SNAPSHOT_OBJECT_ID(a1->GetId(), a2->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(k1->GetId(), k2->GetId());
764 765
}

766

767 768
TEST(HeapEntryIdsAndGC) {
  LocalContext env;
769
  v8::HandleScope scope(env->GetIsolate());
770
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
771

772
  CompileRun(
773 774 775 776
      "function A() {}\n"
      "function B(x) { this.x = x; }\n"
      "var a = new A();\n"
      "var b = new B(a);");
777 778
  v8::Local<v8::String> s1_str = v8_str("s1");
  v8::Local<v8::String> s2_str = v8_str("s2");
779
  const v8::HeapSnapshot* snapshot1 =
780
      heap_profiler->TakeHeapSnapshot(s1_str);
781
  CHECK(ValidateSnapshot(snapshot1));
782

783
  CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
784 785

  const v8::HeapSnapshot* snapshot2 =
786
      heap_profiler->TakeHeapSnapshot(s2_str);
787
  CHECK(ValidateSnapshot(snapshot2));
788

789
  CHECK_GT(snapshot1->GetMaxSnapshotJSObjectId(), 7000);
790 791
  CHECK(snapshot1->GetMaxSnapshotJSObjectId() <=
        snapshot2->GetMaxSnapshotJSObjectId());
792 793 794

  const v8::HeapGraphNode* global1 = GetGlobalObject(snapshot1);
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);
795 796
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, global1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(global1->GetId(), global2->GetId());
797
  const v8::HeapGraphNode* A1 =
798 799
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "A");
  CHECK_NE(NULL, A1);
800
  const v8::HeapGraphNode* A2 =
801 802
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "A");
  CHECK_NE(NULL, A2);
803 804
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, A1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(A1->GetId(), A2->GetId());
805
  const v8::HeapGraphNode* B1 =
806 807
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "B");
  CHECK_NE(NULL, B1);
808
  const v8::HeapGraphNode* B2 =
809 810
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "B");
  CHECK_NE(NULL, B2);
811 812
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, B1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(B1->GetId(), B2->GetId());
813
  const v8::HeapGraphNode* a1 =
814 815
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a1);
816
  const v8::HeapGraphNode* a2 =
817 818
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a2);
819 820
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, a1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(a1->GetId(), a2->GetId());
821
  const v8::HeapGraphNode* b1 =
822 823
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "b");
  CHECK_NE(NULL, b1);
824
  const v8::HeapGraphNode* b2 =
825 826
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "b");
  CHECK_NE(NULL, b2);
827 828
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, b1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(b1->GetId(), b2->GetId());
829 830 831
}


832 833
TEST(HeapSnapshotRootPreservedAfterSorting) {
  LocalContext env;
834
  v8::HandleScope scope(env->GetIsolate());
835
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
836
  const v8::HeapSnapshot* snapshot =
837
      heap_profiler->TakeHeapSnapshot(v8_str("s"));
838
  CHECK(ValidateSnapshot(snapshot));
839 840 841 842 843 844 845 846
  const v8::HeapGraphNode* root1 = snapshot->GetRoot();
  const_cast<i::HeapSnapshot*>(reinterpret_cast<const i::HeapSnapshot*>(
      snapshot))->GetSortedEntriesList();
  const v8::HeapGraphNode* root2 = snapshot->GetRoot();
  CHECK_EQ(root1, root2);
}


847 848 849 850
namespace {

class TestJSONStream : public v8::OutputStream {
 public:
851 852 853
  TestJSONStream() : eos_signaled_(0), abort_countdown_(-1) {}
  explicit TestJSONStream(int abort_countdown)
      : eos_signaled_(0), abort_countdown_(abort_countdown) {}
854 855
  virtual ~TestJSONStream() {}
  virtual void EndOfStream() { ++eos_signaled_; }
856 857 858
  virtual WriteResult WriteAsciiChunk(char* buffer, int chars_written) {
    if (abort_countdown_ > 0) --abort_countdown_;
    if (abort_countdown_ == 0) return kAbort;
859 860
    CHECK_GT(chars_written, 0);
    i::Vector<char> chunk = buffer_.AddBlock(chars_written, '\0');
861
    i::MemCopy(chunk.start(), buffer, chars_written);
862
    return kContinue;
863
  }
864
  virtual WriteResult WriteUint32Chunk(uint32_t* buffer, int chars_written) {
865
    DCHECK(false);
866 867
    return kAbort;
  }
868 869 870
  void WriteTo(i::Vector<char> dest) { buffer_.WriteTo(dest); }
  int eos_signaled() { return eos_signaled_; }
  int size() { return buffer_.size(); }
871

872 873 874
 private:
  i::Collector<char> buffer_;
  int eos_signaled_;
875
  int abort_countdown_;
876 877
};

878
class OneByteResource : public v8::String::ExternalOneByteStringResource {
879
 public:
880
  explicit OneByteResource(i::Vector<char> string) : data_(string.start()) {
881 882 883 884 885 886 887 888 889 890 891 892 893
    length_ = string.length();
  }
  virtual const char* data() const { return data_; }
  virtual size_t length() const { return length_; }
 private:
  const char* data_;
  size_t length_;
};

}  // namespace

TEST(HeapSnapshotJSONSerialization) {
  LocalContext env;
894
  v8::HandleScope scope(env->GetIsolate());
895
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
896 897 898

#define STRING_LITERAL_FOR_TEST \
  "\"String \\n\\r\\u0008\\u0081\\u0101\\u0801\\u8001\""
899
  CompileRun(
900 901 902 903 904
      "function A(s) { this.s = s; }\n"
      "function B(x) { this.x = x; }\n"
      "var a = new A(" STRING_LITERAL_FOR_TEST ");\n"
      "var b = new B(a);");
  const v8::HeapSnapshot* snapshot =
905
      heap_profiler->TakeHeapSnapshot(v8_str("json"));
906
  CHECK(ValidateSnapshot(snapshot));
907

908 909 910 911 912 913 914 915
  TestJSONStream stream;
  snapshot->Serialize(&stream, v8::HeapSnapshot::kJSON);
  CHECK_GT(stream.size(), 0);
  CHECK_EQ(1, stream.eos_signaled());
  i::ScopedVector<char> json(stream.size());
  stream.WriteTo(json);

  // Verify that snapshot string is valid JSON.
916
  OneByteResource* json_res = new OneByteResource(json);
917
  v8::Local<v8::String> json_string =
918
      v8::String::NewExternal(env->GetIsolate(), json_res);
919
  env->Global()->Set(v8_str("json_snapshot"), json_string);
920 921 922 923 924 925
  v8::Local<v8::Value> snapshot_parse_result = CompileRun(
      "var parsed = JSON.parse(json_snapshot); true;");
  CHECK(!snapshot_parse_result.IsEmpty());

  // Verify that snapshot object has required fields.
  v8::Local<v8::Object> parsed_snapshot =
926 927 928
      env->Global()->Get(v8_str("parsed"))->ToObject();
  CHECK(parsed_snapshot->Has(v8_str("snapshot")));
  CHECK(parsed_snapshot->Has(v8_str("nodes")));
929
  CHECK(parsed_snapshot->Has(v8_str("edges")));
930
  CHECK(parsed_snapshot->Has(v8_str("strings")));
931 932 933

  // Get node and edge "member" offsets.
  v8::Local<v8::Value> meta_analysis_result = CompileRun(
934
      "var meta = parsed.snapshot.meta;\n"
935
      "var edge_count_offset = meta.node_fields.indexOf('edge_count');\n"
936 937 938 939 940
      "var node_fields_count = meta.node_fields.length;\n"
      "var edge_fields_count = meta.edge_fields.length;\n"
      "var edge_type_offset = meta.edge_fields.indexOf('type');\n"
      "var edge_name_offset = meta.edge_fields.indexOf('name_or_index');\n"
      "var edge_to_node_offset = meta.edge_fields.indexOf('to_node');\n"
941
      "var property_type ="
942
      "    meta.edge_types[edge_type_offset].indexOf('property');\n"
943
      "var shortcut_type ="
944
      "    meta.edge_types[edge_type_offset].indexOf('shortcut');\n"
945 946 947 948 949 950
      "var node_count = parsed.nodes.length / node_fields_count;\n"
      "var first_edge_indexes = parsed.first_edge_indexes = [];\n"
      "for (var i = 0, first_edge_index = 0; i < node_count; ++i) {\n"
      "  first_edge_indexes[i] = first_edge_index;\n"
      "  first_edge_index += edge_fields_count *\n"
      "      parsed.nodes[i * node_fields_count + edge_count_offset];\n"
951 952
      "}\n"
      "first_edge_indexes[node_count] = first_edge_index;\n");
953 954 955 956
  CHECK(!meta_analysis_result.IsEmpty());

  // A helper function for processing encoded nodes.
  CompileRun(
957
      "function GetChildPosByProperty(pos, prop_name, prop_type) {\n"
958
      "  var nodes = parsed.nodes;\n"
959
      "  var edges = parsed.edges;\n"
960
      "  var strings = parsed.strings;\n"
961 962 963
      "  var node_ordinal = pos / node_fields_count;\n"
      "  for (var i = parsed.first_edge_indexes[node_ordinal],\n"
      "      count = parsed.first_edge_indexes[node_ordinal + 1];\n"
964 965 966 967
      "      i < count; i += edge_fields_count) {\n"
      "    if (edges[i + edge_type_offset] === prop_type\n"
      "        && strings[edges[i + edge_name_offset]] === prop_name)\n"
      "      return edges[i + edge_to_node_offset];\n"
968 969 970 971 972 973 974 975
      "  }\n"
      "  return null;\n"
      "}\n");
  // Get the string index using the path: <root> -> <global>.b.x.s
  v8::Local<v8::Value> string_obj_pos_val = CompileRun(
      "GetChildPosByProperty(\n"
      "  GetChildPosByProperty(\n"
      "    GetChildPosByProperty("
976
      "      parsed.edges[edge_fields_count + edge_to_node_offset],"
977
      "      \"b\", property_type),\n"
978 979
      "    \"x\", property_type),"
      "  \"s\", property_type)");
980 981 982 983
  CHECK(!string_obj_pos_val.IsEmpty());
  int string_obj_pos =
      static_cast<int>(string_obj_pos_val->ToNumber()->Value());
  v8::Local<v8::Object> nodes_array =
984
      parsed_snapshot->Get(v8_str("nodes"))->ToObject();
985 986 987 988
  int string_index = static_cast<int>(
      nodes_array->Get(string_obj_pos + 1)->ToNumber()->Value());
  CHECK_GT(string_index, 0);
  v8::Local<v8::Object> strings_array =
989
      parsed_snapshot->Get(v8_str("strings"))->ToObject();
990 991 992 993 994 995 996 997
  v8::Local<v8::String> string = strings_array->Get(string_index)->ToString();
  v8::Local<v8::String> ref_string =
      CompileRun(STRING_LITERAL_FOR_TEST)->ToString();
#undef STRING_LITERAL_FOR_TEST
  CHECK_EQ(*v8::String::Utf8Value(ref_string),
           *v8::String::Utf8Value(string));
}

998 999 1000

TEST(HeapSnapshotJSONSerializationAborting) {
  LocalContext env;
1001
  v8::HandleScope scope(env->GetIsolate());
1002
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1003
  const v8::HeapSnapshot* snapshot =
1004
      heap_profiler->TakeHeapSnapshot(v8_str("abort"));
1005
  CHECK(ValidateSnapshot(snapshot));
1006 1007 1008 1009 1010 1011
  TestJSONStream stream(5);
  snapshot->Serialize(&stream, v8::HeapSnapshot::kJSON);
  CHECK_GT(stream.size(), 0);
  CHECK_EQ(0, stream.eos_signaled());
}

1012 1013 1014 1015 1016 1017
namespace {

class TestStatsStream : public v8::OutputStream {
 public:
  TestStatsStream()
    : eos_signaled_(0),
1018
      updates_written_(0),
1019
      entries_count_(0),
1020
      entries_size_(0),
1021 1022 1023
      intervals_count_(0),
      first_interval_index_(-1) { }
  TestStatsStream(const TestStatsStream& stream)
loislo@chromium.org's avatar
loislo@chromium.org committed
1024 1025
    : v8::OutputStream(stream),
      eos_signaled_(stream.eos_signaled_),
1026
      updates_written_(stream.updates_written_),
1027
      entries_count_(stream.entries_count_),
1028
      entries_size_(stream.entries_size_),
1029 1030 1031 1032 1033
      intervals_count_(stream.intervals_count_),
      first_interval_index_(stream.first_interval_index_) { }
  virtual ~TestStatsStream() {}
  virtual void EndOfStream() { ++eos_signaled_; }
  virtual WriteResult WriteAsciiChunk(char* buffer, int chars_written) {
1034
    DCHECK(false);
1035 1036
    return kAbort;
  }
1037 1038
  virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* buffer,
                                          int updates_written) {
1039
    ++intervals_count_;
1040
    DCHECK(updates_written);
1041
    updates_written_ += updates_written;
1042
    entries_count_ = 0;
1043 1044 1045 1046 1047
    if (first_interval_index_ == -1 && updates_written != 0)
      first_interval_index_ = buffer[0].index;
    for (int i = 0; i < updates_written; ++i) {
      entries_count_ += buffer[i].count;
      entries_size_ += buffer[i].size;
1048
    }
1049 1050 1051 1052

    return kContinue;
  }
  int eos_signaled() { return eos_signaled_; }
1053
  int updates_written() { return updates_written_; }
1054
  uint32_t entries_count() const { return entries_count_; }
1055
  uint32_t entries_size() const { return entries_size_; }
1056 1057 1058 1059 1060
  int intervals_count() const { return intervals_count_; }
  int first_interval_index() const { return first_interval_index_; }

 private:
  int eos_signaled_;
1061
  int updates_written_;
1062
  uint32_t entries_count_;
1063
  uint32_t entries_size_;
1064 1065 1066 1067 1068 1069
  int intervals_count_;
  int first_interval_index_;
};

}  // namespace

1070
static TestStatsStream GetHeapStatsUpdate(
1071
    v8::HeapProfiler* heap_profiler,
1072
    v8::SnapshotObjectId* object_id = NULL) {
1073
  TestStatsStream stream;
1074
  v8::SnapshotObjectId last_seen_id = heap_profiler->GetHeapStats(&stream);
1075 1076
  if (object_id)
    *object_id = last_seen_id;
1077 1078 1079 1080 1081 1082 1083
  CHECK_EQ(1, stream.eos_signaled());
  return stream;
}


TEST(HeapSnapshotObjectsStats) {
  LocalContext env;
1084
  v8::HandleScope scope(env->GetIsolate());
1085
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1086

1087
  heap_profiler->StartTrackingHeapObjects();
1088
  // We have to call GC 6 times. In other case the garbage will be
1089
  // the reason of flakiness.
1090
  for (int i = 0; i < 6; ++i) {
1091
    CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
1092 1093
  }

1094
  v8::SnapshotObjectId initial_id;
1095 1096
  {
    // Single chunk of data expected in update. Initial data.
1097 1098
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler,
                                                      &initial_id);
1099
    CHECK_EQ(1, stats_update.intervals_count());
1100
    CHECK_EQ(1, stats_update.updates_written());
1101
    CHECK_LT(0, stats_update.entries_size());
1102 1103 1104 1105
    CHECK_EQ(0, stats_update.first_interval_index());
  }

  // No data expected in update because nothing has happened.
1106
  v8::SnapshotObjectId same_id;
1107
  CHECK_EQ(0, GetHeapStatsUpdate(heap_profiler, &same_id).updates_written());
1108 1109
  CHECK_EQ_SNAPSHOT_OBJECT_ID(initial_id, same_id);

1110
  {
1111
    v8::SnapshotObjectId additional_string_id;
1112
    v8::HandleScope inner_scope_1(env->GetIsolate());
1113
    v8_str("string1");
1114 1115
    {
      // Single chunk of data with one new entry expected in update.
1116 1117
      TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler,
                                                        &additional_string_id);
1118
      CHECK_LT(same_id, additional_string_id);
1119
      CHECK_EQ(1, stats_update.intervals_count());
1120
      CHECK_EQ(1, stats_update.updates_written());
1121
      CHECK_LT(0, stats_update.entries_size());
1122 1123 1124 1125 1126
      CHECK_EQ(1, stats_update.entries_count());
      CHECK_EQ(2, stats_update.first_interval_index());
    }

    // No data expected in update because nothing happened.
1127
    v8::SnapshotObjectId last_id;
1128
    CHECK_EQ(0, GetHeapStatsUpdate(heap_profiler, &last_id).updates_written());
1129
    CHECK_EQ_SNAPSHOT_OBJECT_ID(additional_string_id, last_id);
1130 1131

    {
1132
      v8::HandleScope inner_scope_2(env->GetIsolate());
1133
      v8_str("string2");
1134

1135
      uint32_t entries_size;
1136
      {
1137
        v8::HandleScope inner_scope_3(env->GetIsolate());
1138 1139
        v8_str("string3");
        v8_str("string4");
1140 1141 1142

        {
          // Single chunk of data with three new entries expected in update.
1143
          TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1144
          CHECK_EQ(1, stats_update.intervals_count());
1145
          CHECK_EQ(1, stats_update.updates_written());
1146
          CHECK_LT(0, entries_size = stats_update.entries_size());
1147 1148 1149 1150 1151 1152 1153
          CHECK_EQ(3, stats_update.entries_count());
          CHECK_EQ(4, stats_update.first_interval_index());
        }
      }

      {
        // Single chunk of data with two left entries expected in update.
1154
        TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1155
        CHECK_EQ(1, stats_update.intervals_count());
1156
        CHECK_EQ(1, stats_update.updates_written());
1157
        CHECK_GT(entries_size, stats_update.entries_size());
1158 1159 1160 1161 1162 1163 1164 1165
        CHECK_EQ(1, stats_update.entries_count());
        // Two strings from forth interval were released.
        CHECK_EQ(4, stats_update.first_interval_index());
      }
    }

    {
      // Single chunk of data with 0 left entries expected in update.
1166
      TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1167
      CHECK_EQ(1, stats_update.intervals_count());
1168
      CHECK_EQ(1, stats_update.updates_written());
1169
      CHECK_EQ(0, stats_update.entries_size());
1170 1171 1172 1173 1174 1175 1176
      CHECK_EQ(0, stats_update.entries_count());
      // The last string from forth interval was released.
      CHECK_EQ(4, stats_update.first_interval_index());
    }
  }
  {
    // Single chunk of data with 0 left entries expected in update.
1177
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1178
    CHECK_EQ(1, stats_update.intervals_count());
1179
    CHECK_EQ(1, stats_update.updates_written());
1180
    CHECK_EQ(0, stats_update.entries_size());
1181 1182 1183 1184 1185
    CHECK_EQ(0, stats_update.entries_count());
    // The only string from the second interval was released.
    CHECK_EQ(2, stats_update.first_interval_index());
  }

1186
  v8::Local<v8::Array> array = v8::Array::New(env->GetIsolate());
1187 1188 1189 1190 1191 1192 1193
  CHECK_EQ(0, array->Length());
  // Force array's buffer allocation.
  array->Set(2, v8_num(7));

  uint32_t entries_size;
  {
    // Single chunk of data with 2 entries expected in update.
1194
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1195
    CHECK_EQ(1, stats_update.intervals_count());
1196
    CHECK_EQ(1, stats_update.updates_written());
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    CHECK_LT(0, entries_size = stats_update.entries_size());
    // They are the array and its buffer.
    CHECK_EQ(2, stats_update.entries_count());
    CHECK_EQ(8, stats_update.first_interval_index());
  }

  for (int i = 0; i < 100; ++i)
    array->Set(i, v8_num(i));

  {
    // Single chunk of data with 1 entry expected in update.
1208
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1209 1210 1211
    CHECK_EQ(1, stats_update.intervals_count());
    // The first interval was changed because old buffer was collected.
    // The second interval was changed because new buffer was allocated.
1212
    CHECK_EQ(2, stats_update.updates_written());
1213 1214 1215 1216 1217
    CHECK_LT(entries_size, stats_update.entries_size());
    CHECK_EQ(2, stats_update.entries_count());
    CHECK_EQ(8, stats_update.first_interval_index());
  }

1218
  heap_profiler->StopTrackingHeapObjects();
1219 1220
}

1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
TEST(HeapObjectIds) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  const int kLength = 10;
  v8::Handle<v8::Object> objects[kLength];
  v8::SnapshotObjectId ids[kLength];

  heap_profiler->StartTrackingHeapObjects(false);

  for (int i = 0; i < kLength; i++) {
    objects[i] = v8::Object::New(isolate);
  }
  GetHeapStatsUpdate(heap_profiler);

  for (int i = 0; i < kLength; i++) {
    v8::SnapshotObjectId id = heap_profiler->GetObjectId(objects[i]);
    CHECK_NE(v8::HeapProfiler::kUnknownObjectId, static_cast<int>(id));
    ids[i] = id;
  }

  heap_profiler->StopTrackingHeapObjects();
  CcTest::heap()->CollectAllAvailableGarbage();

  for (int i = 0; i < kLength; i++) {
    v8::SnapshotObjectId id = heap_profiler->GetObjectId(objects[i]);
    CHECK_EQ(static_cast<int>(ids[i]), static_cast<int>(id));
    v8::Handle<v8::Value> obj = heap_profiler->FindObjectById(ids[i]);
    CHECK_EQ(objects[i], obj);
  }

  heap_profiler->ClearObjectIds();
  for (int i = 0; i < kLength; i++) {
    v8::SnapshotObjectId id = heap_profiler->GetObjectId(objects[i]);
    CHECK_EQ(v8::HeapProfiler::kUnknownObjectId, static_cast<int>(id));
    v8::Handle<v8::Value> obj = heap_profiler->FindObjectById(ids[i]);
    CHECK(obj.IsEmpty());
  }
}


1265 1266 1267 1268 1269 1270 1271 1272 1273
static void CheckChildrenIds(const v8::HeapSnapshot* snapshot,
                             const v8::HeapGraphNode* node,
                             int level, int max_level) {
  if (level > max_level) return;
  CHECK_EQ(node, snapshot->GetNodeById(node->GetId()));
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = node->GetChild(i);
    const v8::HeapGraphNode* child =
        snapshot->GetNodeById(prop->GetToNode()->GetId());
1274
    CHECK_EQ_SNAPSHOT_OBJECT_ID(prop->GetToNode()->GetId(), child->GetId());
1275 1276 1277 1278 1279 1280
    CHECK_EQ(prop->GetToNode(), child);
    CheckChildrenIds(snapshot, child, level + 1, max_level);
  }
}


1281 1282
TEST(HeapSnapshotGetNodeById) {
  LocalContext env;
1283
  v8::HandleScope scope(env->GetIsolate());
1284
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1285 1286

  const v8::HeapSnapshot* snapshot =
1287
      heap_profiler->TakeHeapSnapshot(v8_str("id"));
1288
  CHECK(ValidateSnapshot(snapshot));
1289
  const v8::HeapGraphNode* root = snapshot->GetRoot();
1290
  CheckChildrenIds(snapshot, root, 0, 3);
1291 1292 1293 1294
  // Check a big id, which should not exist yet.
  CHECK_EQ(NULL, snapshot->GetNodeById(0x1000000UL));
}

1295

1296 1297
TEST(HeapSnapshotGetSnapshotObjectId) {
  LocalContext env;
1298
  v8::HandleScope scope(env->GetIsolate());
1299
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1300 1301
  CompileRun("globalObject = {};\n");
  const v8::HeapSnapshot* snapshot =
1302
      heap_profiler->TakeHeapSnapshot(v8_str("get_snapshot_object_id"));
1303
  CHECK(ValidateSnapshot(snapshot));
1304 1305 1306 1307 1308
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* global_object =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "globalObject");
  CHECK(global_object);

1309 1310
  v8::Local<v8::Value> globalObjectHandle = env->Global()->Get(
      v8::String::NewFromUtf8(env->GetIsolate(), "globalObject"));
1311 1312 1313
  CHECK(!globalObjectHandle.IsEmpty());
  CHECK(globalObjectHandle->IsObject());

1314
  v8::SnapshotObjectId id = heap_profiler->GetObjectId(globalObjectHandle);
1315 1316 1317 1318 1319 1320 1321 1322
  CHECK_NE(static_cast<int>(v8::HeapProfiler::kUnknownObjectId),
           id);
  CHECK_EQ(static_cast<int>(id), global_object->GetId());
}


TEST(HeapSnapshotUnknownSnapshotObjectId) {
  LocalContext env;
1323
  v8::HandleScope scope(env->GetIsolate());
1324
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1325 1326
  CompileRun("globalObject = {};\n");
  const v8::HeapSnapshot* snapshot =
1327
      heap_profiler->TakeHeapSnapshot(v8_str("unknown_object_id"));
1328
  CHECK(ValidateSnapshot(snapshot));
1329 1330 1331 1332 1333 1334
  const v8::HeapGraphNode* node =
      snapshot->GetNodeById(v8::HeapProfiler::kUnknownObjectId);
  CHECK_EQ(NULL, node);
}


1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
namespace {

class TestActivityControl : public v8::ActivityControl {
 public:
  explicit TestActivityControl(int abort_count)
      : done_(0), total_(0), abort_count_(abort_count) {}
  ControlOption ReportProgressValue(int done, int total) {
    done_ = done;
    total_ = total;
    return --abort_count_ != 0 ? kContinue : kAbort;
  }
  int done() { return done_; }
  int total() { return total_; }

 private:
  int done_;
  int total_;
  int abort_count_;
};
}

1356

1357 1358
TEST(TakeHeapSnapshotAborting) {
  LocalContext env;
1359
  v8::HandleScope scope(env->GetIsolate());
1360

1361 1362
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  const int snapshots_count = heap_profiler->GetSnapshotCount();
1363
  TestActivityControl aborting_control(1);
1364
  const v8::HeapSnapshot* no_snapshot =
1365
      heap_profiler->TakeHeapSnapshot(v8_str("abort"),
1366 1367
                                     &aborting_control);
  CHECK_EQ(NULL, no_snapshot);
1368
  CHECK_EQ(snapshots_count, heap_profiler->GetSnapshotCount());
1369 1370 1371 1372
  CHECK_GT(aborting_control.total(), aborting_control.done());

  TestActivityControl control(-1);  // Don't abort.
  const v8::HeapSnapshot* snapshot =
1373
      heap_profiler->TakeHeapSnapshot(v8_str("full"),
1374
                                     &control);
1375
  CHECK(ValidateSnapshot(snapshot));
1376

1377
  CHECK_NE(NULL, snapshot);
1378
  CHECK_EQ(snapshots_count + 1, heap_profiler->GetSnapshotCount());
1379 1380 1381 1382
  CHECK_EQ(control.total(), control.done());
  CHECK_GT(control.total(), 0);
}

1383 1384 1385 1386 1387 1388

namespace {

class TestRetainedObjectInfo : public v8::RetainedObjectInfo {
 public:
  TestRetainedObjectInfo(int hash,
1389
                         const char* group_label,
1390 1391 1392 1393 1394
                         const char* label,
                         intptr_t element_count = -1,
                         intptr_t size = -1)
      : disposed_(false),
        hash_(hash),
1395
        group_label_(group_label),
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
        label_(label),
        element_count_(element_count),
        size_(size) {
    instances.Add(this);
  }
  virtual ~TestRetainedObjectInfo() {}
  virtual void Dispose() {
    CHECK(!disposed_);
    disposed_ = true;
  }
  virtual bool IsEquivalent(RetainedObjectInfo* other) {
    return GetHash() == other->GetHash();
  }
  virtual intptr_t GetHash() { return hash_; }
1410
  virtual const char* GetGroupLabel() { return group_label_; }
1411 1412 1413 1414 1415 1416 1417 1418 1419
  virtual const char* GetLabel() { return label_; }
  virtual intptr_t GetElementCount() { return element_count_; }
  virtual intptr_t GetSizeInBytes() { return size_; }
  bool disposed() { return disposed_; }

  static v8::RetainedObjectInfo* WrapperInfoCallback(
      uint16_t class_id, v8::Handle<v8::Value> wrapper) {
    if (class_id == 1) {
      if (wrapper->IsString()) {
1420 1421
        v8::String::Utf8Value utf8(wrapper);
        if (strcmp(*utf8, "AAA") == 0)
1422
          return new TestRetainedObjectInfo(1, "aaa-group", "aaa", 100);
1423
        else if (strcmp(*utf8, "BBB") == 0)
1424
          return new TestRetainedObjectInfo(1, "aaa-group", "aaa", 100);
1425 1426 1427
      }
    } else if (class_id == 2) {
      if (wrapper->IsString()) {
1428 1429
        v8::String::Utf8Value utf8(wrapper);
        if (strcmp(*utf8, "CCC") == 0)
1430
          return new TestRetainedObjectInfo(2, "ccc-group", "ccc");
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
      }
    }
    CHECK(false);
    return NULL;
  }

  static i::List<TestRetainedObjectInfo*> instances;

 private:
  bool disposed_;
  int hash_;
1442
  const char* group_label_;
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
  const char* label_;
  intptr_t element_count_;
  intptr_t size_;
};


i::List<TestRetainedObjectInfo*> TestRetainedObjectInfo::instances;
}


static const v8::HeapGraphNode* GetNode(const v8::HeapGraphNode* parent,
                                        v8::HeapGraphNode::Type type,
                                        const char* name) {
  for (int i = 0, count = parent->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphNode* node = parent->GetChild(i)->GetToNode();
    if (node->GetType() == type && strcmp(name,
               const_cast<i::HeapEntry*>(
                   reinterpret_cast<const i::HeapEntry*>(node))->name()) == 0) {
      return node;
    }
  }
  return NULL;
}


TEST(HeapSnapshotRetainedObjectInfo) {
  LocalContext env;
1470
  v8::Isolate* isolate = env->GetIsolate();
1471
  v8::HandleScope scope(isolate);
1472
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
1473

1474
  heap_profiler->SetWrapperClassInfoProvider(
1475
      1, TestRetainedObjectInfo::WrapperInfoCallback);
1476
  heap_profiler->SetWrapperClassInfoProvider(
1477
      2, TestRetainedObjectInfo::WrapperInfoCallback);
1478
  v8::Persistent<v8::String> p_AAA(isolate, v8_str("AAA"));
1479
  p_AAA.SetWrapperClassId(1);
1480
  v8::Persistent<v8::String> p_BBB(isolate, v8_str("BBB"));
1481
  p_BBB.SetWrapperClassId(1);
1482
  v8::Persistent<v8::String> p_CCC(isolate, v8_str("CCC"));
1483
  p_CCC.SetWrapperClassId(2);
1484 1485
  CHECK_EQ(0, TestRetainedObjectInfo::instances.length());
  const v8::HeapSnapshot* snapshot =
1486
      heap_profiler->TakeHeapSnapshot(v8_str("retained"));
1487
  CHECK(ValidateSnapshot(snapshot));
1488 1489 1490 1491 1492 1493 1494

  CHECK_EQ(3, TestRetainedObjectInfo::instances.length());
  for (int i = 0; i < TestRetainedObjectInfo::instances.length(); ++i) {
    CHECK(TestRetainedObjectInfo::instances[i]->disposed());
    delete TestRetainedObjectInfo::instances[i];
  }

1495
  const v8::HeapGraphNode* native_group_aaa = GetNode(
1496
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "aaa-group");
1497 1498
  CHECK_NE(NULL, native_group_aaa);
  CHECK_EQ(1, native_group_aaa->GetChildrenCount());
1499
  const v8::HeapGraphNode* aaa = GetNode(
1500
      native_group_aaa, v8::HeapGraphNode::kNative, "aaa / 100 entries");
1501
  CHECK_NE(NULL, aaa);
1502 1503 1504
  CHECK_EQ(2, aaa->GetChildrenCount());

  const v8::HeapGraphNode* native_group_ccc = GetNode(
1505
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "ccc-group");
1506
  const v8::HeapGraphNode* ccc = GetNode(
1507
      native_group_ccc, v8::HeapGraphNode::kNative, "ccc");
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
  CHECK_NE(NULL, ccc);

  const v8::HeapGraphNode* n_AAA = GetNode(
      aaa, v8::HeapGraphNode::kString, "AAA");
  CHECK_NE(NULL, n_AAA);
  const v8::HeapGraphNode* n_BBB = GetNode(
      aaa, v8::HeapGraphNode::kString, "BBB");
  CHECK_NE(NULL, n_BBB);
  CHECK_EQ(1, ccc->GetChildrenCount());
  const v8::HeapGraphNode* n_CCC = GetNode(
      ccc, v8::HeapGraphNode::kString, "CCC");
  CHECK_NE(NULL, n_CCC);

1521 1522 1523
  CHECK_EQ(aaa, GetProperty(n_AAA, v8::HeapGraphEdge::kInternal, "native"));
  CHECK_EQ(aaa, GetProperty(n_BBB, v8::HeapGraphEdge::kInternal, "native"));
  CHECK_EQ(ccc, GetProperty(n_CCC, v8::HeapGraphEdge::kInternal, "native"));
1524 1525
}

1526

1527 1528 1529 1530 1531 1532
class GraphWithImplicitRefs {
 public:
  static const int kObjectsCount = 4;
  explicit GraphWithImplicitRefs(LocalContext* env) {
    CHECK_EQ(NULL, instance_);
    instance_ = this;
1533
    isolate_ = (*env)->GetIsolate();
1534
    for (int i = 0; i < kObjectsCount; i++) {
1535
      objects_[i].Reset(isolate_, v8::Object::New(isolate_));
1536
    }
1537 1538
    (*env)->Global()->Set(v8_str("root_object"),
                          v8::Local<v8::Value>::New(isolate_, objects_[0]));
1539 1540 1541 1542 1543
  }
  ~GraphWithImplicitRefs() {
    instance_ = NULL;
  }

1544
  static void gcPrologue(v8::GCType type, v8::GCCallbackFlags flags) {
1545 1546 1547 1548 1549 1550
    instance_->AddImplicitReferences();
  }

 private:
  void AddImplicitReferences() {
    // 0 -> 1
1551
    isolate_->SetObjectGroupId(objects_[0],
1552 1553
                               v8::UniqueId(1));
    isolate_->SetReferenceFromGroup(
1554
        v8::UniqueId(1), objects_[1]);
1555
    // Adding two more references: 1 -> 2, 1 -> 3
1556 1557 1558 1559
    isolate_->SetReference(objects_[1].As<v8::Object>(),
                           objects_[2]);
    isolate_->SetReference(objects_[1].As<v8::Object>(),
                           objects_[3]);
1560 1561 1562 1563
  }

  v8::Persistent<v8::Value> objects_[kObjectsCount];
  static GraphWithImplicitRefs* instance_;
1564
  v8::Isolate* isolate_;
1565 1566 1567 1568 1569 1570 1571
};

GraphWithImplicitRefs* GraphWithImplicitRefs::instance_ = NULL;


TEST(HeapSnapshotImplicitReferences) {
  LocalContext env;
1572
  v8::HandleScope scope(env->GetIsolate());
1573
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1574 1575

  GraphWithImplicitRefs graph(&env);
1576
  v8::V8::AddGCPrologueCallback(&GraphWithImplicitRefs::gcPrologue);
1577 1578

  const v8::HeapSnapshot* snapshot =
1579
      heap_profiler->TakeHeapSnapshot(v8_str("implicit_refs"));
1580
  CHECK(ValidateSnapshot(snapshot));
1581 1582 1583

  const v8::HeapGraphNode* global_object = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* obj0 = GetProperty(
1584
      global_object, v8::HeapGraphEdge::kProperty, "root_object");
1585 1586 1587 1588 1589 1590 1591 1592
  CHECK(obj0);
  CHECK_EQ(v8::HeapGraphNode::kObject, obj0->GetType());
  const v8::HeapGraphNode* obj1 = GetProperty(
      obj0, v8::HeapGraphEdge::kInternal, "native");
  CHECK(obj1);
  int implicit_targets_count = 0;
  for (int i = 0, count = obj1->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = obj1->GetChild(i);
1593
    v8::String::Utf8Value prop_name(prop->GetName());
1594 1595 1596 1597 1598 1599
    if (prop->GetType() == v8::HeapGraphEdge::kInternal &&
        strcmp("native", *prop_name) == 0) {
      ++implicit_targets_count;
    }
  }
  CHECK_EQ(2, implicit_targets_count);
1600
  v8::V8::RemoveGCPrologueCallback(&GraphWithImplicitRefs::gcPrologue);
1601 1602 1603
}


1604 1605
TEST(DeleteAllHeapSnapshots) {
  LocalContext env;
1606
  v8::HandleScope scope(env->GetIsolate());
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
  heap_profiler->DeleteAllHeapSnapshots();
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
  CHECK_NE(NULL, heap_profiler->TakeHeapSnapshot(v8_str("1")));
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
  heap_profiler->DeleteAllHeapSnapshots();
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
  CHECK_NE(NULL, heap_profiler->TakeHeapSnapshot(v8_str("1")));
  CHECK_NE(NULL, heap_profiler->TakeHeapSnapshot(v8_str("2")));
  CHECK_EQ(2, heap_profiler->GetSnapshotCount());
  heap_profiler->DeleteAllHeapSnapshots();
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1621 1622 1623
}


1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
static const v8::HeapSnapshot* FindHeapSnapshot(v8::HeapProfiler* profiler,
                                                unsigned uid) {
  int length = profiler->GetSnapshotCount();
  for (int i = 0; i < length; i++) {
    const v8::HeapSnapshot* snapshot = profiler->GetHeapSnapshot(i);
    if (snapshot->GetUid() == uid) {
      return snapshot;
    }
  }
  return NULL;
}


1637 1638
TEST(DeleteHeapSnapshot) {
  LocalContext env;
1639
  v8::HandleScope scope(env->GetIsolate());
1640
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1641

1642
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1643
  const v8::HeapSnapshot* s1 =
1644
      heap_profiler->TakeHeapSnapshot(v8_str("1"));
1645

1646
  CHECK_NE(NULL, s1);
1647
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1648
  unsigned uid1 = s1->GetUid();
1649
  CHECK_EQ(s1, FindHeapSnapshot(heap_profiler, uid1));
1650
  const_cast<v8::HeapSnapshot*>(s1)->Delete();
1651
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1652
  CHECK_EQ(NULL, FindHeapSnapshot(heap_profiler, uid1));
1653 1654

  const v8::HeapSnapshot* s2 =
1655
      heap_profiler->TakeHeapSnapshot(v8_str("2"));
1656
  CHECK_NE(NULL, s2);
1657
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1658 1659
  unsigned uid2 = s2->GetUid();
  CHECK_NE(static_cast<int>(uid1), static_cast<int>(uid2));
1660
  CHECK_EQ(s2, FindHeapSnapshot(heap_profiler, uid2));
1661
  const v8::HeapSnapshot* s3 =
1662
      heap_profiler->TakeHeapSnapshot(v8_str("3"));
1663
  CHECK_NE(NULL, s3);
1664
  CHECK_EQ(2, heap_profiler->GetSnapshotCount());
1665 1666
  unsigned uid3 = s3->GetUid();
  CHECK_NE(static_cast<int>(uid1), static_cast<int>(uid3));
1667
  CHECK_EQ(s3, FindHeapSnapshot(heap_profiler, uid3));
1668
  const_cast<v8::HeapSnapshot*>(s2)->Delete();
1669
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1670 1671
  CHECK_EQ(NULL, FindHeapSnapshot(heap_profiler, uid2));
  CHECK_EQ(s3, FindHeapSnapshot(heap_profiler, uid3));
1672
  const_cast<v8::HeapSnapshot*>(s3)->Delete();
1673
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1674
  CHECK_EQ(NULL, FindHeapSnapshot(heap_profiler, uid3));
1675 1676
}

1677

1678 1679 1680 1681 1682 1683 1684
class NameResolver : public v8::HeapProfiler::ObjectNameResolver {
 public:
  virtual const char* GetName(v8::Handle<v8::Object> object) {
    return "Global object name";
  }
};

1685

1686 1687
TEST(GlobalObjectName) {
  LocalContext env;
1688
  v8::HandleScope scope(env->GetIsolate());
1689
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1690 1691 1692 1693 1694

  CompileRun("document = { URL:\"abcdefgh\" };");

  NameResolver name_resolver;
  const v8::HeapSnapshot* snapshot =
1695
      heap_profiler->TakeHeapSnapshot(v8_str("document"),
1696 1697
      NULL,
      &name_resolver);
1698
  CHECK(ValidateSnapshot(snapshot));
1699 1700 1701 1702 1703 1704 1705 1706
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  CHECK_EQ("Object / Global object name" ,
           const_cast<i::HeapEntry*>(
               reinterpret_cast<const i::HeapEntry*>(global))->name());
}


1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
TEST(GlobalObjectFields) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun("obj = {};");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* builtins =
      GetProperty(global, v8::HeapGraphEdge::kInternal, "builtins");
  CHECK_NE(NULL, builtins);
  const v8::HeapGraphNode* native_context =
      GetProperty(global, v8::HeapGraphEdge::kInternal, "native_context");
  CHECK_NE(NULL, native_context);
  const v8::HeapGraphNode* global_context =
      GetProperty(global, v8::HeapGraphEdge::kInternal, "global_context");
  CHECK_NE(NULL, global_context);
1725 1726 1727
  const v8::HeapGraphNode* global_proxy =
      GetProperty(global, v8::HeapGraphEdge::kInternal, "global_proxy");
  CHECK_NE(NULL, global_proxy);
1728 1729 1730
}


1731 1732
TEST(NoHandleLeaks) {
  LocalContext env;
1733
  v8::HandleScope scope(env->GetIsolate());
1734
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1735 1736 1737 1738

  CompileRun("document = { URL:\"abcdefgh\" };");

  v8::Handle<v8::String> name(v8_str("leakz"));
1739
  i::Isolate* isolate = CcTest::i_isolate();
1740
  int count_before = i::HandleScope::NumberOfHandles(isolate);
1741
  heap_profiler->TakeHeapSnapshot(name);
1742
  int count_after = i::HandleScope::NumberOfHandles(isolate);
1743 1744 1745 1746
  CHECK_EQ(count_before, count_after);
}


1747 1748
TEST(NodesIteration) {
  LocalContext env;
1749
  v8::HandleScope scope(env->GetIsolate());
1750
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1751
  const v8::HeapSnapshot* snapshot =
1752
      heap_profiler->TakeHeapSnapshot(v8_str("iteration"));
1753
  CHECK(ValidateSnapshot(snapshot));
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  // Verify that we can find this object by iteration.
  const int nodes_count = snapshot->GetNodesCount();
  int count = 0;
  for (int i = 0; i < nodes_count; ++i) {
    if (snapshot->GetNode(i) == global)
      ++count;
  }
  CHECK_EQ(1, count);
}
1765 1766


1767
TEST(GetHeapValueForNode) {
1768
  LocalContext env;
1769
  v8::HandleScope scope(env->GetIsolate());
1770
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1771

1772
  CompileRun("a = { s_prop: \'value\', n_prop: \'value2\' };");
1773
  const v8::HeapSnapshot* snapshot =
1774
      heap_profiler->TakeHeapSnapshot(v8_str("value"));
1775
  CHECK(ValidateSnapshot(snapshot));
1776
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
1777
  CHECK(heap_profiler->FindObjectById(global->GetId())->IsObject());
1778 1779
  v8::Local<v8::Object> js_global =
      env->Global()->GetPrototype().As<v8::Object>();
1780
  CHECK(js_global == heap_profiler->FindObjectById(global->GetId()));
1781
  const v8::HeapGraphNode* obj = GetProperty(
1782
      global, v8::HeapGraphEdge::kProperty, "a");
1783
  CHECK(heap_profiler->FindObjectById(obj->GetId())->IsObject());
1784
  v8::Local<v8::Object> js_obj = js_global->Get(v8_str("a")).As<v8::Object>();
1785
  CHECK(js_obj == heap_profiler->FindObjectById(obj->GetId()));
1786 1787 1788 1789
  const v8::HeapGraphNode* s_prop =
      GetProperty(obj, v8::HeapGraphEdge::kProperty, "s_prop");
  v8::Local<v8::String> js_s_prop =
      js_obj->Get(v8_str("s_prop")).As<v8::String>();
1790
  CHECK(js_s_prop == heap_profiler->FindObjectById(s_prop->GetId()));
1791 1792
  const v8::HeapGraphNode* n_prop =
      GetProperty(obj, v8::HeapGraphEdge::kProperty, "n_prop");
1793 1794 1795
  v8::Local<v8::String> js_n_prop =
      js_obj->Get(v8_str("n_prop")).As<v8::String>();
  CHECK(js_n_prop == heap_profiler->FindObjectById(n_prop->GetId()));
1796 1797 1798 1799 1800
}


TEST(GetHeapValueForDeletedObject) {
  LocalContext env;
1801
  v8::HandleScope scope(env->GetIsolate());
1802
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1803 1804 1805 1806 1807 1808

  // It is impossible to delete a global property, so we are about to delete a
  // property of the "a" object. Also, the "p" object can't be an empty one
  // because the empty object is static and isn't actually deleted.
  CompileRun("a = { p: { r: {} } };");
  const v8::HeapSnapshot* snapshot =
1809
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1810
  CHECK(ValidateSnapshot(snapshot));
1811 1812
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* obj = GetProperty(
1813
      global, v8::HeapGraphEdge::kProperty, "a");
1814 1815 1816 1817 1818
  const v8::HeapGraphNode* prop = GetProperty(
      obj, v8::HeapGraphEdge::kProperty, "p");
  {
    // Perform the check inside a nested local scope to avoid creating a
    // reference to the object we are deleting.
1819
    v8::HandleScope scope(env->GetIsolate());
1820
    CHECK(heap_profiler->FindObjectById(prop->GetId())->IsObject());
1821 1822
  }
  CompileRun("delete a.p;");
1823
  CHECK(heap_profiler->FindObjectById(prop->GetId()).IsEmpty());
1824 1825 1826
}


1827
static int StringCmp(const char* ref, i::String* act) {
1828
  i::SmartArrayPointer<char> s_act = act->ToCString();
1829
  int result = strcmp(ref, s_act.get());
1830
  if (result != 0)
1831
    fprintf(stderr, "Expected: \"%s\", Actual: \"%s\"\n", ref, s_act.get());
1832 1833 1834 1835 1836 1837
  return result;
}


TEST(GetConstructorName) {
  LocalContext env;
1838
  v8::HandleScope scope(env->GetIsolate());
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865

  CompileRun(
      "function Constructor1() {};\n"
      "var obj1 = new Constructor1();\n"
      "var Constructor2 = function() {};\n"
      "var obj2 = new Constructor2();\n"
      "var obj3 = {};\n"
      "obj3.constructor = function Constructor3() {};\n"
      "var obj4 = {};\n"
      "// Slow properties\n"
      "for (var i=0; i<2000; ++i) obj4[\"p\" + i] = i;\n"
      "obj4.constructor = function Constructor4() {};\n"
      "var obj5 = {};\n"
      "var obj6 = {};\n"
      "obj6.constructor = 6;");
  v8::Local<v8::Object> js_global =
      env->Global()->GetPrototype().As<v8::Object>();
  v8::Local<v8::Object> obj1 = js_global->Get(v8_str("obj1")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj1 = v8::Utils::OpenHandle(*obj1);
  CHECK_EQ(0, StringCmp(
      "Constructor1", i::V8HeapExplorer::GetConstructorName(*js_obj1)));
  v8::Local<v8::Object> obj2 = js_global->Get(v8_str("obj2")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj2 = v8::Utils::OpenHandle(*obj2);
  CHECK_EQ(0, StringCmp(
      "Constructor2", i::V8HeapExplorer::GetConstructorName(*js_obj2)));
  v8::Local<v8::Object> obj3 = js_global->Get(v8_str("obj3")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj3 = v8::Utils::OpenHandle(*obj3);
1866 1867 1868 1869
  // TODO(verwaest): Restore to Constructor3 once supported by the
  // heap-snapshot-generator.
  CHECK_EQ(
      0, StringCmp("Object", i::V8HeapExplorer::GetConstructorName(*js_obj3)));
1870 1871
  v8::Local<v8::Object> obj4 = js_global->Get(v8_str("obj4")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj4 = v8::Utils::OpenHandle(*obj4);
1872 1873 1874 1875
  // TODO(verwaest): Restore to Constructor4 once supported by the
  // heap-snapshot-generator.
  CHECK_EQ(
      0, StringCmp("Object", i::V8HeapExplorer::GetConstructorName(*js_obj4)));
1876 1877 1878 1879 1880 1881 1882 1883 1884
  v8::Local<v8::Object> obj5 = js_global->Get(v8_str("obj5")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj5 = v8::Utils::OpenHandle(*obj5);
  CHECK_EQ(0, StringCmp(
      "Object", i::V8HeapExplorer::GetConstructorName(*js_obj5)));
  v8::Local<v8::Object> obj6 = js_global->Get(v8_str("obj6")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj6 = v8::Utils::OpenHandle(*obj6);
  CHECK_EQ(0, StringCmp(
      "Object", i::V8HeapExplorer::GetConstructorName(*js_obj6)));
}
1885

1886

1887
TEST(FastCaseAccessors) {
1888
  LocalContext env;
1889
  v8::HandleScope scope(env->GetIsolate());
1890
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1891 1892 1893 1894 1895 1896 1897 1898 1899

  CompileRun("var obj1 = {};\n"
             "obj1.__defineGetter__('propWithGetter', function Y() {\n"
             "  return 42;\n"
             "});\n"
             "obj1.__defineSetter__('propWithSetter', function Z(value) {\n"
             "  return this.value_ = value;\n"
             "});\n");
  const v8::HeapSnapshot* snapshot =
1900
      heap_profiler->TakeHeapSnapshot(v8_str("fastCaseAccessors"));
1901
  CHECK(ValidateSnapshot(snapshot));
1902 1903 1904 1905

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* obj1 =
1906
      GetProperty(global, v8::HeapGraphEdge::kProperty, "obj1");
1907
  CHECK_NE(NULL, obj1);
1908 1909 1910 1911 1912 1913 1914 1915 1916
  const v8::HeapGraphNode* func;
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "get propWithGetter");
  CHECK_NE(NULL, func);
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "set propWithGetter");
  CHECK_EQ(NULL, func);
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "set propWithSetter");
  CHECK_NE(NULL, func);
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "get propWithSetter");
  CHECK_EQ(NULL, func);
1917
}
1918

1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934

TEST(SlowCaseAccessors) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun("var obj1 = {};\n"
             "for (var i = 0; i < 100; ++i) obj1['z' + i] = {};"
             "obj1.__defineGetter__('propWithGetter', function Y() {\n"
             "  return 42;\n"
             "});\n"
             "obj1.__defineSetter__('propWithSetter', function Z(value) {\n"
             "  return this.value_ = value;\n"
             "});\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("slowCaseAccessors"));
1935
  CHECK(ValidateSnapshot(snapshot));
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* obj1 =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "obj1");
  CHECK_NE(NULL, obj1);
  const v8::HeapGraphNode* func;
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "get propWithGetter");
  CHECK_NE(NULL, func);
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "set propWithGetter");
  CHECK_EQ(NULL, func);
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "set propWithSetter");
  CHECK_NE(NULL, func);
  func = GetProperty(obj1, v8::HeapGraphEdge::kProperty, "get propWithSetter");
  CHECK_EQ(NULL, func);
}


1954 1955
TEST(HiddenPropertiesFastCase) {
  LocalContext env;
1956
  v8::HandleScope scope(env->GetIsolate());
1957
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1958 1959 1960 1961 1962

  CompileRun(
      "function C(x) { this.a = this; this.b = x; }\n"
      "c = new C(2012);\n");
  const v8::HeapSnapshot* snapshot =
1963
      heap_profiler->TakeHeapSnapshot(v8_str("HiddenPropertiesFastCase1"));
1964
  CHECK(ValidateSnapshot(snapshot));
1965 1966 1967 1968 1969 1970 1971 1972
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* c =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "c");
  CHECK_NE(NULL, c);
  const v8::HeapGraphNode* hidden_props =
      GetProperty(c, v8::HeapGraphEdge::kInternal, "hidden_properties");
  CHECK_EQ(NULL, hidden_props);

1973 1974
  v8::Handle<v8::Value> cHandle =
      env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "c"));
1975
  CHECK(!cHandle.IsEmpty() && cHandle->IsObject());
1976
  cHandle->ToObject()->SetHiddenValue(v8_str("key"), v8_str("val"));
1977

1978
  snapshot = heap_profiler->TakeHeapSnapshot(
1979
      v8_str("HiddenPropertiesFastCase2"));
1980
  CHECK(ValidateSnapshot(snapshot));
1981 1982 1983 1984 1985 1986 1987
  global = GetGlobalObject(snapshot);
  c = GetProperty(global, v8::HeapGraphEdge::kProperty, "c");
  CHECK_NE(NULL, c);
  hidden_props = GetProperty(c, v8::HeapGraphEdge::kInternal,
      "hidden_properties");
  CHECK_NE(NULL, hidden_props);
}
1988

1989

1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
TEST(AccessorInfo) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun("function foo(x) { }\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("AccessorInfoTest"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* foo =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "foo");
  CHECK_NE(NULL, foo);
  const v8::HeapGraphNode* map =
      GetProperty(foo, v8::HeapGraphEdge::kInternal, "map");
  CHECK_NE(NULL, map);
  const v8::HeapGraphNode* descriptors =
      GetProperty(map, v8::HeapGraphEdge::kInternal, "descriptors");
  CHECK_NE(NULL, descriptors);
  const v8::HeapGraphNode* length_name =
      GetProperty(descriptors, v8::HeapGraphEdge::kInternal, "2");
  CHECK_NE(NULL, length_name);
  CHECK_EQ("length", *v8::String::Utf8Value(length_name->GetName()));
  const v8::HeapGraphNode* length_accessor =
      GetProperty(descriptors, v8::HeapGraphEdge::kInternal, "4");
  CHECK_NE(NULL, length_accessor);
  CHECK_EQ("system / ExecutableAccessorInfo",
           *v8::String::Utf8Value(length_accessor->GetName()));
  const v8::HeapGraphNode* name =
      GetProperty(length_accessor, v8::HeapGraphEdge::kInternal, "name");
  CHECK_NE(NULL, name);
  const v8::HeapGraphNode* getter =
      GetProperty(length_accessor, v8::HeapGraphEdge::kInternal, "getter");
  CHECK_NE(NULL, getter);
  const v8::HeapGraphNode* setter =
      GetProperty(length_accessor, v8::HeapGraphEdge::kInternal, "setter");
  CHECK_NE(NULL, setter);
}


2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
bool HasWeakEdge(const v8::HeapGraphNode* node) {
  for (int i = 0; i < node->GetChildrenCount(); ++i) {
    const v8::HeapGraphEdge* handle_edge = node->GetChild(i);
    if (handle_edge->GetType() == v8::HeapGraphEdge::kWeak) return true;
  }
  return false;
}


bool HasWeakGlobalHandle() {
2040
  v8::Isolate* isolate = CcTest::isolate();
2041
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
2042
  const v8::HeapSnapshot* snapshot =
2043
      heap_profiler->TakeHeapSnapshot(v8_str("weaks"));
2044
  CHECK(ValidateSnapshot(snapshot));
2045
  const v8::HeapGraphNode* gc_roots = GetNode(
2046
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "(GC roots)");
2047 2048
  CHECK_NE(NULL, gc_roots);
  const v8::HeapGraphNode* global_handles = GetNode(
2049
      gc_roots, v8::HeapGraphNode::kSynthetic, "(Global handles)");
2050 2051 2052 2053 2054
  CHECK_NE(NULL, global_handles);
  return HasWeakEdge(global_handles);
}


2055 2056 2057 2058
static void PersistentHandleCallback(
    const v8::WeakCallbackData<v8::Object, v8::Persistent<v8::Object> >& data) {
  data.GetParameter()->Reset();
  delete data.GetParameter();
2059 2060 2061 2062 2063
}


TEST(WeakGlobalHandle) {
  LocalContext env;
2064
  v8::HandleScope scope(env->GetIsolate());
2065 2066 2067

  CHECK(!HasWeakGlobalHandle());

2068 2069 2070
  v8::Persistent<v8::Object> handle(env->GetIsolate(),
                                    v8::Object::New(env->GetIsolate()));
  handle.SetWeak(&handle, PersistentHandleCallback);
2071 2072 2073 2074 2075 2076 2077

  CHECK(HasWeakGlobalHandle());
}


TEST(SfiAndJsFunctionWeakRefs) {
  LocalContext env;
2078
  v8::HandleScope scope(env->GetIsolate());
2079
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2080 2081 2082 2083

  CompileRun(
      "fun = (function (x) { return function () { return x + 1; } })(1);");
  const v8::HeapSnapshot* snapshot =
2084
      heap_profiler->TakeHeapSnapshot(v8_str("fun"));
2085
  CHECK(ValidateSnapshot(snapshot));
2086 2087 2088
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* fun =
2089
      GetProperty(global, v8::HeapGraphEdge::kProperty, "fun");
2090
  CHECK(!HasWeakEdge(fun));
2091 2092
  const v8::HeapGraphNode* shared =
      GetProperty(fun, v8::HeapGraphEdge::kInternal, "shared");
2093
  CHECK(!HasWeakEdge(shared));
2094
}
2095 2096


2097 2098
TEST(NoDebugObjectInSnapshot) {
  LocalContext env;
2099
  v8::HandleScope scope(env->GetIsolate());
2100
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2101

2102
  CHECK(CcTest::i_isolate()->debug()->Load());
2103 2104
  CompileRun("foo = {};");
  const v8::HeapSnapshot* snapshot =
2105
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
2106
  CHECK(ValidateSnapshot(snapshot));
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
  const v8::HeapGraphNode* root = snapshot->GetRoot();
  int globals_count = 0;
  for (int i = 0; i < root->GetChildrenCount(); ++i) {
    const v8::HeapGraphEdge* edge = root->GetChild(i);
    if (edge->GetType() == v8::HeapGraphEdge::kShortcut) {
      ++globals_count;
      const v8::HeapGraphNode* global = edge->GetToNode();
      const v8::HeapGraphNode* foo =
          GetProperty(global, v8::HeapGraphEdge::kProperty, "foo");
      CHECK_NE(NULL, foo);
    }
  }
  CHECK_EQ(1, globals_count);
}


2123 2124
TEST(AllStrongGcRootsHaveNames) {
  LocalContext env;
2125
  v8::HandleScope scope(env->GetIsolate());
2126
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2127 2128 2129

  CompileRun("foo = {};");
  const v8::HeapSnapshot* snapshot =
2130
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
2131
  CHECK(ValidateSnapshot(snapshot));
2132
  const v8::HeapGraphNode* gc_roots = GetNode(
2133
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "(GC roots)");
2134 2135
  CHECK_NE(NULL, gc_roots);
  const v8::HeapGraphNode* strong_roots = GetNode(
2136
      gc_roots, v8::HeapGraphNode::kSynthetic, "(Strong roots)");
2137 2138 2139 2140
  CHECK_NE(NULL, strong_roots);
  for (int i = 0; i < strong_roots->GetChildrenCount(); ++i) {
    const v8::HeapGraphEdge* edge = strong_roots->GetChild(i);
    CHECK_EQ(v8::HeapGraphEdge::kInternal, edge->GetType());
2141
    v8::String::Utf8Value name(edge->GetName());
2142 2143 2144
    CHECK(isalpha(**name));
  }
}
2145 2146 2147 2148


TEST(NoRefsToNonEssentialEntries) {
  LocalContext env;
2149
  v8::HandleScope scope(env->GetIsolate());
2150
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2151 2152
  CompileRun("global_object = {};\n");
  const v8::HeapSnapshot* snapshot =
2153
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
2154
  CHECK(ValidateSnapshot(snapshot));
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* global_object =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "global_object");
  CHECK_NE(NULL, global_object);
  const v8::HeapGraphNode* properties =
      GetProperty(global_object, v8::HeapGraphEdge::kInternal, "properties");
  CHECK_EQ(NULL, properties);
  const v8::HeapGraphNode* elements =
      GetProperty(global_object, v8::HeapGraphEdge::kInternal, "elements");
  CHECK_EQ(NULL, elements);
}
2166 2167 2168 2169


TEST(MapHasDescriptorsAndTransitions) {
  LocalContext env;
2170
  v8::HandleScope scope(env->GetIsolate());
2171
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2172 2173
  CompileRun("obj = { a: 10 };\n");
  const v8::HeapSnapshot* snapshot =
2174
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
2175
  CHECK(ValidateSnapshot(snapshot));
2176 2177 2178 2179
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* global_object =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "obj");
  CHECK_NE(NULL, global_object);
2180

2181 2182 2183
  const v8::HeapGraphNode* map =
      GetProperty(global_object, v8::HeapGraphEdge::kInternal, "map");
  CHECK_NE(NULL, map);
2184 2185
  const v8::HeapGraphNode* own_descriptors = GetProperty(
      map, v8::HeapGraphEdge::kInternal, "descriptors");
2186
  CHECK_NE(NULL, own_descriptors);
2187 2188 2189
  const v8::HeapGraphNode* own_transitions = GetProperty(
      map, v8::HeapGraphEdge::kInternal, "transitions");
  CHECK_EQ(NULL, own_transitions);
2190
}
2191 2192 2193 2194


TEST(ManyLocalsInSharedContext) {
  LocalContext env;
2195 2196
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2197
  int num_objects = 6000;
2198
  CompileRun(
2199
      "var n = 6000;"
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
      "var result = [];"
      "result.push('(function outer() {');"
      "for (var i = 0; i < n; i++) {"
      "    var f = 'function f_' + i + '() { ';"
      "    if (i > 0)"
      "        f += 'f_' + (i - 1) + '();';"
      "    f += ' }';"
      "    result.push(f);"
      "}"
      "result.push('return f_' + (n - 1) + ';');"
      "result.push('})()');"
      "var ok = eval(result.join('\\n'));");
  const v8::HeapSnapshot* snapshot =
2213
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
2214
  CHECK(ValidateSnapshot(snapshot));
2215

2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* ok_object =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "ok");
  CHECK_NE(NULL, ok_object);
  const v8::HeapGraphNode* context_object =
      GetProperty(ok_object, v8::HeapGraphEdge::kInternal, "context");
  CHECK_NE(NULL, context_object);
  // Check the objects are not duplicated in the context.
  CHECK_EQ(v8::internal::Context::MIN_CONTEXT_SLOTS + num_objects - 1,
           context_object->GetChildrenCount());
  // Check all the objects have got their names.
2228 2229
  // ... well check just every 15th because otherwise it's too slow in debug.
  for (int i = 0; i < num_objects - 1; i += 15) {
alph@chromium.org's avatar
alph@chromium.org committed
2230
    i::EmbeddedVector<char, 100> var_name;
2231
    i::SNPrintF(var_name, "f_%d", i);
2232
    const v8::HeapGraphNode* f_object = GetProperty(
alph@chromium.org's avatar
alph@chromium.org committed
2233
        context_object, v8::HeapGraphEdge::kContextVariable, var_name.start());
2234 2235 2236
    CHECK_NE(NULL, f_object);
  }
}
2237 2238 2239 2240


TEST(AllocationSitesAreVisible) {
  LocalContext env;
2241 2242 2243
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
2244 2245 2246 2247 2248
  CompileRun(
      "fun = function () { var a = [3, 2, 1]; return a; }\n"
      "fun();");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
2249
  CHECK(ValidateSnapshot(snapshot));
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* fun_code =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "fun");
  CHECK_NE(NULL, fun_code);
  const v8::HeapGraphNode* literals =
      GetProperty(fun_code, v8::HeapGraphEdge::kInternal, "literals");
  CHECK_NE(NULL, literals);
  CHECK_EQ(v8::HeapGraphNode::kArray, literals->GetType());
  CHECK_EQ(2, literals->GetChildrenCount());

  // The second value in the literals array should be the boilerplate,
  // after an AllocationSite.
  const v8::HeapGraphEdge* prop = literals->GetChild(1);
  const v8::HeapGraphNode* allocation_site = prop->GetToNode();
  v8::String::Utf8Value name(allocation_site->GetName());
  CHECK_EQ("system / AllocationSite", *name);
  const v8::HeapGraphNode* transition_info =
      GetProperty(allocation_site, v8::HeapGraphEdge::kInternal,
                  "transition_info");
  CHECK_NE(NULL, transition_info);

  const v8::HeapGraphNode* elements =
      GetProperty(transition_info, v8::HeapGraphEdge::kInternal,
                  "elements");
  CHECK_NE(NULL, elements);
  CHECK_EQ(v8::HeapGraphNode::kArray, elements->GetType());
2278 2279
  CHECK_EQ(v8::internal::FixedArray::SizeFor(3),
           static_cast<int>(elements->GetShallowSize()));
2280

2281 2282 2283 2284
  v8::Handle<v8::Value> array_val =
      heap_profiler->FindObjectById(transition_info->GetId());
  CHECK(array_val->IsArray());
  v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(array_val);
2285 2286
  // Verify the array is "a" in the code above.
  CHECK_EQ(3, array->Length());
2287 2288 2289 2290 2291 2292
  CHECK_EQ(v8::Integer::New(isolate, 3),
           array->Get(v8::Integer::New(isolate, 0)));
  CHECK_EQ(v8::Integer::New(isolate, 2),
           array->Get(v8::Integer::New(isolate, 1)));
  CHECK_EQ(v8::Integer::New(isolate, 1),
           array->Get(v8::Integer::New(isolate, 2)));
2293
}
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311


TEST(JSFunctionHasCodeLink) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun("function foo(x, y) { return x + y; }\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* foo_func =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "foo");
  CHECK_NE(NULL, foo_func);
  const v8::HeapGraphNode* code =
      GetProperty(foo_func, v8::HeapGraphEdge::kInternal, "code");
  CHECK_NE(NULL, code);
}
2312 2313


2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
static const v8::HeapGraphNode* GetNodeByPath(const v8::HeapSnapshot* snapshot,
                                              const char* path[],
                                              int depth) {
  const v8::HeapGraphNode* node = snapshot->GetRoot();
  for (int current_depth = 0; current_depth < depth; ++current_depth) {
    int i, count = node->GetChildrenCount();
    for (i = 0; i < count; ++i) {
      const v8::HeapGraphEdge* edge = node->GetChild(i);
      const v8::HeapGraphNode* to_node = edge->GetToNode();
      v8::String::Utf8Value edge_name(edge->GetName());
      v8::String::Utf8Value node_name(to_node->GetName());
      i::EmbeddedVector<char, 100> name;
2326
      i::SNPrintF(name, "%s::%s", *edge_name, *node_name);
2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
      if (strstr(name.start(), path[current_depth])) {
        node = to_node;
        break;
      }
    }
    if (i == count) return NULL;
  }
  return node;
}


TEST(CheckCodeNames) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun("var a = 1.1;");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("CheckCodeNames"));
  CHECK(ValidateSnapshot(snapshot));

  const char* stub_path[] = {
    "::(GC roots)",
    "::(Strong roots)",
    "code_stubs::",
    "::(ArraySingleArgumentConstructorStub code)"
  };
  const v8::HeapGraphNode* node = GetNodeByPath(snapshot,
2354
      stub_path, arraysize(stub_path));
2355 2356
  CHECK_NE(NULL, node);

2357
  const char* builtin_path1[] = {
2358 2359
    "::(GC roots)",
    "::(Builtins)",
2360
    "::(KeyedLoadIC_Generic builtin)"
2361
  };
2362
  node = GetNodeByPath(snapshot, builtin_path1, arraysize(builtin_path1));
2363
  CHECK_NE(NULL, node);
2364

2365 2366
  const char* builtin_path2[] = {"::(GC roots)", "::(Builtins)",
                                 "::(CompileLazy builtin)"};
2367
  node = GetNodeByPath(snapshot, builtin_path2, arraysize(builtin_path2));
2368 2369
  CHECK_NE(NULL, node);
  v8::String::Utf8Value node_name(node->GetName());
2370
  CHECK_EQ("(CompileLazy builtin)", *node_name);
2371
}
2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423


static const char* record_trace_tree_source =
"var topFunctions = [];\n"
"var global = this;\n"
"function generateFunctions(width, depth) {\n"
"  var script = [];\n"
"  for (var i = 0; i < width; i++) {\n"
"    for (var j = 0; j < depth; j++) {\n"
"      script.push('function f_' + i + '_' + j + '(x) {\\n');\n"
"      script.push('  try {\\n');\n"
"      if (j < depth-2) {\n"
"        script.push('    return f_' + i + '_' + (j+1) + '(x+1);\\n');\n"
"      } else if (j == depth - 2) {\n"
"        script.push('    return new f_' + i + '_' + (depth - 1) + '();\\n');\n"
"      } else if (j == depth - 1) {\n"
"        script.push('    this.ts = Date.now();\\n');\n"
"      }\n"
"      script.push('  } catch (e) {}\\n');\n"
"      script.push('}\\n');\n"
"      \n"
"    }\n"
"  }\n"
"  var script = script.join('');\n"
"  // throw script;\n"
"  global.eval(script);\n"
"  for (var i = 0; i < width; i++) {\n"
"    topFunctions.push(this['f_' + i + '_0']);\n"
"  }\n"
"}\n"
"\n"
"var width = 3;\n"
"var depth = 3;\n"
"generateFunctions(width, depth);\n"
"var instances = [];\n"
"function start() {\n"
"  for (var i = 0; i < width; i++) {\n"
"    instances.push(topFunctions[i](0));\n"
"  }\n"
"}\n"
"\n"
"for (var i = 0; i < 100; i++) start();\n";


static AllocationTraceNode* FindNode(
    AllocationTracker* tracker, const Vector<const char*>& names) {
  AllocationTraceNode* node = tracker->trace_tree()->root();
  for (int i = 0; node != NULL && i < names.length(); i++) {
    const char* name = names[i];
    Vector<AllocationTraceNode*> children = node->children();
    node = NULL;
    for (int j = 0; j < children.length(); j++) {
2424 2425 2426
      unsigned index = children[j]->function_info_index();
      AllocationTracker::FunctionInfo* info =
          tracker->function_info_list()[index];
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436
      if (info && strcmp(info->name, name) == 0) {
        node = children[j];
        break;
      }
    }
  }
  return node;
}


2437 2438 2439 2440
TEST(ArrayGrowLeftTrim) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2441
  heap_profiler->StartTrackingHeapObjects(true);
2442 2443 2444 2445 2446 2447 2448 2449

  CompileRun(
    "var a = [];\n"
    "for (var i = 0; i < 5; ++i)\n"
    "    a[i] = i;\n"
    "for (var i = 0; i < 3; ++i)\n"
    "    a.shift();\n");

2450
  const char* names[] = {""};
2451 2452
  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2453 2454 2455 2456 2457 2458 2459
  CHECK_NE(NULL, tracker);
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

  AllocationTraceNode* node =
2460
      FindNode(tracker, Vector<const char*>(names, arraysize(names)));
2461 2462 2463
  CHECK_NE(NULL, node);
  CHECK_GE(node->allocation_count(), 2);
  CHECK_GE(node->allocation_size(), 4 * 5);
2464
  heap_profiler->StopTrackingHeapObjects();
2465 2466 2467
}


2468 2469 2470 2471 2472
TEST(TrackHeapAllocations) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2473
  heap_profiler->StartTrackingHeapObjects(true);
2474 2475 2476

  CompileRun(record_trace_tree_source);

2477 2478
  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2479 2480 2481 2482 2483 2484
  CHECK_NE(NULL, tracker);
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

2485
  const char* names[] = {"", "start", "f_0_0", "f_0_1", "f_0_2"};
2486
  AllocationTraceNode* node =
2487
      FindNode(tracker, Vector<const char*>(names, arraysize(names)));
2488 2489 2490
  CHECK_NE(NULL, node);
  CHECK_GE(node->allocation_count(), 100);
  CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
2491
  heap_profiler->StopTrackingHeapObjects();
2492
}
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519


static const char* inline_heap_allocation_source =
"function f_0(x) {\n"
"  return f_1(x+1);\n"
"}\n"
"%NeverOptimizeFunction(f_0);\n"
"function f_1(x) {\n"
"  return new f_2(x+1);\n"
"}\n"
"function f_2(x) {\n"
"  this.foo = x;\n"
"}\n"
"var instances = [];\n"
"function start() {\n"
"  instances.push(f_0(0));\n"
"}\n"
"\n"
"for (var i = 0; i < 100; i++) start();\n";


TEST(TrackBumpPointerAllocations) {
  i::FLAG_allow_natives_syntax = true;
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2520
  const char* names[] = {"", "start", "f_0", "f_1"};
2521 2522
  // First check that normally all allocations are recorded.
  {
2523
    heap_profiler->StartTrackingHeapObjects(true);
2524 2525 2526

    CompileRun(inline_heap_allocation_source);

2527 2528
    AllocationTracker* tracker =
        reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2529 2530 2531 2532 2533 2534 2535
    CHECK_NE(NULL, tracker);
    // Resolve all function locations.
    tracker->PrepareForSerialization();
    // Print for better diagnostics in case of failure.
    tracker->trace_tree()->Print(tracker);

    AllocationTraceNode* node =
2536
        FindNode(tracker, Vector<const char*>(names, arraysize(names)));
2537 2538 2539
    CHECK_NE(NULL, node);
    CHECK_GE(node->allocation_count(), 100);
    CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
2540
    heap_profiler->StopTrackingHeapObjects();
2541 2542 2543
  }

  {
2544
    heap_profiler->StartTrackingHeapObjects(true);
2545 2546 2547 2548 2549 2550 2551 2552

    // Now check that not all allocations are tracked if we manually reenable
    // inline allocations.
    CHECK(CcTest::heap()->inline_allocation_disabled());
    CcTest::heap()->EnableInlineAllocation();

    CompileRun(inline_heap_allocation_source);

2553 2554
    AllocationTracker* tracker =
        reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2555 2556 2557 2558 2559 2560 2561
    CHECK_NE(NULL, tracker);
    // Resolve all function locations.
    tracker->PrepareForSerialization();
    // Print for better diagnostics in case of failure.
    tracker->trace_tree()->Print(tracker);

    AllocationTraceNode* node =
2562
        FindNode(tracker, Vector<const char*>(names, arraysize(names)));
2563 2564 2565 2566
    CHECK_NE(NULL, node);
    CHECK_LT(node->allocation_count(), 100);

    CcTest::heap()->DisableInlineAllocation();
2567
    heap_profiler->StopTrackingHeapObjects();
2568 2569
  }
}
2570 2571


2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
TEST(TrackV8ApiAllocation) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  const char* names[] = { "(V8 API)" };
  heap_profiler->StartTrackingHeapObjects(true);

  v8::Handle<v8::Object> o1 = v8::Object::New(env->GetIsolate());
  o1->Clone();

  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
  CHECK_NE(NULL, tracker);
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

  AllocationTraceNode* node =
2592
      FindNode(tracker, Vector<const char*>(names, arraysize(names)));
2593 2594 2595 2596 2597 2598 2599
  CHECK_NE(NULL, node);
  CHECK_GE(node->allocation_count(), 2);
  CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
  heap_profiler->StopTrackingHeapObjects();
}


2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
TEST(ArrayBufferAndArrayBufferView) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun("arr1 = new Uint32Array(100);\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* arr1_obj =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "arr1");
  CHECK_NE(NULL, arr1_obj);
  const v8::HeapGraphNode* arr1_buffer =
      GetProperty(arr1_obj, v8::HeapGraphEdge::kInternal, "buffer");
  CHECK_NE(NULL, arr1_buffer);
  const v8::HeapGraphNode* first_view =
2616
      GetProperty(arr1_buffer, v8::HeapGraphEdge::kWeak, "weak_first_view");
2617
  CHECK_NE(NULL, first_view);
2618 2619 2620
  const v8::HeapGraphNode* backing_store =
      GetProperty(arr1_buffer, v8::HeapGraphEdge::kInternal, "backing_store");
  CHECK_NE(NULL, backing_store);
2621
  CHECK_EQ(400, static_cast<int>(backing_store->GetShallowSize()));
2622
}
2623 2624


2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641
static int GetRetainersCount(const v8::HeapSnapshot* snapshot,
                             const v8::HeapGraphNode* node) {
  int count = 0;
  for (int i = 0, l = snapshot->GetNodesCount(); i < l; ++i) {
    const v8::HeapGraphNode* parent = snapshot->GetNode(i);
    for (int j = 0, l2 = parent->GetChildrenCount(); j < l2; ++j) {
      if (parent->GetChild(j)->GetToNode() == node) {
        ++count;
      }
    }
  }
  return count;
}


TEST(ArrayBufferSharedBackingStore) {
  LocalContext env;
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();

  v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, 1024);
  CHECK_EQ(1024, static_cast<int>(ab->ByteLength()));
  CHECK(!ab->IsExternal());
  v8::ArrayBuffer::Contents ab_contents = ab->Externalize();
  CHECK(ab->IsExternal());

  CHECK_EQ(1024, static_cast<int>(ab_contents.ByteLength()));
  void* data = ab_contents.Data();
2654
  DCHECK(data != NULL);
2655 2656 2657 2658 2659 2660 2661 2662 2663
  v8::Local<v8::ArrayBuffer> ab2 =
      v8::ArrayBuffer::New(isolate, data, ab_contents.ByteLength());
  CHECK(ab2->IsExternal());
  env->Global()->Set(v8_str("ab1"), ab);
  env->Global()->Set(v8_str("ab2"), ab2);

  v8::Handle<v8::Value> result = CompileRun("ab2.byteLength");
  CHECK_EQ(1024, result->Int32Value());

2664 2665 2666
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
  CHECK(ValidateSnapshot(snapshot));
2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* ab1_node =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "ab1");
  CHECK_NE(NULL, ab1_node);
  const v8::HeapGraphNode* ab1_data =
      GetProperty(ab1_node, v8::HeapGraphEdge::kInternal, "backing_store");
  CHECK_NE(NULL, ab1_data);
  const v8::HeapGraphNode* ab2_node =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "ab2");
  CHECK_NE(NULL, ab2_node);
  const v8::HeapGraphNode* ab2_data =
      GetProperty(ab2_node, v8::HeapGraphEdge::kInternal, "backing_store");
  CHECK_NE(NULL, ab2_data);
  CHECK_EQ(ab1_data, ab2_data);
  CHECK_EQ(2, GetRetainersCount(snapshot, ab1_data));
  free(data);
2683 2684 2685
}


2686 2687 2688 2689 2690 2691 2692 2693
TEST(BoxObject) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  LocalContext env;
  v8::Handle<v8::Object> global_proxy = env->Global();
  v8::Handle<v8::Object> global = global_proxy->GetPrototype().As<v8::Object>();

  i::Factory* factory = CcTest::i_isolate()->factory();
2694
  i::Handle<i::String> string = factory->NewStringFromStaticChars("string");
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711
  i::Handle<i::Object> box = factory->NewBox(string);
  global->Set(0, v8::ToApiHandle<v8::Object>(box));

  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global_node = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* box_node =
      GetProperty(global_node, v8::HeapGraphEdge::kElement, "0");
  CHECK_NE(NULL, box_node);
  v8::String::Utf8Value box_node_name(box_node->GetName());
  CHECK_EQ("system / Box", *box_node_name);
  const v8::HeapGraphNode* box_value =
      GetProperty(box_node, v8::HeapGraphEdge::kInternal, "value");
  CHECK_NE(NULL, box_value);
}
2712 2713


2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
TEST(WeakContainers) {
  i::FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  if (!CcTest::i_isolate()->use_crankshaft()) return;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun(
      "function foo(a) { return a.x; }\n"
      "obj = {x : 123};\n"
      "foo(obj);\n"
      "foo(obj);\n"
      "%OptimizeFunctionOnNextCall(foo);\n"
      "foo(obj);\n");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* obj =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "obj");
  CHECK_NE(NULL, obj);
  const v8::HeapGraphNode* map =
      GetProperty(obj, v8::HeapGraphEdge::kInternal, "map");
  CHECK_NE(NULL, map);
  const v8::HeapGraphNode* dependent_code =
      GetProperty(map, v8::HeapGraphEdge::kInternal, "dependent_code");
  if (!dependent_code) return;
  int count = dependent_code->GetChildrenCount();
  CHECK_NE(0, count);
  for (int i = 0; i < count; ++i) {
    const v8::HeapGraphEdge* prop = dependent_code->GetChild(i);
    CHECK_EQ(v8::HeapGraphEdge::kWeak, prop->GetType());
  }
}


2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
static inline i::Address ToAddress(int n) {
  return reinterpret_cast<i::Address>(n);
}


TEST(AddressToTraceMap) {
  i::AddressToTraceMap map;

  CHECK_EQ(0, map.GetTraceNodeId(ToAddress(150)));

  // [0x100, 0x200) -> 1
  map.AddRange(ToAddress(0x100), 0x100, 1U);
  CHECK_EQ(0, map.GetTraceNodeId(ToAddress(0x50)));
  CHECK_EQ(1, map.GetTraceNodeId(ToAddress(0x100)));
  CHECK_EQ(1, map.GetTraceNodeId(ToAddress(0x150)));
  CHECK_EQ(0, map.GetTraceNodeId(ToAddress(0x100 + 0x100)));
2765
  CHECK_EQ(1, static_cast<int>(map.size()));
2766 2767 2768 2769

  // [0x100, 0x200) -> 1, [0x200, 0x300) -> 2
  map.AddRange(ToAddress(0x200), 0x100, 2U);
  CHECK_EQ(2, map.GetTraceNodeId(ToAddress(0x2a0)));
2770
  CHECK_EQ(2, static_cast<int>(map.size()));
2771 2772 2773 2774 2775 2776

  // [0x100, 0x180) -> 1, [0x180, 0x280) -> 3, [0x280, 0x300) -> 2
  map.AddRange(ToAddress(0x180), 0x100, 3U);
  CHECK_EQ(1, map.GetTraceNodeId(ToAddress(0x17F)));
  CHECK_EQ(2, map.GetTraceNodeId(ToAddress(0x280)));
  CHECK_EQ(3, map.GetTraceNodeId(ToAddress(0x180)));
2777
  CHECK_EQ(3, static_cast<int>(map.size()));
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787

  // [0x100, 0x180) -> 1, [0x180, 0x280) -> 3, [0x280, 0x300) -> 2,
  // [0x400, 0x500) -> 4
  map.AddRange(ToAddress(0x400), 0x100, 4U);
  CHECK_EQ(1, map.GetTraceNodeId(ToAddress(0x17F)));
  CHECK_EQ(2, map.GetTraceNodeId(ToAddress(0x280)));
  CHECK_EQ(3, map.GetTraceNodeId(ToAddress(0x180)));
  CHECK_EQ(4, map.GetTraceNodeId(ToAddress(0x450)));
  CHECK_EQ(0, map.GetTraceNodeId(ToAddress(0x500)));
  CHECK_EQ(0, map.GetTraceNodeId(ToAddress(0x350)));
2788
  CHECK_EQ(4, static_cast<int>(map.size()));
2789 2790 2791 2792 2793

  // [0x100, 0x180) -> 1, [0x180, 0x200) -> 3, [0x200, 0x600) -> 5
  map.AddRange(ToAddress(0x200), 0x400, 5U);
  CHECK_EQ(5, map.GetTraceNodeId(ToAddress(0x200)));
  CHECK_EQ(5, map.GetTraceNodeId(ToAddress(0x400)));
2794
  CHECK_EQ(3, static_cast<int>(map.size()));
2795 2796 2797 2798 2799 2800

  // [0x100, 0x180) -> 1, [0x180, 0x200) -> 7, [0x200, 0x600) ->5
  map.AddRange(ToAddress(0x180), 0x80, 6U);
  map.AddRange(ToAddress(0x180), 0x80, 7U);
  CHECK_EQ(7, map.GetTraceNodeId(ToAddress(0x180)));
  CHECK_EQ(5, map.GetTraceNodeId(ToAddress(0x200)));
2801
  CHECK_EQ(3, static_cast<int>(map.size()));
2802 2803

  map.Clear();
2804
  CHECK_EQ(0, static_cast<int>(map.size()));
2805 2806
  CHECK_EQ(0, map.GetTraceNodeId(ToAddress(0x400)));
}