test-heap-profiler.cc 82.1 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 33
#include "v8.h"

34
#include "allocation-tracker.h"
35
#include "cctest.h"
36
#include "hashmap.h"
37
#include "heap-profiler.h"
38
#include "snapshot.h"
39
#include "debug.h"
40
#include "utils-inl.h"
41
#include "../include/v8-profiler.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, x->GetSelfSize());
  CHECK_NE(0, x1->GetSelfSize());
  CHECK_NE(0, x2->GetSelfSize());
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 347
  CHECK_NE(NULL, lazy_code);

  // Verify that non-compiled code doesn't contain references to "x"
348 349
  // literal, while compiled code does. The scope info is stored in FixedArray
  // objects attached to the SharedFunctionInfo.
350 351 352 353
  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();
354
    if (node->GetType() == v8::HeapGraphNode::kArray) {
355 356 357 358 359 360 361 362 363
      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();
364
    if (node->GetType() == v8::HeapGraphNode::kArray) {
365 366 367 368 369 370 371 372 373 374
      if (HasString(node, "x")) {
        lazy_references_x = true;
        break;
      }
    }
  }
  CHECK(compiled_references_x);
  CHECK(!lazy_references_x);
}

375

376 377
TEST(HeapSnapshotHeapNumbers) {
  LocalContext env;
378
  v8::HandleScope scope(env->GetIsolate());
379
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
380 381 382 383
  CompileRun(
      "a = 1;    // a is Smi\n"
      "b = 2.5;  // b is HeapNumber");
  const v8::HeapSnapshot* snapshot =
384
      heap_profiler->TakeHeapSnapshot(v8_str("numbers"));
385
  CHECK(ValidateSnapshot(snapshot));
386
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
387
  CHECK_EQ(NULL, GetProperty(global, v8::HeapGraphEdge::kProperty, "a"));
388
  const v8::HeapGraphNode* b =
389
      GetProperty(global, v8::HeapGraphEdge::kProperty, "b");
390 391 392 393
  CHECK_NE(NULL, b);
  CHECK_EQ(v8::HeapGraphNode::kHeapNumber, b->GetType());
}

394

395 396
TEST(HeapSnapshotSlicedString) {
  LocalContext env;
397
  v8::HandleScope scope(env->GetIsolate());
398
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
399 400 401 402 403 404 405
  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 =
406
      heap_profiler->TakeHeapSnapshot(v8_str("strings"));
407
  CHECK(ValidateSnapshot(snapshot));
408 409
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* parent_string =
410
      GetProperty(global, v8::HeapGraphEdge::kProperty, "parent_string");
411 412
  CHECK_NE(NULL, parent_string);
  const v8::HeapGraphNode* child_string =
413
      GetProperty(global, v8::HeapGraphEdge::kProperty, "child_string");
414
  CHECK_NE(NULL, child_string);
415
  CHECK_EQ(v8::HeapGraphNode::kSlicedString, child_string->GetType());
416 417 418
  const v8::HeapGraphNode* parent =
      GetProperty(child_string, v8::HeapGraphEdge::kInternal, "parent");
  CHECK_EQ(parent_string, parent);
419
  heap_profiler->DeleteAllHeapSnapshots();
420
}
421

422

423
TEST(HeapSnapshotConsString) {
424
  v8::Isolate* isolate = CcTest::isolate();
425 426 427 428 429 430 431 432
  v8::HandleScope scope(isolate);
  v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
  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());

433
  i::Factory* factory = CcTest::i_isolate()->factory();
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  i::Handle<i::String> first =
      factory->NewStringFromAscii(i::CStrVector("0123456789"));
  i::Handle<i::String> second =
      factory->NewStringFromAscii(i::CStrVector("0123456789"));
  i::Handle<i::String> cons_string = factory->NewConsString(first, second);

  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();
}



466
TEST(HeapSnapshotInternalReferences) {
467
  v8::Isolate* isolate = CcTest::isolate();
468
  v8::HandleScope scope(isolate);
469 470 471 472 473 474 475 476 477
  v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
  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());
  v8::Local<v8::Object> obj = v8::Object::New();
  global->SetInternalField(0, v8_num(17));
  global->SetInternalField(1, obj);
478
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
479
  const v8::HeapSnapshot* snapshot =
480
      heap_profiler->TakeHeapSnapshot(v8_str("internals"));
481
  CHECK(ValidateSnapshot(snapshot));
482 483 484 485 486 487 488 489
  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"));
}


490
// Trying to introduce a check helper for uint32_t causes many
491 492
// overloading ambiguities, so it seems easier just to cast
// them to a signed type.
493 494 495
#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) \
496
  CHECK((a) != (b))  // NOLINT
497

498 499
TEST(HeapSnapshotAddressReuse) {
  LocalContext env;
500
  v8::HandleScope scope(env->GetIsolate());
501
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
502 503 504 505 506 507 508

  CompileRun(
      "function A() {}\n"
      "var a = [];\n"
      "for (var i = 0; i < 10000; ++i)\n"
      "  a[i] = new A();\n");
  const v8::HeapSnapshot* snapshot1 =
509
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot1"));
510
  CHECK(ValidateSnapshot(snapshot1));
511 512 513 514 515
  v8::SnapshotObjectId maxId1 = snapshot1->GetMaxSnapshotJSObjectId();

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

  const v8::HeapSnapshot* snapshot2 =
519
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot2"));
520
  CHECK(ValidateSnapshot(snapshot2));
521 522 523 524 525 526 527 528 529 530 531 532 533 534
  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;
  }
535
  CHECK_EQ(0, wrong_count);
536 537 538
}


539 540
TEST(HeapEntryIdsAndArrayShift) {
  LocalContext env;
541
  v8::HandleScope scope(env->GetIsolate());
542
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
543 544 545 546 547 548 549 550 551 552

  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 =
553
      heap_profiler->TakeHeapSnapshot(v8_str("s1"));
554
  CHECK(ValidateSnapshot(snapshot1));
555 556 557 558 559

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

560
  CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
561 562

  const v8::HeapSnapshot* snapshot2 =
563
      heap_profiler->TakeHeapSnapshot(v8_str("s2"));
564
  CHECK(ValidateSnapshot(snapshot2));
565 566 567

  const v8::HeapGraphNode* global1 = GetGlobalObject(snapshot1);
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);
568 569
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, global1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(global1->GetId(), global2->GetId());
570 571 572 573 574

  const v8::HeapGraphNode* a1 =
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a1);
  const v8::HeapGraphNode* k1 =
575
      GetProperty(a1, v8::HeapGraphEdge::kInternal, "elements");
576 577 578 579 580
  CHECK_NE(NULL, k1);
  const v8::HeapGraphNode* a2 =
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a2);
  const v8::HeapGraphNode* k2 =
581
      GetProperty(a2, v8::HeapGraphEdge::kInternal, "elements");
582 583
  CHECK_NE(NULL, k2);

584 585
  CHECK_EQ_SNAPSHOT_OBJECT_ID(a1->GetId(), a2->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(k1->GetId(), k2->GetId());
586 587
}

588

589 590
TEST(HeapEntryIdsAndGC) {
  LocalContext env;
591
  v8::HandleScope scope(env->GetIsolate());
592
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
593

594
  CompileRun(
595 596 597 598
      "function A() {}\n"
      "function B(x) { this.x = x; }\n"
      "var a = new A();\n"
      "var b = new B(a);");
599 600
  v8::Local<v8::String> s1_str = v8_str("s1");
  v8::Local<v8::String> s2_str = v8_str("s2");
601
  const v8::HeapSnapshot* snapshot1 =
602
      heap_profiler->TakeHeapSnapshot(s1_str);
603
  CHECK(ValidateSnapshot(snapshot1));
604

605
  CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
606 607

  const v8::HeapSnapshot* snapshot2 =
608
      heap_profiler->TakeHeapSnapshot(s2_str);
609
  CHECK(ValidateSnapshot(snapshot2));
610

611
  CHECK_GT(snapshot1->GetMaxSnapshotJSObjectId(), 7000);
612 613
  CHECK(snapshot1->GetMaxSnapshotJSObjectId() <=
        snapshot2->GetMaxSnapshotJSObjectId());
614 615 616

  const v8::HeapGraphNode* global1 = GetGlobalObject(snapshot1);
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);
617 618
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, global1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(global1->GetId(), global2->GetId());
619
  const v8::HeapGraphNode* A1 =
620 621
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "A");
  CHECK_NE(NULL, A1);
622
  const v8::HeapGraphNode* A2 =
623 624
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "A");
  CHECK_NE(NULL, A2);
625 626
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, A1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(A1->GetId(), A2->GetId());
627
  const v8::HeapGraphNode* B1 =
628 629
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "B");
  CHECK_NE(NULL, B1);
630
  const v8::HeapGraphNode* B2 =
631 632
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "B");
  CHECK_NE(NULL, B2);
633 634
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, B1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(B1->GetId(), B2->GetId());
635
  const v8::HeapGraphNode* a1 =
636 637
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a1);
638
  const v8::HeapGraphNode* a2 =
639 640
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "a");
  CHECK_NE(NULL, a2);
641 642
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, a1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(a1->GetId(), a2->GetId());
643
  const v8::HeapGraphNode* b1 =
644 645
      GetProperty(global1, v8::HeapGraphEdge::kProperty, "b");
  CHECK_NE(NULL, b1);
646
  const v8::HeapGraphNode* b2 =
647 648
      GetProperty(global2, v8::HeapGraphEdge::kProperty, "b");
  CHECK_NE(NULL, b2);
649 650
  CHECK_NE_SNAPSHOT_OBJECT_ID(0, b1->GetId());
  CHECK_EQ_SNAPSHOT_OBJECT_ID(b1->GetId(), b2->GetId());
651 652 653
}


654 655
TEST(HeapSnapshotRootPreservedAfterSorting) {
  LocalContext env;
656
  v8::HandleScope scope(env->GetIsolate());
657
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
658
  const v8::HeapSnapshot* snapshot =
659
      heap_profiler->TakeHeapSnapshot(v8_str("s"));
660
  CHECK(ValidateSnapshot(snapshot));
661 662 663 664 665 666 667 668
  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);
}


669 670 671 672
namespace {

class TestJSONStream : public v8::OutputStream {
 public:
673 674 675
  TestJSONStream() : eos_signaled_(0), abort_countdown_(-1) {}
  explicit TestJSONStream(int abort_countdown)
      : eos_signaled_(0), abort_countdown_(abort_countdown) {}
676 677
  virtual ~TestJSONStream() {}
  virtual void EndOfStream() { ++eos_signaled_; }
678 679 680
  virtual WriteResult WriteAsciiChunk(char* buffer, int chars_written) {
    if (abort_countdown_ > 0) --abort_countdown_;
    if (abort_countdown_ == 0) return kAbort;
681 682
    CHECK_GT(chars_written, 0);
    i::Vector<char> chunk = buffer_.AddBlock(chars_written, '\0');
683
    i::OS::MemCopy(chunk.start(), buffer, chars_written);
684
    return kContinue;
685
  }
686 687 688 689
  virtual WriteResult WriteUint32Chunk(uint32_t* buffer, int chars_written) {
    ASSERT(false);
    return kAbort;
  }
690 691 692
  void WriteTo(i::Vector<char> dest) { buffer_.WriteTo(dest); }
  int eos_signaled() { return eos_signaled_; }
  int size() { return buffer_.size(); }
693

694 695 696
 private:
  i::Collector<char> buffer_;
  int eos_signaled_;
697
  int abort_countdown_;
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
};

class AsciiResource: public v8::String::ExternalAsciiStringResource {
 public:
  explicit AsciiResource(i::Vector<char> string): data_(string.start()) {
    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;
716
  v8::HandleScope scope(env->GetIsolate());
717
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
718 719 720

#define STRING_LITERAL_FOR_TEST \
  "\"String \\n\\r\\u0008\\u0081\\u0101\\u0801\\u8001\""
721
  CompileRun(
722 723 724 725 726
      "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 =
727
      heap_profiler->TakeHeapSnapshot(v8_str("json"));
728
  CHECK(ValidateSnapshot(snapshot));
729

730 731 732 733 734 735 736 737 738
  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.
  AsciiResource json_res(json);
739 740
  v8::Local<v8::String> json_string =
      v8::String::NewExternal(env->GetIsolate(), &json_res);
741
  env->Global()->Set(v8_str("json_snapshot"), json_string);
742 743 744 745 746 747
  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 =
748 749 750
      env->Global()->Get(v8_str("parsed"))->ToObject();
  CHECK(parsed_snapshot->Has(v8_str("snapshot")));
  CHECK(parsed_snapshot->Has(v8_str("nodes")));
751
  CHECK(parsed_snapshot->Has(v8_str("edges")));
752
  CHECK(parsed_snapshot->Has(v8_str("strings")));
753 754 755

  // Get node and edge "member" offsets.
  v8::Local<v8::Value> meta_analysis_result = CompileRun(
756
      "var meta = parsed.snapshot.meta;\n"
757
      "var edge_count_offset = meta.node_fields.indexOf('edge_count');\n"
758 759 760 761 762
      "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"
763
      "var property_type ="
764
      "    meta.edge_types[edge_type_offset].indexOf('property');\n"
765
      "var shortcut_type ="
766
      "    meta.edge_types[edge_type_offset].indexOf('shortcut');\n"
767 768 769 770 771 772
      "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"
773 774
      "}\n"
      "first_edge_indexes[node_count] = first_edge_index;\n");
775 776 777 778
  CHECK(!meta_analysis_result.IsEmpty());

  // A helper function for processing encoded nodes.
  CompileRun(
779
      "function GetChildPosByProperty(pos, prop_name, prop_type) {\n"
780
      "  var nodes = parsed.nodes;\n"
781
      "  var edges = parsed.edges;\n"
782
      "  var strings = parsed.strings;\n"
783 784 785
      "  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"
786 787 788 789
      "      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"
790 791 792 793 794 795 796 797
      "  }\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("
798
      "      parsed.edges[edge_fields_count + edge_to_node_offset],"
799
      "      \"b\", property_type),\n"
800 801
      "    \"x\", property_type),"
      "  \"s\", property_type)");
802 803 804 805
  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 =
806
      parsed_snapshot->Get(v8_str("nodes"))->ToObject();
807 808 809 810
  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 =
811
      parsed_snapshot->Get(v8_str("strings"))->ToObject();
812 813 814 815 816 817 818 819
  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));
}

820 821 822

TEST(HeapSnapshotJSONSerializationAborting) {
  LocalContext env;
823
  v8::HandleScope scope(env->GetIsolate());
824
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
825
  const v8::HeapSnapshot* snapshot =
826
      heap_profiler->TakeHeapSnapshot(v8_str("abort"));
827
  CHECK(ValidateSnapshot(snapshot));
828 829 830 831 832 833
  TestJSONStream stream(5);
  snapshot->Serialize(&stream, v8::HeapSnapshot::kJSON);
  CHECK_GT(stream.size(), 0);
  CHECK_EQ(0, stream.eos_signaled());
}

834 835 836 837 838 839
namespace {

class TestStatsStream : public v8::OutputStream {
 public:
  TestStatsStream()
    : eos_signaled_(0),
840
      updates_written_(0),
841
      entries_count_(0),
842
      entries_size_(0),
843 844 845
      intervals_count_(0),
      first_interval_index_(-1) { }
  TestStatsStream(const TestStatsStream& stream)
loislo@chromium.org's avatar
loislo@chromium.org committed
846 847
    : v8::OutputStream(stream),
      eos_signaled_(stream.eos_signaled_),
848
      updates_written_(stream.updates_written_),
849
      entries_count_(stream.entries_count_),
850
      entries_size_(stream.entries_size_),
851 852 853 854 855 856 857 858
      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) {
    ASSERT(false);
    return kAbort;
  }
859 860
  virtual WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* buffer,
                                          int updates_written) {
861
    ++intervals_count_;
862 863
    ASSERT(updates_written);
    updates_written_ += updates_written;
864
    entries_count_ = 0;
865 866 867 868 869
    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;
870
    }
871 872 873 874

    return kContinue;
  }
  int eos_signaled() { return eos_signaled_; }
875
  int updates_written() { return updates_written_; }
876
  uint32_t entries_count() const { return entries_count_; }
877
  uint32_t entries_size() const { return entries_size_; }
878 879 880 881 882
  int intervals_count() const { return intervals_count_; }
  int first_interval_index() const { return first_interval_index_; }

 private:
  int eos_signaled_;
883
  int updates_written_;
884
  uint32_t entries_count_;
885
  uint32_t entries_size_;
886 887 888 889 890 891
  int intervals_count_;
  int first_interval_index_;
};

}  // namespace

892
static TestStatsStream GetHeapStatsUpdate(
893
    v8::HeapProfiler* heap_profiler,
894
    v8::SnapshotObjectId* object_id = NULL) {
895
  TestStatsStream stream;
896
  v8::SnapshotObjectId last_seen_id = heap_profiler->GetHeapStats(&stream);
897 898
  if (object_id)
    *object_id = last_seen_id;
899 900 901 902 903 904 905
  CHECK_EQ(1, stream.eos_signaled());
  return stream;
}


TEST(HeapSnapshotObjectsStats) {
  LocalContext env;
906
  v8::HandleScope scope(env->GetIsolate());
907
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
908

909
  heap_profiler->StartTrackingHeapObjects();
910
  // We have to call GC 6 times. In other case the garbage will be
911
  // the reason of flakiness.
912
  for (int i = 0; i < 6; ++i) {
913
    CcTest::heap()->CollectAllGarbage(i::Heap::kNoGCFlags);
914 915
  }

916
  v8::SnapshotObjectId initial_id;
917 918
  {
    // Single chunk of data expected in update. Initial data.
919 920
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler,
                                                      &initial_id);
921
    CHECK_EQ(1, stats_update.intervals_count());
922
    CHECK_EQ(1, stats_update.updates_written());
923
    CHECK_LT(0, stats_update.entries_size());
924 925 926 927
    CHECK_EQ(0, stats_update.first_interval_index());
  }

  // No data expected in update because nothing has happened.
928
  v8::SnapshotObjectId same_id;
929
  CHECK_EQ(0, GetHeapStatsUpdate(heap_profiler, &same_id).updates_written());
930 931
  CHECK_EQ_SNAPSHOT_OBJECT_ID(initial_id, same_id);

932
  {
933
    v8::SnapshotObjectId additional_string_id;
934
    v8::HandleScope inner_scope_1(env->GetIsolate());
935
    v8_str("string1");
936 937
    {
      // Single chunk of data with one new entry expected in update.
938 939
      TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler,
                                                        &additional_string_id);
940
      CHECK_LT(same_id, additional_string_id);
941
      CHECK_EQ(1, stats_update.intervals_count());
942
      CHECK_EQ(1, stats_update.updates_written());
943
      CHECK_LT(0, stats_update.entries_size());
944 945 946 947 948
      CHECK_EQ(1, stats_update.entries_count());
      CHECK_EQ(2, stats_update.first_interval_index());
    }

    // No data expected in update because nothing happened.
949
    v8::SnapshotObjectId last_id;
950
    CHECK_EQ(0, GetHeapStatsUpdate(heap_profiler, &last_id).updates_written());
951
    CHECK_EQ_SNAPSHOT_OBJECT_ID(additional_string_id, last_id);
952 953

    {
954
      v8::HandleScope inner_scope_2(env->GetIsolate());
955
      v8_str("string2");
956

957
      uint32_t entries_size;
958
      {
959
        v8::HandleScope inner_scope_3(env->GetIsolate());
960 961
        v8_str("string3");
        v8_str("string4");
962 963 964

        {
          // Single chunk of data with three new entries expected in update.
965
          TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
966
          CHECK_EQ(1, stats_update.intervals_count());
967
          CHECK_EQ(1, stats_update.updates_written());
968
          CHECK_LT(0, entries_size = stats_update.entries_size());
969 970 971 972 973 974 975
          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.
976
        TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
977
        CHECK_EQ(1, stats_update.intervals_count());
978
        CHECK_EQ(1, stats_update.updates_written());
979
        CHECK_GT(entries_size, stats_update.entries_size());
980 981 982 983 984 985 986 987
        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.
988
      TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
989
      CHECK_EQ(1, stats_update.intervals_count());
990
      CHECK_EQ(1, stats_update.updates_written());
991
      CHECK_EQ(0, stats_update.entries_size());
992 993 994 995 996 997 998
      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.
999
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1000
    CHECK_EQ(1, stats_update.intervals_count());
1001
    CHECK_EQ(1, stats_update.updates_written());
1002
    CHECK_EQ(0, stats_update.entries_size());
1003 1004 1005 1006 1007
    CHECK_EQ(0, stats_update.entries_count());
    // The only string from the second interval was released.
    CHECK_EQ(2, stats_update.first_interval_index());
  }

1008
  v8::Local<v8::Array> array = v8::Array::New(env->GetIsolate());
1009 1010 1011 1012 1013 1014 1015
  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.
1016
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1017
    CHECK_EQ(1, stats_update.intervals_count());
1018
    CHECK_EQ(1, stats_update.updates_written());
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    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.
1030
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1031 1032 1033
    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.
1034
    CHECK_EQ(2, stats_update.updates_written());
1035 1036 1037 1038 1039
    CHECK_LT(entries_size, stats_update.entries_size());
    CHECK_EQ(2, stats_update.entries_count());
    CHECK_EQ(8, stats_update.first_interval_index());
  }

1040
  heap_profiler->StopTrackingHeapObjects();
1041 1042
}

1043

1044 1045 1046 1047 1048 1049 1050 1051 1052
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());
1053
    CHECK_EQ_SNAPSHOT_OBJECT_ID(prop->GetToNode()->GetId(), child->GetId());
1054 1055 1056 1057 1058 1059
    CHECK_EQ(prop->GetToNode(), child);
    CheckChildrenIds(snapshot, child, level + 1, max_level);
  }
}


1060 1061
TEST(HeapSnapshotGetNodeById) {
  LocalContext env;
1062
  v8::HandleScope scope(env->GetIsolate());
1063
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1064 1065

  const v8::HeapSnapshot* snapshot =
1066
      heap_profiler->TakeHeapSnapshot(v8_str("id"));
1067
  CHECK(ValidateSnapshot(snapshot));
1068
  const v8::HeapGraphNode* root = snapshot->GetRoot();
1069
  CheckChildrenIds(snapshot, root, 0, 3);
1070 1071 1072 1073
  // Check a big id, which should not exist yet.
  CHECK_EQ(NULL, snapshot->GetNodeById(0x1000000UL));
}

1074

1075 1076
TEST(HeapSnapshotGetSnapshotObjectId) {
  LocalContext env;
1077
  v8::HandleScope scope(env->GetIsolate());
1078
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1079 1080
  CompileRun("globalObject = {};\n");
  const v8::HeapSnapshot* snapshot =
1081
      heap_profiler->TakeHeapSnapshot(v8_str("get_snapshot_object_id"));
1082
  CHECK(ValidateSnapshot(snapshot));
1083 1084 1085 1086 1087
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* global_object =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "globalObject");
  CHECK(global_object);

1088 1089
  v8::Local<v8::Value> globalObjectHandle = env->Global()->Get(
      v8::String::NewFromUtf8(env->GetIsolate(), "globalObject"));
1090 1091 1092
  CHECK(!globalObjectHandle.IsEmpty());
  CHECK(globalObjectHandle->IsObject());

1093
  v8::SnapshotObjectId id = heap_profiler->GetObjectId(globalObjectHandle);
1094 1095 1096 1097 1098 1099 1100 1101
  CHECK_NE(static_cast<int>(v8::HeapProfiler::kUnknownObjectId),
           id);
  CHECK_EQ(static_cast<int>(id), global_object->GetId());
}


TEST(HeapSnapshotUnknownSnapshotObjectId) {
  LocalContext env;
1102
  v8::HandleScope scope(env->GetIsolate());
1103
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1104 1105
  CompileRun("globalObject = {};\n");
  const v8::HeapSnapshot* snapshot =
1106
      heap_profiler->TakeHeapSnapshot(v8_str("unknown_object_id"));
1107
  CHECK(ValidateSnapshot(snapshot));
1108 1109 1110 1111 1112 1113
  const v8::HeapGraphNode* node =
      snapshot->GetNodeById(v8::HeapProfiler::kUnknownObjectId);
  CHECK_EQ(NULL, node);
}


1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
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_;
};
}

1135

1136 1137
TEST(TakeHeapSnapshotAborting) {
  LocalContext env;
1138
  v8::HandleScope scope(env->GetIsolate());
1139

1140 1141
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  const int snapshots_count = heap_profiler->GetSnapshotCount();
1142
  TestActivityControl aborting_control(1);
1143
  const v8::HeapSnapshot* no_snapshot =
1144
      heap_profiler->TakeHeapSnapshot(v8_str("abort"),
1145 1146
                                     &aborting_control);
  CHECK_EQ(NULL, no_snapshot);
1147
  CHECK_EQ(snapshots_count, heap_profiler->GetSnapshotCount());
1148 1149 1150 1151
  CHECK_GT(aborting_control.total(), aborting_control.done());

  TestActivityControl control(-1);  // Don't abort.
  const v8::HeapSnapshot* snapshot =
1152
      heap_profiler->TakeHeapSnapshot(v8_str("full"),
1153
                                     &control);
1154
  CHECK(ValidateSnapshot(snapshot));
1155

1156
  CHECK_NE(NULL, snapshot);
1157
  CHECK_EQ(snapshots_count + 1, heap_profiler->GetSnapshotCount());
1158 1159 1160 1161
  CHECK_EQ(control.total(), control.done());
  CHECK_GT(control.total(), 0);
}

1162 1163 1164 1165 1166 1167

namespace {

class TestRetainedObjectInfo : public v8::RetainedObjectInfo {
 public:
  TestRetainedObjectInfo(int hash,
1168
                         const char* group_label,
1169 1170 1171 1172 1173
                         const char* label,
                         intptr_t element_count = -1,
                         intptr_t size = -1)
      : disposed_(false),
        hash_(hash),
1174
        group_label_(group_label),
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
        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_; }
1189
  virtual const char* GetGroupLabel() { return group_label_; }
1190 1191 1192 1193 1194 1195 1196 1197 1198
  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()) {
1199 1200
        v8::String::Utf8Value utf8(wrapper);
        if (strcmp(*utf8, "AAA") == 0)
1201
          return new TestRetainedObjectInfo(1, "aaa-group", "aaa", 100);
1202
        else if (strcmp(*utf8, "BBB") == 0)
1203
          return new TestRetainedObjectInfo(1, "aaa-group", "aaa", 100);
1204 1205 1206
      }
    } else if (class_id == 2) {
      if (wrapper->IsString()) {
1207 1208
        v8::String::Utf8Value utf8(wrapper);
        if (strcmp(*utf8, "CCC") == 0)
1209
          return new TestRetainedObjectInfo(2, "ccc-group", "ccc");
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
      }
    }
    CHECK(false);
    return NULL;
  }

  static i::List<TestRetainedObjectInfo*> instances;

 private:
  bool disposed_;
  int hash_;
1221
  const char* group_label_;
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
  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;
1249
  v8::Isolate* isolate = env->GetIsolate();
1250
  v8::HandleScope scope(isolate);
1251
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
1252

1253
  heap_profiler->SetWrapperClassInfoProvider(
1254
      1, TestRetainedObjectInfo::WrapperInfoCallback);
1255
  heap_profiler->SetWrapperClassInfoProvider(
1256
      2, TestRetainedObjectInfo::WrapperInfoCallback);
1257
  v8::Persistent<v8::String> p_AAA(isolate, v8_str("AAA"));
1258
  p_AAA.SetWrapperClassId(1);
1259
  v8::Persistent<v8::String> p_BBB(isolate, v8_str("BBB"));
1260
  p_BBB.SetWrapperClassId(1);
1261
  v8::Persistent<v8::String> p_CCC(isolate, v8_str("CCC"));
1262
  p_CCC.SetWrapperClassId(2);
1263 1264
  CHECK_EQ(0, TestRetainedObjectInfo::instances.length());
  const v8::HeapSnapshot* snapshot =
1265
      heap_profiler->TakeHeapSnapshot(v8_str("retained"));
1266
  CHECK(ValidateSnapshot(snapshot));
1267 1268 1269 1270 1271 1272 1273

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

1274
  const v8::HeapGraphNode* native_group_aaa = GetNode(
1275
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "aaa-group");
1276 1277
  CHECK_NE(NULL, native_group_aaa);
  CHECK_EQ(1, native_group_aaa->GetChildrenCount());
1278
  const v8::HeapGraphNode* aaa = GetNode(
1279
      native_group_aaa, v8::HeapGraphNode::kNative, "aaa / 100 entries");
1280
  CHECK_NE(NULL, aaa);
1281 1282 1283
  CHECK_EQ(2, aaa->GetChildrenCount());

  const v8::HeapGraphNode* native_group_ccc = GetNode(
1284
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "ccc-group");
1285
  const v8::HeapGraphNode* ccc = GetNode(
1286
      native_group_ccc, v8::HeapGraphNode::kNative, "ccc");
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
  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);

1300 1301 1302
  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"));
1303 1304
}

1305

1306 1307 1308 1309 1310 1311
class GraphWithImplicitRefs {
 public:
  static const int kObjectsCount = 4;
  explicit GraphWithImplicitRefs(LocalContext* env) {
    CHECK_EQ(NULL, instance_);
    instance_ = this;
1312
    isolate_ = (*env)->GetIsolate();
1313
    for (int i = 0; i < kObjectsCount; i++) {
1314
      objects_[i].Reset(isolate_, v8::Object::New());
1315
    }
1316 1317
    (*env)->Global()->Set(v8_str("root_object"),
                          v8::Local<v8::Value>::New(isolate_, objects_[0]));
1318 1319 1320 1321 1322
  }
  ~GraphWithImplicitRefs() {
    instance_ = NULL;
  }

1323
  static void gcPrologue(v8::GCType type, v8::GCCallbackFlags flags) {
1324 1325 1326 1327 1328 1329
    instance_->AddImplicitReferences();
  }

 private:
  void AddImplicitReferences() {
    // 0 -> 1
1330
    isolate_->SetObjectGroupId(objects_[0],
1331 1332
                               v8::UniqueId(1));
    isolate_->SetReferenceFromGroup(
1333
        v8::UniqueId(1), objects_[1]);
1334
    // Adding two more references: 1 -> 2, 1 -> 3
1335 1336 1337 1338
    isolate_->SetReference(objects_[1].As<v8::Object>(),
                           objects_[2]);
    isolate_->SetReference(objects_[1].As<v8::Object>(),
                           objects_[3]);
1339 1340 1341 1342
  }

  v8::Persistent<v8::Value> objects_[kObjectsCount];
  static GraphWithImplicitRefs* instance_;
1343
  v8::Isolate* isolate_;
1344 1345 1346 1347 1348 1349 1350
};

GraphWithImplicitRefs* GraphWithImplicitRefs::instance_ = NULL;


TEST(HeapSnapshotImplicitReferences) {
  LocalContext env;
1351
  v8::HandleScope scope(env->GetIsolate());
1352
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1353 1354

  GraphWithImplicitRefs graph(&env);
1355
  v8::V8::AddGCPrologueCallback(&GraphWithImplicitRefs::gcPrologue);
1356 1357

  const v8::HeapSnapshot* snapshot =
1358
      heap_profiler->TakeHeapSnapshot(v8_str("implicit_refs"));
1359
  CHECK(ValidateSnapshot(snapshot));
1360 1361 1362

  const v8::HeapGraphNode* global_object = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* obj0 = GetProperty(
1363
      global_object, v8::HeapGraphEdge::kProperty, "root_object");
1364 1365 1366 1367 1368 1369 1370 1371
  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);
1372
    v8::String::Utf8Value prop_name(prop->GetName());
1373 1374 1375 1376 1377 1378
    if (prop->GetType() == v8::HeapGraphEdge::kInternal &&
        strcmp("native", *prop_name) == 0) {
      ++implicit_targets_count;
    }
  }
  CHECK_EQ(2, implicit_targets_count);
1379
  v8::V8::RemoveGCPrologueCallback(&GraphWithImplicitRefs::gcPrologue);
1380 1381 1382
}


1383 1384
TEST(DeleteAllHeapSnapshots) {
  LocalContext env;
1385
  v8::HandleScope scope(env->GetIsolate());
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
  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());
1400 1401 1402
}


1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
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;
}


1416 1417
TEST(DeleteHeapSnapshot) {
  LocalContext env;
1418
  v8::HandleScope scope(env->GetIsolate());
1419
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1420

1421
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1422
  const v8::HeapSnapshot* s1 =
1423
      heap_profiler->TakeHeapSnapshot(v8_str("1"));
1424

1425
  CHECK_NE(NULL, s1);
1426
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1427
  unsigned uid1 = s1->GetUid();
1428
  CHECK_EQ(s1, FindHeapSnapshot(heap_profiler, uid1));
1429
  const_cast<v8::HeapSnapshot*>(s1)->Delete();
1430
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1431
  CHECK_EQ(NULL, FindHeapSnapshot(heap_profiler, uid1));
1432 1433

  const v8::HeapSnapshot* s2 =
1434
      heap_profiler->TakeHeapSnapshot(v8_str("2"));
1435
  CHECK_NE(NULL, s2);
1436
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1437 1438
  unsigned uid2 = s2->GetUid();
  CHECK_NE(static_cast<int>(uid1), static_cast<int>(uid2));
1439
  CHECK_EQ(s2, FindHeapSnapshot(heap_profiler, uid2));
1440
  const v8::HeapSnapshot* s3 =
1441
      heap_profiler->TakeHeapSnapshot(v8_str("3"));
1442
  CHECK_NE(NULL, s3);
1443
  CHECK_EQ(2, heap_profiler->GetSnapshotCount());
1444 1445
  unsigned uid3 = s3->GetUid();
  CHECK_NE(static_cast<int>(uid1), static_cast<int>(uid3));
1446
  CHECK_EQ(s3, FindHeapSnapshot(heap_profiler, uid3));
1447
  const_cast<v8::HeapSnapshot*>(s2)->Delete();
1448
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1449 1450
  CHECK_EQ(NULL, FindHeapSnapshot(heap_profiler, uid2));
  CHECK_EQ(s3, FindHeapSnapshot(heap_profiler, uid3));
1451
  const_cast<v8::HeapSnapshot*>(s3)->Delete();
1452
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1453
  CHECK_EQ(NULL, FindHeapSnapshot(heap_profiler, uid3));
1454 1455
}

1456

1457 1458 1459 1460 1461 1462 1463
class NameResolver : public v8::HeapProfiler::ObjectNameResolver {
 public:
  virtual const char* GetName(v8::Handle<v8::Object> object) {
    return "Global object name";
  }
};

1464

1465 1466
TEST(GlobalObjectName) {
  LocalContext env;
1467
  v8::HandleScope scope(env->GetIsolate());
1468
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1469 1470 1471 1472 1473

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

  NameResolver name_resolver;
  const v8::HeapSnapshot* snapshot =
1474
      heap_profiler->TakeHeapSnapshot(v8_str("document"),
1475 1476
      NULL,
      &name_resolver);
1477
  CHECK(ValidateSnapshot(snapshot));
1478 1479 1480 1481 1482 1483 1484 1485
  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());
}


1486 1487
TEST(NoHandleLeaks) {
  LocalContext env;
1488
  v8::HandleScope scope(env->GetIsolate());
1489
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1490 1491 1492 1493

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

  v8::Handle<v8::String> name(v8_str("leakz"));
1494
  i::Isolate* isolate = CcTest::i_isolate();
1495
  int count_before = i::HandleScope::NumberOfHandles(isolate);
1496
  heap_profiler->TakeHeapSnapshot(name);
1497
  int count_after = i::HandleScope::NumberOfHandles(isolate);
1498 1499 1500 1501
  CHECK_EQ(count_before, count_after);
}


1502 1503
TEST(NodesIteration) {
  LocalContext env;
1504
  v8::HandleScope scope(env->GetIsolate());
1505
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1506
  const v8::HeapSnapshot* snapshot =
1507
      heap_profiler->TakeHeapSnapshot(v8_str("iteration"));
1508
  CHECK(ValidateSnapshot(snapshot));
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
  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);
}
1520 1521


1522 1523
TEST(GetHeapValue) {
  LocalContext env;
1524
  v8::HandleScope scope(env->GetIsolate());
1525
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1526 1527 1528

  CompileRun("a = { s_prop: \'value\', n_prop: 0.1 };");
  const v8::HeapSnapshot* snapshot =
1529
      heap_profiler->TakeHeapSnapshot(v8_str("value"));
1530
  CHECK(ValidateSnapshot(snapshot));
1531 1532 1533 1534 1535 1536
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK(global->GetHeapValue()->IsObject());
  v8::Local<v8::Object> js_global =
      env->Global()->GetPrototype().As<v8::Object>();
  CHECK(js_global == global->GetHeapValue());
  const v8::HeapGraphNode* obj = GetProperty(
1537
      global, v8::HeapGraphEdge::kProperty, "a");
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
  CHECK(obj->GetHeapValue()->IsObject());
  v8::Local<v8::Object> js_obj = js_global->Get(v8_str("a")).As<v8::Object>();
  CHECK(js_obj == obj->GetHeapValue());
  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>();
  CHECK(js_s_prop == s_prop->GetHeapValue());
  const v8::HeapGraphNode* n_prop =
      GetProperty(obj, v8::HeapGraphEdge::kProperty, "n_prop");
  v8::Local<v8::Number> js_n_prop =
      js_obj->Get(v8_str("n_prop")).As<v8::Number>();
1550
  CHECK(js_n_prop->NumberValue() == n_prop->GetHeapValue()->NumberValue());
1551 1552 1553 1554 1555
}


TEST(GetHeapValueForDeletedObject) {
  LocalContext env;
1556
  v8::HandleScope scope(env->GetIsolate());
1557
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1558 1559 1560 1561 1562 1563

  // 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 =
1564
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1565
  CHECK(ValidateSnapshot(snapshot));
1566 1567
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* obj = GetProperty(
1568
      global, v8::HeapGraphEdge::kProperty, "a");
1569 1570 1571 1572 1573
  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.
1574
    v8::HandleScope scope(env->GetIsolate());
1575 1576 1577 1578 1579 1580 1581
    CHECK(prop->GetHeapValue()->IsObject());
  }
  CompileRun("delete a.p;");
  CHECK(prop->GetHeapValue()->IsUndefined());
}


1582
static int StringCmp(const char* ref, i::String* act) {
1583
  i::SmartArrayPointer<char> s_act = act->ToCString();
1584 1585 1586 1587 1588 1589 1590 1591 1592
  int result = strcmp(ref, *s_act);
  if (result != 0)
    fprintf(stderr, "Expected: \"%s\", Actual: \"%s\"\n", ref, *s_act);
  return result;
}


TEST(GetConstructorName) {
  LocalContext env;
1593
  v8::HandleScope scope(env->GetIsolate());
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

  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);
  CHECK_EQ(0, StringCmp(
      "Constructor3", i::V8HeapExplorer::GetConstructorName(*js_obj3)));
  v8::Local<v8::Object> obj4 = js_global->Get(v8_str("obj4")).As<v8::Object>();
  i::Handle<i::JSObject> js_obj4 = v8::Utils::OpenHandle(*obj4);
  CHECK_EQ(0, StringCmp(
      "Constructor4", i::V8HeapExplorer::GetConstructorName(*js_obj4)));
  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)));
}
1636

1637

1638
TEST(FastCaseAccessors) {
1639
  LocalContext env;
1640
  v8::HandleScope scope(env->GetIsolate());
1641
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1642 1643 1644 1645 1646 1647 1648 1649 1650

  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 =
1651
      heap_profiler->TakeHeapSnapshot(v8_str("fastCaseAccessors"));
1652
  CHECK(ValidateSnapshot(snapshot));
1653 1654 1655 1656

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* obj1 =
1657
      GetProperty(global, v8::HeapGraphEdge::kProperty, "obj1");
1658
  CHECK_NE(NULL, obj1);
1659 1660 1661 1662 1663 1664 1665 1666 1667
  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);
1668
}
1669

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685

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"));
1686
  CHECK(ValidateSnapshot(snapshot));
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704

  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);
}


1705 1706
TEST(HiddenPropertiesFastCase) {
  LocalContext env;
1707
  v8::HandleScope scope(env->GetIsolate());
1708
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1709 1710 1711 1712 1713

  CompileRun(
      "function C(x) { this.a = this; this.b = x; }\n"
      "c = new C(2012);\n");
  const v8::HeapSnapshot* snapshot =
1714
      heap_profiler->TakeHeapSnapshot(v8_str("HiddenPropertiesFastCase1"));
1715
  CHECK(ValidateSnapshot(snapshot));
1716 1717 1718 1719 1720 1721 1722 1723
  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);

1724 1725
  v8::Handle<v8::Value> cHandle =
      env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "c"));
1726
  CHECK(!cHandle.IsEmpty() && cHandle->IsObject());
1727
  cHandle->ToObject()->SetHiddenValue(v8_str("key"), v8_str("val"));
1728

1729
  snapshot = heap_profiler->TakeHeapSnapshot(
1730
      v8_str("HiddenPropertiesFastCase2"));
1731
  CHECK(ValidateSnapshot(snapshot));
1732 1733 1734 1735 1736 1737 1738
  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);
}
1739

1740

1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
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() {
1751
  v8::Isolate* isolate = CcTest::isolate();
1752
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
1753
  const v8::HeapSnapshot* snapshot =
1754
      heap_profiler->TakeHeapSnapshot(v8_str("weaks"));
1755
  CHECK(ValidateSnapshot(snapshot));
1756
  const v8::HeapGraphNode* gc_roots = GetNode(
1757
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "(GC roots)");
1758 1759
  CHECK_NE(NULL, gc_roots);
  const v8::HeapGraphNode* global_handles = GetNode(
1760
      gc_roots, v8::HeapGraphNode::kSynthetic, "(Global handles)");
1761 1762 1763 1764 1765
  CHECK_NE(NULL, global_handles);
  return HasWeakEdge(global_handles);
}


1766 1767 1768 1769
static void PersistentHandleCallback(
    const v8::WeakCallbackData<v8::Object, v8::Persistent<v8::Object> >& data) {
  data.GetParameter()->Reset();
  delete data.GetParameter();
1770 1771 1772 1773 1774
}


TEST(WeakGlobalHandle) {
  LocalContext env;
1775
  v8::HandleScope scope(env->GetIsolate());
1776 1777 1778

  CHECK(!HasWeakGlobalHandle());

1779 1780 1781
  v8::Persistent<v8::Object>* handle =
      new v8::Persistent<v8::Object>(env->GetIsolate(), v8::Object::New());
  handle->SetWeak(handle, PersistentHandleCallback);
1782 1783 1784 1785 1786 1787 1788

  CHECK(HasWeakGlobalHandle());
}


TEST(SfiAndJsFunctionWeakRefs) {
  LocalContext env;
1789
  v8::HandleScope scope(env->GetIsolate());
1790
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1791 1792 1793 1794

  CompileRun(
      "fun = (function (x) { return function () { return x + 1; } })(1);");
  const v8::HeapSnapshot* snapshot =
1795
      heap_profiler->TakeHeapSnapshot(v8_str("fun"));
1796
  CHECK(ValidateSnapshot(snapshot));
1797 1798 1799
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_NE(NULL, global);
  const v8::HeapGraphNode* fun =
1800
      GetProperty(global, v8::HeapGraphEdge::kProperty, "fun");
1801
  CHECK(!HasWeakEdge(fun));
1802 1803
  const v8::HeapGraphNode* shared =
      GetProperty(fun, v8::HeapGraphEdge::kInternal, "shared");
1804
  CHECK(!HasWeakEdge(shared));
1805
}
1806 1807


1808
#ifdef ENABLE_DEBUGGER_SUPPORT
1809 1810
TEST(NoDebugObjectInSnapshot) {
  LocalContext env;
1811
  v8::HandleScope scope(env->GetIsolate());
1812
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1813

1814
  CcTest::i_isolate()->debug()->Load();
1815 1816
  CompileRun("foo = {};");
  const v8::HeapSnapshot* snapshot =
1817
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1818
  CHECK(ValidateSnapshot(snapshot));
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
  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);
}
1833
#endif  // ENABLE_DEBUGGER_SUPPORT
1834 1835


1836 1837
TEST(AllStrongGcRootsHaveNames) {
  LocalContext env;
1838
  v8::HandleScope scope(env->GetIsolate());
1839
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1840 1841 1842

  CompileRun("foo = {};");
  const v8::HeapSnapshot* snapshot =
1843
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1844
  CHECK(ValidateSnapshot(snapshot));
1845
  const v8::HeapGraphNode* gc_roots = GetNode(
1846
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "(GC roots)");
1847 1848
  CHECK_NE(NULL, gc_roots);
  const v8::HeapGraphNode* strong_roots = GetNode(
1849
      gc_roots, v8::HeapGraphNode::kSynthetic, "(Strong roots)");
1850 1851 1852 1853
  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());
1854
    v8::String::Utf8Value name(edge->GetName());
1855 1856 1857
    CHECK(isalpha(**name));
  }
}
1858 1859 1860 1861


TEST(NoRefsToNonEssentialEntries) {
  LocalContext env;
1862
  v8::HandleScope scope(env->GetIsolate());
1863
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1864 1865
  CompileRun("global_object = {};\n");
  const v8::HeapSnapshot* snapshot =
1866
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1867
  CHECK(ValidateSnapshot(snapshot));
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  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);
}
1879 1880 1881 1882


TEST(MapHasDescriptorsAndTransitions) {
  LocalContext env;
1883
  v8::HandleScope scope(env->GetIsolate());
1884
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1885 1886
  CompileRun("obj = { a: 10 };\n");
  const v8::HeapSnapshot* snapshot =
1887
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1888
  CHECK(ValidateSnapshot(snapshot));
1889 1890 1891 1892
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* global_object =
      GetProperty(global, v8::HeapGraphEdge::kProperty, "obj");
  CHECK_NE(NULL, global_object);
1893

1894 1895 1896
  const v8::HeapGraphNode* map =
      GetProperty(global_object, v8::HeapGraphEdge::kInternal, "map");
  CHECK_NE(NULL, map);
1897 1898
  const v8::HeapGraphNode* own_descriptors = GetProperty(
      map, v8::HeapGraphEdge::kInternal, "descriptors");
1899
  CHECK_NE(NULL, own_descriptors);
1900 1901 1902
  const v8::HeapGraphNode* own_transitions = GetProperty(
      map, v8::HeapGraphEdge::kInternal, "transitions");
  CHECK_EQ(NULL, own_transitions);
1903
}
1904 1905 1906 1907


TEST(ManyLocalsInSharedContext) {
  LocalContext env;
1908 1909
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1910
  int num_objects = 6000;
1911
  CompileRun(
1912
      "var n = 6000;"
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
      "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 =
1926
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1927
  CHECK(ValidateSnapshot(snapshot));
1928

1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
  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.
1941 1942
  // ... 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
1943 1944
    i::EmbeddedVector<char, 100> var_name;
    i::OS::SNPrintF(var_name, "f_%d", i);
1945
    const v8::HeapGraphNode* f_object = GetProperty(
alph@chromium.org's avatar
alph@chromium.org committed
1946
        context_object, v8::HeapGraphEdge::kContextVariable, var_name.start());
1947 1948 1949
    CHECK_NE(NULL, f_object);
  }
}
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960


TEST(AllocationSitesAreVisible) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun(
      "fun = function () { var a = [3, 2, 1]; return a; }\n"
      "fun();");
  const v8::HeapSnapshot* snapshot =
      heap_profiler->TakeHeapSnapshot(v8_str("snapshot"));
1961
  CHECK(ValidateSnapshot(snapshot));
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000

  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());
  CHECK_EQ(v8::internal::FixedArray::SizeFor(3), elements->GetSelfSize());

  CHECK(transition_info->GetHeapValue()->IsArray());
  v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(
      transition_info->GetHeapValue());
  // Verify the array is "a" in the code above.
  CHECK_EQ(3, array->Length());
  CHECK_EQ(v8::Integer::New(3), array->Get(v8::Integer::New(0)));
  CHECK_EQ(v8::Integer::New(2), array->Get(v8::Integer::New(1)));
  CHECK_EQ(v8::Integer::New(1), array->Get(v8::Integer::New(2)));
}
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018


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);
}
2019 2020


2021 2022 2023 2024 2025

class HeapProfilerExtension : public v8::Extension {
 public:
  static const char* kName;
  HeapProfilerExtension() : v8::Extension(kName, kSource) { }
2026 2027
  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
      v8::Isolate* isolate,
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
      v8::Handle<v8::String> name);
  static void FindUntrackedObjects(
      const v8::FunctionCallbackInfo<v8::Value>& args);
 private:
  static const char* kSource;
};

const char* HeapProfilerExtension::kName = "v8/heap-profiler";


const char* HeapProfilerExtension::kSource =
    "native function findUntrackedObjects();";


2042 2043 2044 2045
v8::Handle<v8::FunctionTemplate>
HeapProfilerExtension::GetNativeFunctionTemplate(v8::Isolate* isolate,
                                                 v8::Handle<v8::String> name) {
  if (name->Equals(v8::String::NewFromUtf8(isolate, "findUntrackedObjects"))) {
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
    return v8::FunctionTemplate::New(
        HeapProfilerExtension::FindUntrackedObjects);
  } else {
    CHECK(false);
    return v8::Handle<v8::FunctionTemplate>();
  }
}


void HeapProfilerExtension::FindUntrackedObjects(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  i::HeapProfiler* heap_profiler =
      reinterpret_cast<i::HeapProfiler*>(args.GetIsolate()->GetHeapProfiler());
2059 2060
  int untracked_objects =
      heap_profiler->heap_object_map()->FindUntrackedObjects();
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070
  args.GetReturnValue().Set(untracked_objects);
  CHECK_EQ(0, untracked_objects);
}


static HeapProfilerExtension kHeapProfilerExtension;
v8::DeclareExtension kHeapProfilerExtensionDeclaration(
    &kHeapProfilerExtension);


2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
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;
      i::OS::SNPrintF(name, "%s::%s", *edge_name, *node_name);
      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,
      stub_path, ARRAY_SIZE(stub_path));
  CHECK_NE(NULL, node);

  const char* builtin_path[] = {
    "::(GC roots)",
    "::(Builtins)",
    "::(KeyedLoadIC_Generic code)"
  };
  node = GetNodeByPath(snapshot, builtin_path, ARRAY_SIZE(builtin_path));
  CHECK_NE(NULL, node);
}
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185


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++) {
      v8::SnapshotObjectId id = children[j]->function_id();
      AllocationTracker::FunctionInfo* info = tracker->GetFunctionInfo(id);
      if (info && strcmp(info->name, name) == 0) {
        node = children[j];
        break;
      }
    }
  }
  return node;
}


2186 2187 2188 2189
TEST(ArrayGrowLeftTrim) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2190
  heap_profiler->StartTrackingHeapObjects(true);
2191 2192 2193 2194 2195 2196 2197 2198 2199

  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");

  const char* names[] = { "(anonymous function)" };
2200 2201
  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
  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 =
      FindNode(tracker, Vector<const char*>(names, ARRAY_SIZE(names)));
  CHECK_NE(NULL, node);
  CHECK_GE(node->allocation_count(), 2);
  CHECK_GE(node->allocation_size(), 4 * 5);
2213
  heap_profiler->StopTrackingHeapObjects();
2214 2215 2216
}


2217 2218 2219 2220 2221
TEST(TrackHeapAllocations) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2222
  heap_profiler->StartTrackingHeapObjects(true);
2223 2224 2225

  CompileRun(record_trace_tree_source);

2226 2227
  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
  CHECK_NE(NULL, tracker);
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

  const char* names[] =
      { "(anonymous function)", "start", "f_0_0", "f_0_1", "f_0_2" };
  AllocationTraceNode* node =
      FindNode(tracker, Vector<const char*>(names, ARRAY_SIZE(names)));
  CHECK_NE(NULL, node);
  CHECK_GE(node->allocation_count(), 100);
  CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
2241
  heap_profiler->StopTrackingHeapObjects();
2242
}
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272


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();
  const char* names[] = { "(anonymous function)", "start", "f_0", "f_1" };
  // First check that normally all allocations are recorded.
  {
2273
    heap_profiler->StartTrackingHeapObjects(true);
2274 2275 2276

    CompileRun(inline_heap_allocation_source);

2277 2278
    AllocationTracker* tracker =
        reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
    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 =
        FindNode(tracker, Vector<const char*>(names, ARRAY_SIZE(names)));
    CHECK_NE(NULL, node);
    CHECK_GE(node->allocation_count(), 100);
    CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
2290
    heap_profiler->StopTrackingHeapObjects();
2291 2292 2293
  }

  {
2294
    heap_profiler->StartTrackingHeapObjects(true);
2295 2296 2297 2298 2299 2300 2301 2302

    // 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);

2303 2304
    AllocationTracker* tracker =
        reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
    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 =
        FindNode(tracker, Vector<const char*>(names, ARRAY_SIZE(names)));
    CHECK_NE(NULL, node);
    CHECK_LT(node->allocation_count(), 100);

    CcTest::heap()->DisableInlineAllocation();
2317
    heap_profiler->StopTrackingHeapObjects();
2318 2319
  }
}