test-heap-profiler.cc 146 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 <memory>

34
#include "src/v8.h"
35

36
#include "include/v8-profiler.h"
37
#include "src/api-inl.h"
38
#include "src/assembler-inl.h"
lpy's avatar
lpy committed
39
#include "src/base/hashmap.h"
40
#include "src/collector.h"
41
#include "src/debug/debug.h"
42
#include "src/objects-inl.h"
43 44 45
#include "src/profiler/allocation-tracker.h"
#include "src/profiler/heap-profiler.h"
#include "src/profiler/heap-snapshot-generator-inl.h"
46
#include "test/cctest/cctest.h"
47

48 49 50
using i::AllocationTraceNode;
using i::AllocationTraceTree;
using i::AllocationTracker;
51
using i::ArrayVector;
52
using i::SourceLocation;
53
using i::Vector;
54
using v8::base::Optional;
55

56 57 58 59 60
namespace {

class NamedEntriesDetector {
 public:
  NamedEntriesDetector()
61
      : has_A2(false), has_B2(false), has_C2(false) {
62 63
  }

64 65 66 67
  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;
68 69
  }

70
  void CheckAllReachables(i::HeapEntry* root) {
71
    v8::base::HashMap visited;
72 73
    std::vector<i::HeapEntry*> list;
    list.push_back(root);
74
    CheckEntry(root);
75 76 77
    while (!list.empty()) {
      i::HeapEntry* entry = list.back();
      list.pop_back();
78 79 80 81
      for (int i = 0; i < entry->children_count(); ++i) {
        i::HeapGraphEdge* edge = entry->child(i);
        if (edge->type() == i::HeapGraphEdge::kShortcut) continue;
        i::HeapEntry* child = edge->to();
lpy's avatar
lpy committed
82
        v8::base::HashMap::Entry* entry = visited.LookupOrInsert(
83
            reinterpret_cast<void*>(child),
84
            static_cast<uint32_t>(reinterpret_cast<uintptr_t>(child)));
85 86 87
        if (entry->value)
          continue;
        entry->value = reinterpret_cast<void*>(1);
88
        list.push_back(child);
89
        CheckEntry(child);
90 91
      }
    }
92 93 94 95 96 97 98 99 100
  }

  bool has_A2;
  bool has_B2;
  bool has_C2;
};

}  // namespace

101 102 103

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

112 113 114 115 116
static const char* GetName(const v8::HeapGraphNode* node) {
  return const_cast<i::HeapEntry*>(reinterpret_cast<const i::HeapEntry*>(node))
      ->name();
}

117 118 119 120 121 122
static const char* GetName(const v8::HeapGraphEdge* edge) {
  return const_cast<i::HeapGraphEdge*>(
             reinterpret_cast<const i::HeapGraphEdge*>(edge))
      ->name();
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
static size_t GetSize(const v8::HeapGraphNode* node) {
  return const_cast<i::HeapEntry*>(reinterpret_cast<const i::HeapEntry*>(node))
      ->self_size();
}

static const v8::HeapGraphNode* GetChildByName(const v8::HeapGraphNode* node,
                                               const char* name) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphNode* child = node->GetChild(i)->GetToNode();
    if (!strcmp(name, GetName(child))) {
      return child;
    }
  }
  return nullptr;
}

139 140 141 142 143 144 145 146 147 148 149 150
static const v8::HeapGraphEdge* GetEdgeByChildName(
    const v8::HeapGraphNode* node, const char* name) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* edge = node->GetChild(i);
    const v8::HeapGraphNode* child = edge->GetToNode();
    if (!strcmp(name, GetName(child))) {
      return edge;
    }
  }
  return nullptr;
}

151 152 153 154 155
static const v8::HeapGraphNode* GetRootChild(const v8::HeapSnapshot* snapshot,
                                             const char* name) {
  return GetChildByName(snapshot->GetRoot(), name);
}

156 157 158 159
static Optional<SourceLocation> GetLocation(const v8::HeapSnapshot* s,
                                            const v8::HeapGraphNode* node) {
  const i::HeapSnapshot* snapshot = reinterpret_cast<const i::HeapSnapshot*>(s);
  const std::vector<SourceLocation>& locations = snapshot->locations();
160
  const i::HeapEntry* entry = reinterpret_cast<const i::HeapEntry*>(node);
161
  for (const auto& loc : locations) {
162
    if (loc.entry_index == entry->index()) {
163 164 165 166 167 168 169
      return Optional<SourceLocation>(loc);
    }
  }

  return Optional<SourceLocation>();
}

170 171
static const v8::HeapGraphNode* GetProperty(v8::Isolate* isolate,
                                            const v8::HeapGraphNode* node,
172 173 174 175
                                            v8::HeapGraphEdge::Type type,
                                            const char* name) {
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = node->GetChild(i);
176
    v8::String::Utf8Value prop_name(isolate, prop->GetName());
177 178 179
    if (prop->GetType() == type && strcmp(name, *prop_name) == 0)
      return prop->GetToNode();
  }
180
  return nullptr;
181 182
}

183 184
static bool HasString(v8::Isolate* isolate, const v8::HeapGraphNode* node,
                      const char* contents) {
185 186 187
  for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = node->GetChild(i);
    const v8::HeapGraphNode* node = prop->GetToNode();
188
    if (node->GetType() == v8::HeapGraphNode::kString) {
189
      v8::String::Utf8Value node_name(isolate, node->GetName());
190 191 192 193 194 195
      if (strcmp(contents, *node_name) == 0) return true;
    }
  }
  return false;
}

196 197
static void EnsureNoUninstrumentedInternals(v8::Isolate* isolate,
                                            const v8::HeapGraphNode* node) {
198 199
  for (int i = 0; i < 20; ++i) {
    i::ScopedVector<char> buffer(10);
200 201 202
    const v8::HeapGraphNode* internal =
        GetProperty(isolate, node, v8::HeapGraphEdge::kInternal,
                    i::IntToCString(i, buffer));
203 204 205
    CHECK(!internal);
  }
}
206

207
// Check that snapshot has no unretained entries except root.
208
static bool ValidateSnapshot(const v8::HeapSnapshot* snapshot, int depth = 3) {
209 210 211
  i::HeapSnapshot* heap_snapshot = const_cast<i::HeapSnapshot*>(
      reinterpret_cast<const i::HeapSnapshot*>(snapshot));

212
  v8::base::HashMap visited;
213 214
  std::deque<i::HeapGraphEdge>& edges = heap_snapshot->edges();
  for (size_t i = 0; i < edges.size(); ++i) {
lpy's avatar
lpy committed
215
    v8::base::HashMap::Entry* entry = visited.LookupOrInsert(
216
        reinterpret_cast<void*>(edges[i].to()),
217
        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(edges[i].to())));
218 219 220 221 222
    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;
223
  std::deque<i::HeapEntry>& entries = heap_snapshot->entries();
224 225 226 227 228 229 230
  for (i::HeapEntry& entry : entries) {
    v8::base::HashMap::Entry* map_entry = visited.Lookup(
        reinterpret_cast<void*>(&entry),
        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(&entry)));
    if (!map_entry && entry.id() != 1) {
      entry.Print("entry with no retainer", "", depth, 0);
      ++unretained_entries_count;
231 232
    }
  }
233
  return unretained_entries_count == 0;
234 235
}

236 237 238 239 240
bool EndsWith(const char* a, const char* b) {
  size_t length_a = strlen(a);
  size_t length_b = strlen(b);
  return (length_a >= length_b) && !strcmp(a + length_a - length_b, b);
}
241

242
TEST(HeapSnapshot) {
243
  LocalContext env2;
244
  v8::HandleScope scope(env2->GetIsolate());
245
  v8::HeapProfiler* heap_profiler = env2->GetIsolate()->GetHeapProfiler();
246

247
  CompileRun(
248 249 250 251 252 253
      "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);");
254
  const v8::HeapSnapshot* snapshot_env2 = heap_profiler->TakeHeapSnapshot();
255
  CHECK(ValidateSnapshot(snapshot_env2));
256
  const v8::HeapGraphNode* global_env2 = GetGlobalObject(snapshot_env2);
257

258
  // Verify, that JS global object of env2 has '..2' properties.
259 260
  const v8::HeapGraphNode* a2_node = GetProperty(
      env2->GetIsolate(), global_env2, v8::HeapGraphEdge::kProperty, "a2");
261
  CHECK(a2_node);
262 263 264 265 266 267
  CHECK(GetProperty(env2->GetIsolate(), global_env2,
                    v8::HeapGraphEdge::kProperty, "b2_1"));
  CHECK(GetProperty(env2->GetIsolate(), global_env2,
                    v8::HeapGraphEdge::kProperty, "b2_2"));
  CHECK(GetProperty(env2->GetIsolate(), global_env2,
                    v8::HeapGraphEdge::kProperty, "c2"));
268 269

  NamedEntriesDetector det;
270 271
  det.CheckAllReachables(const_cast<i::HeapEntry*>(
      reinterpret_cast<const i::HeapEntry*>(global_env2)));
272 273 274 275 276
  CHECK(det.has_A2);
  CHECK(det.has_B2);
  CHECK(det.has_C2);
}

277 278 279 280 281 282 283
TEST(HeapSnapshotLocations) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun(
      "function X(a) { return function() { return a; } }\n"
284
      "function* getid() { yield 1; }\n"
285
      "class A {}\n"
286
      "var x = X(1);\n"
287 288
      "var g = getid();\n"
      "var o = new A();");
289 290 291 292 293 294 295 296
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* x =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "x");
  CHECK(x);

297 298 299 300 301 302 303 304 305 306 307 308 309
  Optional<SourceLocation> x_loc = GetLocation(snapshot, x);
  CHECK(x_loc);
  CHECK_EQ(0, x_loc->line);
  CHECK_EQ(31, x_loc->col);

  const v8::HeapGraphNode* g =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "g");
  CHECK(x);

  Optional<SourceLocation> g_loc = GetLocation(snapshot, g);
  CHECK(g_loc);
  CHECK_EQ(1, g_loc->line);
  CHECK_EQ(15, g_loc->col);
310 311 312 313 314 315 316 317 318

  const v8::HeapGraphNode* o =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "o");
  CHECK(x);

  Optional<SourceLocation> o_loc = GetLocation(snapshot, o);
  CHECK(o_loc);
  CHECK_EQ(2, o_loc->line);
  CHECK_EQ(0, o_loc->col);
319
}
320

321 322
TEST(HeapSnapshotObjectSizes) {
  LocalContext env;
323
  v8::HandleScope scope(env->GetIsolate());
324
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
325 326 327

  //   -a-> X1 --a
  // x -b-> X2 <-|
328
  CompileRun(
329 330
      "function X(a, b) { this.a = a; this.b = b; }\n"
      "x = new X(new X(), new X());\n"
331
      "dummy = new X();\n"
332
      "(function() { x.a.a = x.b; })();");
333
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
334
  CHECK(ValidateSnapshot(snapshot));
335 336
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* x =
337
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "x");
338
  CHECK(x);
339
  const v8::HeapGraphNode* x1 =
340
      GetProperty(env->GetIsolate(), x, v8::HeapGraphEdge::kProperty, "a");
341
  CHECK(x1);
342
  const v8::HeapGraphNode* x2 =
343
      GetProperty(env->GetIsolate(), x, v8::HeapGraphEdge::kProperty, "b");
344
  CHECK(x2);
345

346
  // Test sizes.
347 348 349
  CHECK_NE(0, static_cast<int>(x->GetShallowSize()));
  CHECK_NE(0, static_cast<int>(x1->GetShallowSize()));
  CHECK_NE(0, static_cast<int>(x2->GetShallowSize()));
350 351 352
}


353 354
TEST(BoundFunctionInSnapshot) {
  LocalContext env;
355
  v8::HandleScope scope(env->GetIsolate());
356
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
357 358 359 360
  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");
361
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
362
  CHECK(ValidateSnapshot(snapshot));
363
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
364 365
  const v8::HeapGraphNode* f = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "boundFunction");
366
  CHECK(f);
367
  CHECK(v8_str("native_bind")->Equals(env.local(), f->GetName()).FromJust());
368 369
  const v8::HeapGraphNode* bindings = GetProperty(
      env->GetIsolate(), f, v8::HeapGraphEdge::kInternal, "bindings");
370
  CHECK(bindings);
371
  CHECK_EQ(v8::HeapGraphNode::kArray, bindings->GetType());
372
  CHECK_EQ(1, bindings->GetChildrenCount());
373

374 375
  const v8::HeapGraphNode* bound_this = GetProperty(
      env->GetIsolate(), f, v8::HeapGraphEdge::kInternal, "bound_this");
376 377 378
  CHECK(bound_this);
  CHECK_EQ(v8::HeapGraphNode::kObject, bound_this->GetType());

379 380
  const v8::HeapGraphNode* bound_function = GetProperty(
      env->GetIsolate(), f, v8::HeapGraphEdge::kInternal, "bound_function");
381 382 383 384
  CHECK(bound_function);
  CHECK_EQ(v8::HeapGraphNode::kClosure, bound_function->GetType());

  const v8::HeapGraphNode* bound_argument = GetProperty(
385
      env->GetIsolate(), f, v8::HeapGraphEdge::kShortcut, "bound_argument_1");
386 387 388 389 390
  CHECK(bound_argument);
  CHECK_EQ(v8::HeapGraphNode::kObject, bound_argument->GetType());
}


391 392
TEST(HeapSnapshotEntryChildren) {
  LocalContext env;
393
  v8::HandleScope scope(env->GetIsolate());
394
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
395

396
  CompileRun(
397 398
      "function A() { }\n"
      "a = new A;");
399
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
400
  CHECK(ValidateSnapshot(snapshot));
401 402 403 404 405 406
  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 =
407
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "a");
408
  CHECK(a);
409 410 411 412 413 414 415
  for (int i = 0, count = a->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = a->GetChild(i);
    CHECK_EQ(a, prop->GetFromNode());
  }
}


416
TEST(HeapSnapshotCodeObjects) {
417
  LocalContext env;
418
  v8::HandleScope scope(env->GetIsolate());
419
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
420

421
  CompileRun(
422
      "function lazy(x) { return x - 1; }\n"
423
      "function compiled(x) { ()=>x; return x + 1; }\n"
424
      "var anonymous = (function() { return function() { return 0; } })();\n"
425
      "compiled(1)");
426
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
427
  CHECK(ValidateSnapshot(snapshot));
428 429

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
430 431
  const v8::HeapGraphNode* compiled = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "compiled");
432
  CHECK(compiled);
433
  CHECK_EQ(v8::HeapGraphNode::kClosure, compiled->GetType());
434 435
  const v8::HeapGraphNode* lazy = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "lazy");
436
  CHECK(lazy);
437
  CHECK_EQ(v8::HeapGraphNode::kClosure, lazy->GetType());
438 439
  const v8::HeapGraphNode* anonymous = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "anonymous");
440
  CHECK(anonymous);
441
  CHECK_EQ(v8::HeapGraphNode::kClosure, anonymous->GetType());
442
  v8::String::Utf8Value anonymous_name(env->GetIsolate(), anonymous->GetName());
443
  CHECK_EQ(0, strcmp("", *anonymous_name));
444

445 446
  // Find references to shared function info.
  const v8::HeapGraphNode* compiled_sfi = GetProperty(
447
      env->GetIsolate(), compiled, v8::HeapGraphEdge::kInternal, "shared");
448 449
  CHECK(compiled_sfi);
  const v8::HeapGraphNode* lazy_sfi = GetProperty(
450
      env->GetIsolate(), lazy, v8::HeapGraphEdge::kInternal, "shared");
451 452 453 454 455 456 457 458
  CHECK(lazy_sfi);

  // TODO(leszeks): Check that there's bytecode on the compiled function, but
  // not the lazy function.

  // Verify that non-compiled function doesn't contain references to "x"
  // literal, while compiled function does. The scope info is stored in
  // FixedArray objects attached to the SharedFunctionInfo.
459
  bool compiled_references_x = false, lazy_references_x = false;
460 461
  for (int i = 0, count = compiled_sfi->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = compiled_sfi->GetChild(i);
462
    const v8::HeapGraphNode* node = prop->GetToNode();
463
    if (node->GetType() == v8::HeapGraphNode::kArray) {
464
      if (HasString(env->GetIsolate(), node, "x")) {
465 466 467 468 469
        compiled_references_x = true;
        break;
      }
    }
  }
470 471
  for (int i = 0, count = lazy_sfi->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = lazy_sfi->GetChild(i);
472
    const v8::HeapGraphNode* node = prop->GetToNode();
473
    if (node->GetType() == v8::HeapGraphNode::kArray) {
474
      if (HasString(env->GetIsolate(), node, "x")) {
475 476 477 478 479 480
        lazy_references_x = true;
        break;
      }
    }
  }
  CHECK(compiled_references_x);
481
  if (i::FLAG_lazy) {
482 483
    CHECK(!lazy_references_x);
  }
484 485
}

486

487 488
TEST(HeapSnapshotHeapNumbers) {
  LocalContext env;
489
  v8::HandleScope scope(env->GetIsolate());
490
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
491 492 493
  CompileRun(
      "a = 1;    // a is Smi\n"
      "b = 2.5;  // b is HeapNumber");
494
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
495
  CHECK(ValidateSnapshot(snapshot));
496
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
497 498
  CHECK(!GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty,
                     "a"));
499
  const v8::HeapGraphNode* b =
500
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "b");
501
  CHECK(b);
502 503 504
  CHECK_EQ(v8::HeapGraphNode::kHeapNumber, b->GetType());
}

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
TEST(HeapSnapshotHeapBigInts) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun(
      "a = 1n;"
      "b = Object(BigInt(2))");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* a =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "a");
  CHECK(a);
  CHECK_EQ(v8::HeapGraphNode::kBigInt, a->GetType());
  const v8::HeapGraphNode* b =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "b");
  CHECK(b);
  CHECK_EQ(v8::HeapGraphNode::kObject, b->GetType());
}
524

525
TEST(HeapSnapshotSlicedString) {
526
  if (!i::FLAG_string_slices) return;
527
  LocalContext env;
528
  v8::HandleScope scope(env->GetIsolate());
529
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
530 531 532 533
  CompileRun(
      "parent_string = \"123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
534 535 536 537
      "123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
      "123456789.123456789.123456789.123456789.123456789."
538
      "123456789.123456789.123456789.123456789.123456789.\";"
539
      "child_string = parent_string.slice(100);");
540
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
541
  CHECK(ValidateSnapshot(snapshot));
542
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
543 544
  const v8::HeapGraphNode* parent_string = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "parent_string");
545
  CHECK(parent_string);
546 547
  const v8::HeapGraphNode* child_string = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "child_string");
548
  CHECK(child_string);
549
  CHECK_EQ(v8::HeapGraphNode::kSlicedString, child_string->GetType());
550 551
  const v8::HeapGraphNode* parent = GetProperty(
      env->GetIsolate(), child_string, v8::HeapGraphEdge::kInternal, "parent");
552
  CHECK_EQ(parent_string, parent);
553
  heap_profiler->DeleteAllHeapSnapshots();
554
}
555

556

557
TEST(HeapSnapshotConsString) {
558
  v8::Isolate* isolate = CcTest::isolate();
559
  v8::HandleScope scope(isolate);
560 561
  v8::Local<v8::ObjectTemplate> global_template =
      v8::ObjectTemplate::New(isolate);
562
  global_template->SetInternalFieldCount(1);
563
  LocalContext env(nullptr, global_template);
564 565
  v8::Local<v8::Object> global_proxy = env->Global();
  v8::Local<v8::Object> global = global_proxy->GetPrototype().As<v8::Object>();
566 567
  CHECK_EQ(1, global->InternalFieldCount());

568
  i::Factory* factory = CcTest::i_isolate()->factory();
569 570
  i::Handle<i::String> first = factory->NewStringFromStaticChars("0123456789");
  i::Handle<i::String> second = factory->NewStringFromStaticChars("0123456789");
571 572
  i::Handle<i::String> cons_string =
      factory->NewConsString(first, second).ToHandleChecked();
573 574 575 576

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

  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
577
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
578 579 580 581
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global_node = GetGlobalObject(snapshot);

  const v8::HeapGraphNode* string_node =
582
      GetProperty(isolate, global_node, v8::HeapGraphEdge::kInternal, "0");
583
  CHECK(string_node);
584 585 586
  CHECK_EQ(v8::HeapGraphNode::kConsString, string_node->GetType());

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

  const v8::HeapGraphNode* second_node =
591
      GetProperty(isolate, string_node, v8::HeapGraphEdge::kInternal, "second");
592 593 594 595 596 597
  CHECK_EQ(v8::HeapGraphNode::kString, second_node->GetType());

  heap_profiler->DeleteAllHeapSnapshots();
}


598 599 600 601 602 603
TEST(HeapSnapshotSymbol) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun("a = Symbol('mySymbol');\n");
604
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
605 606 607
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* a =
608
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "a");
609
  CHECK(a);
610
  CHECK_EQ(a->GetType(), v8::HeapGraphNode::kSymbol);
611
  CHECK(v8_str("symbol")->Equals(env.local(), a->GetName()).FromJust());
612
  const v8::HeapGraphNode* name =
613
      GetProperty(env->GetIsolate(), a, v8::HeapGraphEdge::kInternal, "name");
614
  CHECK(name);
615
  CHECK(v8_str("mySymbol")->Equals(env.local(), name->GetName()).FromJust());
616 617
}

618 619 620 621 622
TEST(HeapSnapshotWeakCollection) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

623 624 625 626
  CompileRun(
      "k = {}; v = {}; s = 'str';\n"
      "ws = new WeakSet(); ws.add(k); ws.add(v); ws[s] = s;\n"
      "wm = new WeakMap(); wm.set(k, v); wm[s] = s;\n");
627
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
628 629 630
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* k =
631
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "k");
632
  CHECK(k);
633
  const v8::HeapGraphNode* v =
634
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "v");
635
  CHECK(v);
636
  const v8::HeapGraphNode* s =
637
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "s");
638
  CHECK(s);
639

640 641
  const v8::HeapGraphNode* ws = GetProperty(env->GetIsolate(), global,
                                            v8::HeapGraphEdge::kProperty, "ws");
642
  CHECK(ws);
643
  CHECK_EQ(v8::HeapGraphNode::kObject, ws->GetType());
644
  CHECK(v8_str("WeakSet")->Equals(env.local(), ws->GetName()).FromJust());
645 646

  const v8::HeapGraphNode* ws_table =
647
      GetProperty(env->GetIsolate(), ws, v8::HeapGraphEdge::kInternal, "table");
648 649 650 651 652 653 654 655 656 657 658
  CHECK_EQ(v8::HeapGraphNode::kArray, ws_table->GetType());
  CHECK_GT(ws_table->GetChildrenCount(), 0);
  int weak_entries = 0;
  for (int i = 0, count = ws_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = ws_table->GetChild(i);
    if (prop->GetType() != v8::HeapGraphEdge::kWeak) continue;
    if (k->GetId() == prop->GetToNode()->GetId()) {
      ++weak_entries;
    }
  }
  CHECK_EQ(1, weak_entries);
659
  const v8::HeapGraphNode* ws_s =
660
      GetProperty(env->GetIsolate(), ws, v8::HeapGraphEdge::kProperty, "str");
661 662
  CHECK(ws_s);
  CHECK_EQ(s->GetId(), ws_s->GetId());
663

664 665
  const v8::HeapGraphNode* wm = GetProperty(env->GetIsolate(), global,
                                            v8::HeapGraphEdge::kProperty, "wm");
666
  CHECK(wm);
667
  CHECK_EQ(v8::HeapGraphNode::kObject, wm->GetType());
668
  CHECK(v8_str("WeakMap")->Equals(env.local(), wm->GetName()).FromJust());
669 670

  const v8::HeapGraphNode* wm_table =
671
      GetProperty(env->GetIsolate(), wm, v8::HeapGraphEdge::kInternal, "table");
672 673 674 675 676 677 678 679 680 681 682
  CHECK_EQ(v8::HeapGraphNode::kArray, wm_table->GetType());
  CHECK_GT(wm_table->GetChildrenCount(), 0);
  weak_entries = 0;
  for (int i = 0, count = wm_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = wm_table->GetChild(i);
    if (prop->GetType() != v8::HeapGraphEdge::kWeak) continue;
    const v8::SnapshotObjectId to_node_id = prop->GetToNode()->GetId();
    if (to_node_id == k->GetId() || to_node_id == v->GetId()) {
      ++weak_entries;
    }
  }
683
  CHECK_EQ(2, weak_entries);  // Key and value are weak.
684
  const v8::HeapGraphNode* wm_s =
685
      GetProperty(env->GetIsolate(), wm, v8::HeapGraphEdge::kProperty, "str");
686 687
  CHECK(wm_s);
  CHECK_EQ(s->GetId(), wm_s->GetId());
688 689 690 691 692 693 694 695 696 697 698 699
}


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

  CompileRun(
      "k = {}; v = {}; s = 'str';\n"
      "set = new Set(); set.add(k); set.add(v); set[s] = s;\n"
      "map = new Map(); map.set(k, v); map[s] = s;\n");
700
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
701 702 703
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* k =
704
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "k");
705
  CHECK(k);
706
  const v8::HeapGraphNode* v =
707
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "v");
708
  CHECK(v);
709
  const v8::HeapGraphNode* s =
710
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "s");
711
  CHECK(s);
712

713 714
  const v8::HeapGraphNode* set = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "set");
715
  CHECK(set);
716
  CHECK_EQ(v8::HeapGraphNode::kObject, set->GetType());
717
  CHECK(v8_str("Set")->Equals(env.local(), set->GetName()).FromJust());
718

719 720
  const v8::HeapGraphNode* set_table = GetProperty(
      env->GetIsolate(), set, v8::HeapGraphEdge::kInternal, "table");
721 722 723 724 725 726 727 728 729 730 731 732
  CHECK_EQ(v8::HeapGraphNode::kArray, set_table->GetType());
  CHECK_GT(set_table->GetChildrenCount(), 0);
  int entries = 0;
  for (int i = 0, count = set_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = set_table->GetChild(i);
    const v8::SnapshotObjectId to_node_id = prop->GetToNode()->GetId();
    if (to_node_id == k->GetId() || to_node_id == v->GetId()) {
      ++entries;
    }
  }
  CHECK_EQ(2, entries);
  const v8::HeapGraphNode* set_s =
733
      GetProperty(env->GetIsolate(), set, v8::HeapGraphEdge::kProperty, "str");
734 735
  CHECK(set_s);
  CHECK_EQ(s->GetId(), set_s->GetId());
736

737 738
  const v8::HeapGraphNode* map = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "map");
739
  CHECK(map);
740
  CHECK_EQ(v8::HeapGraphNode::kObject, map->GetType());
741
  CHECK(v8_str("Map")->Equals(env.local(), map->GetName()).FromJust());
742

743 744
  const v8::HeapGraphNode* map_table = GetProperty(
      env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "table");
745 746 747 748 749 750 751 752 753 754 755 756
  CHECK_EQ(v8::HeapGraphNode::kArray, map_table->GetType());
  CHECK_GT(map_table->GetChildrenCount(), 0);
  entries = 0;
  for (int i = 0, count = map_table->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* prop = map_table->GetChild(i);
    const v8::SnapshotObjectId to_node_id = prop->GetToNode()->GetId();
    if (to_node_id == k->GetId() || to_node_id == v->GetId()) {
      ++entries;
    }
  }
  CHECK_EQ(2, entries);
  const v8::HeapGraphNode* map_s =
757
      GetProperty(env->GetIsolate(), map, v8::HeapGraphEdge::kProperty, "str");
758 759
  CHECK(map_s);
  CHECK_EQ(s->GetId(), map_s->GetId());
760 761
}

762 763 764 765 766 767
TEST(HeapSnapshotMap) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun(
768
      "function Z() { this.foo = {}; this.bar = 0; }\n"
769 770 771 772 773
      "z = new Z();\n");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* z =
774
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "z");
775 776
  CHECK(z);
  const v8::HeapGraphNode* map =
777
      GetProperty(env->GetIsolate(), z, v8::HeapGraphEdge::kInternal, "map");
778
  CHECK(map);
779 780 781 782
  CHECK(
      GetProperty(env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "map"));
  CHECK(GetProperty(env->GetIsolate(), map, v8::HeapGraphEdge::kInternal,
                    "prototype"));
783 784 785 786
  const v8::HeapGraphNode* parent_map = GetProperty(
      env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "back_pointer");
  CHECK(parent_map);

787 788 789 790
  CHECK(GetProperty(env->GetIsolate(), map, v8::HeapGraphEdge::kInternal,
                    "back_pointer"));
  CHECK(GetProperty(env->GetIsolate(), map, v8::HeapGraphEdge::kInternal,
                    "descriptors"));
791 792
  CHECK(GetProperty(env->GetIsolate(), parent_map, v8::HeapGraphEdge::kWeak,
                    "transition"));
793
}
794

795
TEST(HeapSnapshotInternalReferences) {
796
  v8::Isolate* isolate = CcTest::isolate();
797
  v8::HandleScope scope(isolate);
798 799
  v8::Local<v8::ObjectTemplate> global_template =
      v8::ObjectTemplate::New(isolate);
800
  global_template->SetInternalFieldCount(2);
801
  LocalContext env(nullptr, global_template);
802 803
  v8::Local<v8::Object> global_proxy = env->Global();
  v8::Local<v8::Object> global = global_proxy->GetPrototype().As<v8::Object>();
804
  CHECK_EQ(2, global->InternalFieldCount());
805
  v8::Local<v8::Object> obj = v8::Object::New(isolate);
806 807
  global->SetInternalField(0, v8_num(17));
  global->SetInternalField(1, obj);
808
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
809
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
810
  CHECK(ValidateSnapshot(snapshot));
811 812
  const v8::HeapGraphNode* global_node = GetGlobalObject(snapshot);
  // The first reference will not present, because it's a Smi.
813 814
  CHECK(!GetProperty(env->GetIsolate(), global_node,
                     v8::HeapGraphEdge::kInternal, "0"));
815
  // The second reference is to an object.
816 817
  CHECK(GetProperty(env->GetIsolate(), global_node,
                    v8::HeapGraphEdge::kInternal, "1"));
818 819
}

820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
TEST(HeapSnapshotEphemeron) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun(
      "class KeyClass{};\n"
      "class ValueClass{};\n"
      "var wm = new WeakMap();\n"
      "function foo(key) { wm.set(key, new ValueClass()); }\n"
      "var key = new KeyClass();\n"
      "foo(key);");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);

  const v8::HeapGraphNode* key = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "key");
  CHECK(key);
  bool success = false;
  for (int i = 0, count = key->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* edge = key->GetChild(i);
    const v8::HeapGraphNode* child = edge->GetToNode();
    if (!strcmp("ValueClass", GetName(child))) {
      v8::String::Utf8Value edge_name(CcTest::isolate(), edge->GetName());
845
      CHECK(EndsWith(*edge_name, " / key KeyClass in WeakMap"));
846 847 848 849 850 851
      success = true;
      break;
    }
  }
  CHECK(success);
}
852

853 854
TEST(HeapSnapshotAddressReuse) {
  LocalContext env;
855
  v8::HandleScope scope(env->GetIsolate());
856
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
857 858 859 860 861 862

  CompileRun(
      "function A() {}\n"
      "var a = [];\n"
      "for (var i = 0; i < 10000; ++i)\n"
      "  a[i] = new A();\n");
863
  const v8::HeapSnapshot* snapshot1 = heap_profiler->TakeHeapSnapshot();
864
  CHECK(ValidateSnapshot(snapshot1));
865 866 867 868 869
  v8::SnapshotObjectId maxId1 = snapshot1->GetMaxSnapshotJSObjectId();

  CompileRun(
      "for (var i = 0; i < 10000; ++i)\n"
      "  a[i] = new A();\n");
870
  CcTest::CollectAllGarbage();
871

872
  const v8::HeapSnapshot* snapshot2 = heap_profiler->TakeHeapSnapshot();
873
  CHECK(ValidateSnapshot(snapshot2));
874 875
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);

876 877
  const v8::HeapGraphNode* array_node = GetProperty(
      env->GetIsolate(), global2, v8::HeapGraphEdge::kProperty, "a");
878
  CHECK(array_node);
879 880 881 882 883 884 885 886 887
  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;
  }
888
  CHECK_EQ(0, wrong_count);
889 890 891
}


892 893
TEST(HeapEntryIdsAndArrayShift) {
  LocalContext env;
894
  v8::HandleScope scope(env->GetIsolate());
895
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
896 897 898 899 900 901 902 903 904

  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");
905
  const v8::HeapSnapshot* snapshot1 = heap_profiler->TakeHeapSnapshot();
906
  CHECK(ValidateSnapshot(snapshot1));
907 908 909 910 911

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

912
  CcTest::CollectAllGarbage();
913

914
  const v8::HeapSnapshot* snapshot2 = heap_profiler->TakeHeapSnapshot();
915
  CHECK(ValidateSnapshot(snapshot2));
916 917 918

  const v8::HeapGraphNode* global1 = GetGlobalObject(snapshot1);
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);
919 920
  CHECK_NE(0u, global1->GetId());
  CHECK_EQ(global1->GetId(), global2->GetId());
921

922 923
  const v8::HeapGraphNode* a1 = GetProperty(env->GetIsolate(), global1,
                                            v8::HeapGraphEdge::kProperty, "a");
924
  CHECK(a1);
925 926
  const v8::HeapGraphNode* k1 = GetProperty(
      env->GetIsolate(), a1, v8::HeapGraphEdge::kInternal, "elements");
927
  CHECK(k1);
928 929
  const v8::HeapGraphNode* a2 = GetProperty(env->GetIsolate(), global2,
                                            v8::HeapGraphEdge::kProperty, "a");
930
  CHECK(a2);
931 932
  const v8::HeapGraphNode* k2 = GetProperty(
      env->GetIsolate(), a2, v8::HeapGraphEdge::kInternal, "elements");
933
  CHECK(k2);
934

935 936
  CHECK_EQ(a1->GetId(), a2->GetId());
  CHECK_EQ(k1->GetId(), k2->GetId());
937 938
}

939

940 941
TEST(HeapEntryIdsAndGC) {
  LocalContext env;
942
  v8::HandleScope scope(env->GetIsolate());
943
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
944

945
  CompileRun(
946 947 948 949
      "function A() {}\n"
      "function B(x) { this.x = x; }\n"
      "var a = new A();\n"
      "var b = new B(a);");
950
  const v8::HeapSnapshot* snapshot1 = heap_profiler->TakeHeapSnapshot();
951
  CHECK(ValidateSnapshot(snapshot1));
952

953
  CcTest::CollectAllGarbage();
954

955
  const v8::HeapSnapshot* snapshot2 = heap_profiler->TakeHeapSnapshot();
956
  CHECK(ValidateSnapshot(snapshot2));
957

958
  CHECK_GT(snapshot1->GetMaxSnapshotJSObjectId(), 7000u);
959 960
  CHECK(snapshot1->GetMaxSnapshotJSObjectId() <=
        snapshot2->GetMaxSnapshotJSObjectId());
961 962 963

  const v8::HeapGraphNode* global1 = GetGlobalObject(snapshot1);
  const v8::HeapGraphNode* global2 = GetGlobalObject(snapshot2);
964 965
  CHECK_NE(0u, global1->GetId());
  CHECK_EQ(global1->GetId(), global2->GetId());
966 967
  const v8::HeapGraphNode* A1 = GetProperty(env->GetIsolate(), global1,
                                            v8::HeapGraphEdge::kProperty, "A");
968
  CHECK(A1);
969 970
  const v8::HeapGraphNode* A2 = GetProperty(env->GetIsolate(), global2,
                                            v8::HeapGraphEdge::kProperty, "A");
971 972 973
  CHECK(A2);
  CHECK_NE(0u, A1->GetId());
  CHECK_EQ(A1->GetId(), A2->GetId());
974 975
  const v8::HeapGraphNode* B1 = GetProperty(env->GetIsolate(), global1,
                                            v8::HeapGraphEdge::kProperty, "B");
976
  CHECK(B1);
977 978
  const v8::HeapGraphNode* B2 = GetProperty(env->GetIsolate(), global2,
                                            v8::HeapGraphEdge::kProperty, "B");
979 980 981
  CHECK(B2);
  CHECK_NE(0u, B1->GetId());
  CHECK_EQ(B1->GetId(), B2->GetId());
982 983
  const v8::HeapGraphNode* a1 = GetProperty(env->GetIsolate(), global1,
                                            v8::HeapGraphEdge::kProperty, "a");
984
  CHECK(a1);
985 986
  const v8::HeapGraphNode* a2 = GetProperty(env->GetIsolate(), global2,
                                            v8::HeapGraphEdge::kProperty, "a");
987 988 989
  CHECK(a2);
  CHECK_NE(0u, a1->GetId());
  CHECK_EQ(a1->GetId(), a2->GetId());
990 991
  const v8::HeapGraphNode* b1 = GetProperty(env->GetIsolate(), global1,
                                            v8::HeapGraphEdge::kProperty, "b");
992
  CHECK(b1);
993 994
  const v8::HeapGraphNode* b2 = GetProperty(env->GetIsolate(), global2,
                                            v8::HeapGraphEdge::kProperty, "b");
995 996 997
  CHECK(b2);
  CHECK_NE(0u, b1->GetId());
  CHECK_EQ(b1->GetId(), b2->GetId());
998 999
}

1000 1001 1002 1003
namespace {

class TestJSONStream : public v8::OutputStream {
 public:
1004 1005 1006
  TestJSONStream() : eos_signaled_(0), abort_countdown_(-1) {}
  explicit TestJSONStream(int abort_countdown)
      : eos_signaled_(0), abort_countdown_(abort_countdown) {}
1007 1008 1009
  ~TestJSONStream() override = default;
  void EndOfStream() override { ++eos_signaled_; }
  WriteResult WriteAsciiChunk(char* buffer, int chars_written) override {
1010 1011
    if (abort_countdown_ > 0) --abort_countdown_;
    if (abort_countdown_ == 0) return kAbort;
1012 1013
    CHECK_GT(chars_written, 0);
    i::Vector<char> chunk = buffer_.AddBlock(chars_written, '\0');
1014
    i::MemCopy(chunk.start(), buffer, chars_written);
1015
    return kContinue;
1016
  }
1017
  virtual WriteResult WriteUint32Chunk(uint32_t* buffer, int chars_written) {
1018
    UNREACHABLE();
1019
  }
1020 1021 1022
  void WriteTo(i::Vector<char> dest) { buffer_.WriteTo(dest); }
  int eos_signaled() { return eos_signaled_; }
  int size() { return buffer_.size(); }
1023

1024 1025 1026
 private:
  i::Collector<char> buffer_;
  int eos_signaled_;
1027
  int abort_countdown_;
1028 1029
};

1030
class OneByteResource : public v8::String::ExternalOneByteStringResource {
1031
 public:
1032
  explicit OneByteResource(i::Vector<char> string) : data_(string.start()) {
1033 1034
    length_ = string.length();
  }
1035 1036 1037
  const char* data() const override { return data_; }
  size_t length() const override { return length_; }

1038 1039 1040 1041 1042 1043 1044 1045
 private:
  const char* data_;
  size_t length_;
};

}  // namespace

TEST(HeapSnapshotJSONSerialization) {
1046
  v8::Isolate* isolate = CcTest::isolate();
1047
  LocalContext env;
1048 1049
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
1050 1051 1052

#define STRING_LITERAL_FOR_TEST \
  "\"String \\n\\r\\u0008\\u0081\\u0101\\u0801\\u8001\""
1053
  CompileRun(
1054 1055 1056 1057
      "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);");
1058
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1059
  CHECK(ValidateSnapshot(snapshot));
1060

1061 1062 1063 1064 1065 1066 1067 1068
  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.
1069
  OneByteResource* json_res = new OneByteResource(json);
1070
  v8::Local<v8::String> json_string =
1071 1072 1073 1074 1075
      v8::String::NewExternalOneByte(env->GetIsolate(), json_res)
          .ToLocalChecked();
  env->Global()
      ->Set(env.local(), v8_str("json_snapshot"), json_string)
      .FromJust();
1076 1077 1078 1079 1080 1081
  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 =
1082 1083 1084 1085 1086 1087 1088 1089
      env->Global()
          ->Get(env.local(), v8_str("parsed"))
          .ToLocalChecked()
          ->ToObject(env.local())
          .ToLocalChecked();
  CHECK(parsed_snapshot->Has(env.local(), v8_str("snapshot")).FromJust());
  CHECK(parsed_snapshot->Has(env.local(), v8_str("nodes")).FromJust());
  CHECK(parsed_snapshot->Has(env.local(), v8_str("edges")).FromJust());
1090
  CHECK(parsed_snapshot->Has(env.local(), v8_str("locations")).FromJust());
1091
  CHECK(parsed_snapshot->Has(env.local(), v8_str("strings")).FromJust());
1092 1093 1094

  // Get node and edge "member" offsets.
  v8::Local<v8::Value> meta_analysis_result = CompileRun(
1095
      "var meta = parsed.snapshot.meta;\n"
1096
      "var edge_count_offset = meta.node_fields.indexOf('edge_count');\n"
1097 1098 1099 1100 1101
      "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"
1102
      "var property_type ="
1103
      "    meta.edge_types[edge_type_offset].indexOf('property');\n"
1104
      "var shortcut_type ="
1105
      "    meta.edge_types[edge_type_offset].indexOf('shortcut');\n"
1106 1107 1108 1109 1110 1111
      "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"
1112 1113
      "}\n"
      "first_edge_indexes[node_count] = first_edge_index;\n");
1114 1115 1116 1117
  CHECK(!meta_analysis_result.IsEmpty());

  // A helper function for processing encoded nodes.
  CompileRun(
1118
      "function GetChildPosByProperty(pos, prop_name, prop_type) {\n"
1119
      "  var nodes = parsed.nodes;\n"
1120
      "  var edges = parsed.edges;\n"
1121
      "  var strings = parsed.strings;\n"
1122 1123 1124
      "  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"
1125 1126 1127 1128
      "      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"
1129 1130 1131 1132 1133 1134 1135 1136
      "  }\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("
1137
      "      parsed.edges[edge_fields_count + edge_to_node_offset],"
1138
      "      \"b\", property_type),\n"
1139 1140
      "    \"x\", property_type),"
      "  \"s\", property_type)");
1141
  CHECK(!string_obj_pos_val.IsEmpty());
1142 1143
  int string_obj_pos = static_cast<int>(
      string_obj_pos_val->ToNumber(env.local()).ToLocalChecked()->Value());
1144
  v8::Local<v8::Object> nodes_array =
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
      parsed_snapshot->Get(env.local(), v8_str("nodes"))
          .ToLocalChecked()
          ->ToObject(env.local())
          .ToLocalChecked();
  int string_index =
      static_cast<int>(nodes_array->Get(env.local(), string_obj_pos + 1)
                           .ToLocalChecked()
                           ->ToNumber(env.local())
                           .ToLocalChecked()
                           ->Value());
1155 1156
  CHECK_GT(string_index, 0);
  v8::Local<v8::Object> strings_array =
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
      parsed_snapshot->Get(env.local(), v8_str("strings"))
          .ToLocalChecked()
          ->ToObject(env.local())
          .ToLocalChecked();
  v8::Local<v8::String> string = strings_array->Get(env.local(), string_index)
                                     .ToLocalChecked()
                                     ->ToString(env.local())
                                     .ToLocalChecked();
  v8::Local<v8::String> ref_string = CompileRun(STRING_LITERAL_FOR_TEST)
                                         ->ToString(env.local())
                                         .ToLocalChecked();
1168
#undef STRING_LITERAL_FOR_TEST
1169 1170
  CHECK_EQ(0, strcmp(*v8::String::Utf8Value(env->GetIsolate(), ref_string),
                     *v8::String::Utf8Value(env->GetIsolate(), string)));
1171 1172
}

1173 1174 1175

TEST(HeapSnapshotJSONSerializationAborting) {
  LocalContext env;
1176
  v8::HandleScope scope(env->GetIsolate());
1177
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1178
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1179
  CHECK(ValidateSnapshot(snapshot));
1180 1181 1182 1183 1184 1185
  TestJSONStream stream(5);
  snapshot->Serialize(&stream, v8::HeapSnapshot::kJSON);
  CHECK_GT(stream.size(), 0);
  CHECK_EQ(0, stream.eos_signaled());
}

1186 1187 1188 1189 1190 1191
namespace {

class TestStatsStream : public v8::OutputStream {
 public:
  TestStatsStream()
    : eos_signaled_(0),
1192
      updates_written_(0),
1193
      entries_count_(0),
1194
      entries_size_(0),
1195 1196 1197
      intervals_count_(0),
      first_interval_index_(-1) { }
  TestStatsStream(const TestStatsStream& stream)
1198 1199

      = default;
1200 1201 1202
  ~TestStatsStream() override = default;
  void EndOfStream() override { ++eos_signaled_; }
  WriteResult WriteAsciiChunk(char* buffer, int chars_written) override {
1203
    UNREACHABLE();
1204
  }
1205 1206
  WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* buffer,
                                  int updates_written) override {
1207
    ++intervals_count_;
1208
    CHECK(updates_written);
1209
    updates_written_ += updates_written;
1210
    entries_count_ = 0;
1211 1212 1213 1214 1215
    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;
1216
    }
1217 1218 1219 1220

    return kContinue;
  }
  int eos_signaled() { return eos_signaled_; }
1221
  int updates_written() { return updates_written_; }
1222
  uint32_t entries_count() const { return entries_count_; }
1223
  uint32_t entries_size() const { return entries_size_; }
1224 1225 1226 1227 1228
  int intervals_count() const { return intervals_count_; }
  int first_interval_index() const { return first_interval_index_; }

 private:
  int eos_signaled_;
1229
  int updates_written_;
1230
  uint32_t entries_count_;
1231
  uint32_t entries_size_;
1232 1233 1234 1235 1236 1237
  int intervals_count_;
  int first_interval_index_;
};

}  // namespace

1238
static TestStatsStream GetHeapStatsUpdate(
1239
    v8::HeapProfiler* heap_profiler,
1240
    v8::SnapshotObjectId* object_id = nullptr) {
1241
  TestStatsStream stream;
1242 1243 1244
  int64_t timestamp = -1;
  v8::SnapshotObjectId last_seen_id =
      heap_profiler->GetHeapStats(&stream, &timestamp);
1245 1246
  if (object_id)
    *object_id = last_seen_id;
1247
  CHECK_NE(-1, timestamp);
1248 1249 1250 1251 1252 1253 1254
  CHECK_EQ(1, stream.eos_signaled());
  return stream;
}


TEST(HeapSnapshotObjectsStats) {
  LocalContext env;
1255
  v8::HandleScope scope(env->GetIsolate());
1256
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1257

1258
  heap_profiler->StartTrackingHeapObjects();
1259
  // We have to call GC 6 times. In other case the garbage will be
1260
  // the reason of flakiness.
1261
  for (int i = 0; i < 6; ++i) {
1262
    CcTest::CollectAllGarbage();
1263 1264
  }

1265
  v8::SnapshotObjectId initial_id;
1266 1267
  {
    // Single chunk of data expected in update. Initial data.
1268 1269
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler,
                                                      &initial_id);
1270
    CHECK_EQ(1, stats_update.intervals_count());
1271
    CHECK_EQ(1, stats_update.updates_written());
1272
    CHECK_LT(0u, stats_update.entries_size());
1273 1274 1275 1276
    CHECK_EQ(0, stats_update.first_interval_index());
  }

  // No data expected in update because nothing has happened.
1277
  v8::SnapshotObjectId same_id;
1278
  CHECK_EQ(0, GetHeapStatsUpdate(heap_profiler, &same_id).updates_written());
1279
  CHECK_EQ(initial_id, same_id);
1280

1281
  {
1282
    v8::SnapshotObjectId additional_string_id;
1283
    v8::HandleScope inner_scope_1(env->GetIsolate());
1284
    v8_str("string1");
1285 1286
    {
      // Single chunk of data with one new entry expected in update.
1287 1288
      TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler,
                                                        &additional_string_id);
1289
      CHECK_LT(same_id, additional_string_id);
1290
      CHECK_EQ(1, stats_update.intervals_count());
1291
      CHECK_EQ(1, stats_update.updates_written());
1292 1293
      CHECK_LT(0u, stats_update.entries_size());
      CHECK_EQ(1u, stats_update.entries_count());
1294 1295 1296 1297
      CHECK_EQ(2, stats_update.first_interval_index());
    }

    // No data expected in update because nothing happened.
1298
    v8::SnapshotObjectId last_id;
1299
    CHECK_EQ(0, GetHeapStatsUpdate(heap_profiler, &last_id).updates_written());
1300
    CHECK_EQ(additional_string_id, last_id);
1301 1302

    {
1303
      v8::HandleScope inner_scope_2(env->GetIsolate());
1304
      v8_str("string2");
1305

1306
      uint32_t entries_size;
1307
      {
1308
        v8::HandleScope inner_scope_3(env->GetIsolate());
1309 1310
        v8_str("string3");
        v8_str("string4");
1311 1312 1313

        {
          // Single chunk of data with three new entries expected in update.
1314
          TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1315
          CHECK_EQ(1, stats_update.intervals_count());
1316
          CHECK_EQ(1, stats_update.updates_written());
1317 1318
          CHECK_LT(0u, entries_size = stats_update.entries_size());
          CHECK_EQ(3u, stats_update.entries_count());
1319 1320 1321 1322 1323 1324
          CHECK_EQ(4, stats_update.first_interval_index());
        }
      }

      {
        // Single chunk of data with two left entries expected in update.
1325
        TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1326
        CHECK_EQ(1, stats_update.intervals_count());
1327
        CHECK_EQ(1, stats_update.updates_written());
1328
        CHECK_GT(entries_size, stats_update.entries_size());
1329
        CHECK_EQ(1u, stats_update.entries_count());
1330 1331 1332 1333 1334 1335 1336
        // 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.
1337
      TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1338
      CHECK_EQ(1, stats_update.intervals_count());
1339
      CHECK_EQ(1, stats_update.updates_written());
1340 1341
      CHECK_EQ(0u, stats_update.entries_size());
      CHECK_EQ(0u, stats_update.entries_count());
1342 1343 1344 1345 1346 1347
      // 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.
1348
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1349
    CHECK_EQ(1, stats_update.intervals_count());
1350
    CHECK_EQ(1, stats_update.updates_written());
1351 1352
    CHECK_EQ(0u, stats_update.entries_size());
    CHECK_EQ(0u, stats_update.entries_count());
1353 1354 1355 1356
    // The only string from the second interval was released.
    CHECK_EQ(2, stats_update.first_interval_index());
  }

1357
  v8::Local<v8::Array> array = v8::Array::New(env->GetIsolate());
1358
  CHECK_EQ(0u, array->Length());
1359
  // Force array's buffer allocation.
1360
  array->Set(env.local(), 2, v8_num(7)).FromJust();
1361 1362 1363 1364

  uint32_t entries_size;
  {
    // Single chunk of data with 2 entries expected in update.
1365
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1366
    CHECK_EQ(1, stats_update.intervals_count());
1367
    CHECK_EQ(1, stats_update.updates_written());
1368
    CHECK_LT(0u, entries_size = stats_update.entries_size());
1369
    // They are the array and its buffer.
1370
    CHECK_EQ(2u, stats_update.entries_count());
1371 1372 1373 1374
    CHECK_EQ(8, stats_update.first_interval_index());
  }

  for (int i = 0; i < 100; ++i)
1375
    array->Set(env.local(), i, v8_num(i)).FromJust();
1376 1377 1378

  {
    // Single chunk of data with 1 entry expected in update.
1379
    TestStatsStream stats_update = GetHeapStatsUpdate(heap_profiler);
1380 1381 1382
    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.
1383
    CHECK_EQ(2, stats_update.updates_written());
1384
    CHECK_LT(entries_size, stats_update.entries_size());
1385
    CHECK_EQ(2u, stats_update.entries_count());
1386 1387 1388
    CHECK_EQ(8, stats_update.first_interval_index());
  }

1389
  heap_profiler->StopTrackingHeapObjects();
1390 1391
}

1392

1393 1394 1395 1396 1397 1398 1399
TEST(HeapObjectIds) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  const int kLength = 10;
1400
  v8::Local<v8::Object> objects[kLength];
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
  v8::SnapshotObjectId ids[kLength];

  heap_profiler->StartTrackingHeapObjects(false);

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

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

  heap_profiler->StopTrackingHeapObjects();
1417
  CcTest::CollectAllAvailableGarbage();
1418 1419 1420

  for (int i = 0; i < kLength; i++) {
    v8::SnapshotObjectId id = heap_profiler->GetObjectId(objects[i]);
1421
    CHECK_EQ(ids[i], id);
1422 1423
    v8::Local<v8::Value> obj = heap_profiler->FindObjectById(ids[i]);
    CHECK(objects[i]->Equals(env.local(), obj).FromJust());
1424 1425 1426 1427 1428
  }

  heap_profiler->ClearObjectIds();
  for (int i = 0; i < kLength; i++) {
    v8::SnapshotObjectId id = heap_profiler->GetObjectId(objects[i]);
1429
    CHECK_EQ(v8::HeapProfiler::kUnknownObjectId, id);
1430
    v8::Local<v8::Value> obj = heap_profiler->FindObjectById(ids[i]);
1431 1432 1433 1434 1435
    CHECK(obj.IsEmpty());
  }
}


1436 1437 1438 1439 1440 1441 1442 1443 1444
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());
1445
    CHECK_EQ(prop->GetToNode()->GetId(), child->GetId());
1446 1447 1448 1449 1450 1451
    CHECK_EQ(prop->GetToNode(), child);
    CheckChildrenIds(snapshot, child, level + 1, max_level);
  }
}


1452 1453
TEST(HeapSnapshotGetNodeById) {
  LocalContext env;
1454
  v8::HandleScope scope(env->GetIsolate());
1455
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1456

1457
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1458
  CHECK(ValidateSnapshot(snapshot));
1459
  const v8::HeapGraphNode* root = snapshot->GetRoot();
1460
  CheckChildrenIds(snapshot, root, 0, 3);
1461
  // Check a big id, which should not exist yet.
1462
  CHECK(!snapshot->GetNodeById(0x1000000UL));
1463 1464
}

1465

1466 1467
TEST(HeapSnapshotGetSnapshotObjectId) {
  LocalContext env;
1468
  v8::HandleScope scope(env->GetIsolate());
1469
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1470
  CompileRun("globalObject = {};\n");
1471
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1472
  CHECK(ValidateSnapshot(snapshot));
1473
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
1474 1475
  const v8::HeapGraphNode* global_object = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "globalObject");
1476 1477
  CHECK(global_object);

1478 1479
  v8::Local<v8::Value> globalObjectHandle =
      env->Global()->Get(env.local(), v8_str("globalObject")).ToLocalChecked();
1480 1481 1482
  CHECK(!globalObjectHandle.IsEmpty());
  CHECK(globalObjectHandle->IsObject());

1483
  v8::SnapshotObjectId id = heap_profiler->GetObjectId(globalObjectHandle);
1484 1485
  CHECK_NE(v8::HeapProfiler::kUnknownObjectId, id);
  CHECK_EQ(id, global_object->GetId());
1486 1487 1488 1489 1490
}


TEST(HeapSnapshotUnknownSnapshotObjectId) {
  LocalContext env;
1491
  v8::HandleScope scope(env->GetIsolate());
1492
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1493
  CompileRun("globalObject = {};\n");
1494
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1495
  CHECK(ValidateSnapshot(snapshot));
1496 1497
  const v8::HeapGraphNode* node =
      snapshot->GetNodeById(v8::HeapProfiler::kUnknownObjectId);
1498
  CHECK(!node);
1499 1500 1501
}


1502 1503 1504 1505 1506
namespace {

class TestActivityControl : public v8::ActivityControl {
 public:
  explicit TestActivityControl(int abort_count)
1507 1508 1509 1510
      : done_(0),
        total_(0),
        abort_count_(abort_count),
        reported_finish_(false) {}
1511
  ControlOption ReportProgressValue(int done, int total) override {
1512 1513
    done_ = done;
    total_ = total;
1514 1515 1516 1517 1518
    CHECK_LE(done_, total_);
    if (done_ == total_) {
      CHECK(!reported_finish_);
      reported_finish_ = true;
    }
1519 1520 1521 1522 1523 1524 1525 1526 1527
    return --abort_count_ != 0 ? kContinue : kAbort;
  }
  int done() { return done_; }
  int total() { return total_; }

 private:
  int done_;
  int total_;
  int abort_count_;
1528
  bool reported_finish_;
1529
};
1530 1531

}  // namespace
1532

1533

1534 1535
TEST(TakeHeapSnapshotAborting) {
  LocalContext env;
1536
  v8::HandleScope scope(env->GetIsolate());
1537

1538 1539
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  const int snapshots_count = heap_profiler->GetSnapshotCount();
1540
  TestActivityControl aborting_control(1);
1541
  const v8::HeapSnapshot* no_snapshot =
1542
      heap_profiler->TakeHeapSnapshot(&aborting_control);
1543
  CHECK(!no_snapshot);
1544
  CHECK_EQ(snapshots_count, heap_profiler->GetSnapshotCount());
1545 1546 1547
  CHECK_GT(aborting_control.total(), aborting_control.done());

  TestActivityControl control(-1);  // Don't abort.
1548
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot(&control);
1549
  CHECK(ValidateSnapshot(snapshot));
1550

1551
  CHECK(snapshot);
1552
  CHECK_EQ(snapshots_count + 1, heap_profiler->GetSnapshotCount());
1553 1554 1555 1556
  CHECK_EQ(control.total(), control.done());
  CHECK_GT(control.total(), 0);
}

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
TEST(TakeHeapSnapshotReportFinishOnce) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  TestActivityControl control(-1);
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot(&control);
  CHECK(ValidateSnapshot(snapshot));
  CHECK_EQ(control.total(), control.done());
  CHECK_GT(control.total(), 0);
}
1567 1568 1569

namespace {

1570
class EmbedderGraphBuilder : public v8::PersistentHandleVisitor {
1571
 public:
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
  class Node : public v8::EmbedderGraph::Node {
   public:
    Node(const char* name, size_t size) : name_(name), size_(size) {}
    // v8::EmbedderGraph::Node
    const char* Name() override { return name_; }
    size_t SizeInBytes() override { return size_; }

   private:
    const char* name_;
    size_t size_;
  };

  class Group : public Node {
   public:
    explicit Group(const char* name) : Node(name, 0) {}
    // v8::EmbedderGraph::EmbedderNode
1588
    bool IsRootNode() override { return true; }
1589 1590 1591 1592 1593 1594 1595 1596 1597
  };

  EmbedderGraphBuilder(v8::Isolate* isolate, v8::EmbedderGraph* graph)
      : isolate_(isolate), graph_(graph) {
    classid_to_group_[0] = nullptr;
    classid_to_group_[1] =
        graph->AddNode(std::unique_ptr<Group>(new Group("aaa-group")));
    classid_to_group_[2] =
        graph->AddNode(std::unique_ptr<Group>(new Group("ccc-group")));
1598
  }
1599

1600 1601
  static void BuildEmbedderGraph(v8::Isolate* isolate, v8::EmbedderGraph* graph,
                                 void* data) {
1602 1603
    EmbedderGraphBuilder builder(isolate, graph);
    isolate->VisitHandlesWithClassIds(&builder);
1604
  }
1605 1606 1607 1608 1609

  void VisitPersistentHandle(v8::Persistent<v8::Value>* value,
                             uint16_t class_id) override {
    v8::Local<v8::Value> wrapper = v8::Local<v8::Value>::New(
        isolate_, v8::Persistent<v8::Value>::Cast(*value));
1610 1611
    if (class_id == 1) {
      if (wrapper->IsString()) {
1612
        v8::String::Utf8Value utf8(CcTest::isolate(), wrapper);
1613 1614 1615 1616 1617
        DCHECK(!strcmp(*utf8, "AAA") || !strcmp(*utf8, "BBB"));
        v8::EmbedderGraph::Node* node = graph_->V8Node(wrapper);
        v8::EmbedderGraph::Node* group = classid_to_group_[1];
        graph_->AddEdge(node, group);
        graph_->AddEdge(group, node);
1618 1619 1620
      }
    } else if (class_id == 2) {
      if (wrapper->IsString()) {
1621
        v8::String::Utf8Value utf8(CcTest::isolate(), wrapper);
1622 1623 1624 1625 1626
        DCHECK(!strcmp(*utf8, "CCC"));
        v8::EmbedderGraph::Node* node = graph_->V8Node(wrapper);
        v8::EmbedderGraph::Node* group = classid_to_group_[2];
        graph_->AddEdge(node, group);
        graph_->AddEdge(group, node);
1627
      }
1628 1629
    } else {
      UNREACHABLE();
1630 1631 1632 1633
    }
  }

 private:
1634 1635 1636
  v8::Isolate* isolate_;
  v8::EmbedderGraph* graph_;
  v8::EmbedderGraph::Node* classid_to_group_[3];
1637 1638
};

1639
}  // namespace
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652


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;
    }
  }
1653
  return nullptr;
1654 1655 1656 1657 1658
}


TEST(HeapSnapshotRetainedObjectInfo) {
  LocalContext env;
1659
  v8::Isolate* isolate = env->GetIsolate();
1660
  v8::HandleScope scope(isolate);
1661
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
1662

1663 1664
  heap_profiler->AddBuildEmbedderGraphCallback(
      EmbedderGraphBuilder::BuildEmbedderGraph, nullptr);
1665
  v8::Persistent<v8::String> p_AAA(isolate, v8_str("AAA"));
1666
  p_AAA.SetWrapperClassId(1);
1667
  v8::Persistent<v8::String> p_BBB(isolate, v8_str("BBB"));
1668
  p_BBB.SetWrapperClassId(1);
1669
  v8::Persistent<v8::String> p_CCC(isolate, v8_str("CCC"));
1670
  p_CCC.SetWrapperClassId(2);
1671
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1672
  CHECK(ValidateSnapshot(snapshot));
1673

1674 1675
  const v8::HeapGraphNode* native_group_aaa =
      GetNode(snapshot->GetRoot(), v8::HeapGraphNode::kNative, "aaa-group");
1676
  CHECK(native_group_aaa);
1677 1678 1679 1680 1681 1682
  const v8::HeapGraphNode* native_group_ccc =
      GetNode(snapshot->GetRoot(), v8::HeapGraphNode::kNative, "ccc-group");
  CHECK(native_group_ccc);

  const v8::HeapGraphNode* n_AAA =
      GetNode(native_group_aaa, v8::HeapGraphNode::kString, "AAA");
1683
  CHECK(n_AAA);
1684 1685
  const v8::HeapGraphNode* n_BBB =
      GetNode(native_group_aaa, v8::HeapGraphNode::kString, "BBB");
1686
  CHECK(n_BBB);
1687 1688
  const v8::HeapGraphNode* n_CCC =
      GetNode(native_group_ccc, v8::HeapGraphNode::kString, "CCC");
1689
  CHECK(n_CCC);
1690

1691 1692 1693
  CHECK_EQ(native_group_aaa, GetChildByName(n_AAA, "aaa-group"));
  CHECK_EQ(native_group_aaa, GetChildByName(n_BBB, "aaa-group"));
  CHECK_EQ(native_group_ccc, GetChildByName(n_CCC, "ccc-group"));
1694 1695
}

1696 1697
TEST(DeleteAllHeapSnapshots) {
  LocalContext env;
1698
  v8::HandleScope scope(env->GetIsolate());
1699 1700 1701 1702 1703
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
  heap_profiler->DeleteAllHeapSnapshots();
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1704
  CHECK(heap_profiler->TakeHeapSnapshot());
1705 1706 1707
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
  heap_profiler->DeleteAllHeapSnapshots();
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1708 1709
  CHECK(heap_profiler->TakeHeapSnapshot());
  CHECK(heap_profiler->TakeHeapSnapshot());
1710 1711 1712
  CHECK_EQ(2, heap_profiler->GetSnapshotCount());
  heap_profiler->DeleteAllHeapSnapshots();
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1713 1714 1715
}


1716 1717
static bool FindHeapSnapshot(v8::HeapProfiler* profiler,
                             const v8::HeapSnapshot* snapshot) {
1718 1719
  int length = profiler->GetSnapshotCount();
  for (int i = 0; i < length; i++) {
1720
    if (snapshot == profiler->GetHeapSnapshot(i)) return true;
1721
  }
1722
  return false;
1723 1724 1725
}


1726 1727
TEST(DeleteHeapSnapshot) {
  LocalContext env;
1728
  v8::HandleScope scope(env->GetIsolate());
1729
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1730

1731
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1732
  const v8::HeapSnapshot* s1 = heap_profiler->TakeHeapSnapshot();
1733

1734
  CHECK(s1);
1735
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1736
  CHECK(FindHeapSnapshot(heap_profiler, s1));
1737
  const_cast<v8::HeapSnapshot*>(s1)->Delete();
1738
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1739
  CHECK(!FindHeapSnapshot(heap_profiler, s1));
1740

1741
  const v8::HeapSnapshot* s2 = heap_profiler->TakeHeapSnapshot();
1742
  CHECK(s2);
1743
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1744 1745
  CHECK(FindHeapSnapshot(heap_profiler, s2));
  const v8::HeapSnapshot* s3 = heap_profiler->TakeHeapSnapshot();
1746
  CHECK(s3);
1747
  CHECK_EQ(2, heap_profiler->GetSnapshotCount());
1748 1749
  CHECK_NE(s2, s3);
  CHECK(FindHeapSnapshot(heap_profiler, s3));
1750
  const_cast<v8::HeapSnapshot*>(s2)->Delete();
1751
  CHECK_EQ(1, heap_profiler->GetSnapshotCount());
1752 1753
  CHECK(!FindHeapSnapshot(heap_profiler, s2));
  CHECK(FindHeapSnapshot(heap_profiler, s3));
1754
  const_cast<v8::HeapSnapshot*>(s3)->Delete();
1755
  CHECK_EQ(0, heap_profiler->GetSnapshotCount());
1756
  CHECK(!FindHeapSnapshot(heap_profiler, s3));
1757 1758
}

1759

1760 1761
class NameResolver : public v8::HeapProfiler::ObjectNameResolver {
 public:
1762
  const char* GetName(v8::Local<v8::Object> object) override {
1763 1764 1765 1766
    return "Global object name";
  }
};

1767

1768 1769
TEST(GlobalObjectName) {
  LocalContext env;
1770
  v8::HandleScope scope(env->GetIsolate());
1771
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1772 1773 1774 1775 1776

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

  NameResolver name_resolver;
  const v8::HeapSnapshot* snapshot =
1777
      heap_profiler->TakeHeapSnapshot(nullptr, &name_resolver);
1778
  CHECK(ValidateSnapshot(snapshot));
1779
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
1780 1781 1782 1783 1784
  CHECK(global);
  CHECK_EQ(0,
           strcmp("Object / Global object name",
                  const_cast<i::HeapEntry*>(
                      reinterpret_cast<const i::HeapEntry*>(global))->name()));
1785 1786 1787
}


1788 1789 1790 1791 1792
TEST(GlobalObjectFields) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun("obj = {};");
1793
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1794 1795 1796
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* native_context =
1797 1798
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kInternal,
                  "native_context");
1799
  CHECK(native_context);
1800 1801
  const v8::HeapGraphNode* global_proxy = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kInternal, "global_proxy");
1802
  CHECK(global_proxy);
1803 1804 1805
}


1806 1807
TEST(NoHandleLeaks) {
  LocalContext env;
1808
  v8::HandleScope scope(env->GetIsolate());
1809
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1810 1811 1812

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

1813
  i::Isolate* isolate = CcTest::i_isolate();
1814
  int count_before = i::HandleScope::NumberOfHandles(isolate);
1815
  heap_profiler->TakeHeapSnapshot();
1816
  int count_after = i::HandleScope::NumberOfHandles(isolate);
1817 1818 1819 1820
  CHECK_EQ(count_before, count_after);
}


1821 1822
TEST(NodesIteration) {
  LocalContext env;
1823
  v8::HandleScope scope(env->GetIsolate());
1824
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1825
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1826
  CHECK(ValidateSnapshot(snapshot));
1827
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
1828
  CHECK(global);
1829 1830 1831 1832 1833 1834 1835 1836 1837
  // 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);
}
1838 1839


1840
TEST(GetHeapValueForNode) {
1841
  LocalContext env;
1842
  v8::HandleScope scope(env->GetIsolate());
1843
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1844

1845
  CompileRun("a = { s_prop: \'value\', n_prop: \'value2\' };");
1846
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1847
  CHECK(ValidateSnapshot(snapshot));
1848
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
1849
  CHECK(heap_profiler->FindObjectById(global->GetId())->IsObject());
1850 1851
  v8::Local<v8::Object> js_global =
      env->Global()->GetPrototype().As<v8::Object>();
1852
  CHECK(js_global == heap_profiler->FindObjectById(global->GetId()));
1853 1854
  const v8::HeapGraphNode* obj =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "a");
1855
  CHECK(heap_profiler->FindObjectById(obj->GetId())->IsObject());
1856 1857 1858
  v8::Local<v8::Object> js_obj = js_global->Get(env.local(), v8_str("a"))
                                     .ToLocalChecked()
                                     .As<v8::Object>();
1859
  CHECK(js_obj == heap_profiler->FindObjectById(obj->GetId()));
1860 1861
  const v8::HeapGraphNode* s_prop = GetProperty(
      env->GetIsolate(), obj, v8::HeapGraphEdge::kProperty, "s_prop");
1862 1863 1864
  v8::Local<v8::String> js_s_prop = js_obj->Get(env.local(), v8_str("s_prop"))
                                        .ToLocalChecked()
                                        .As<v8::String>();
1865
  CHECK(js_s_prop == heap_profiler->FindObjectById(s_prop->GetId()));
1866 1867
  const v8::HeapGraphNode* n_prop = GetProperty(
      env->GetIsolate(), obj, v8::HeapGraphEdge::kProperty, "n_prop");
1868 1869 1870
  v8::Local<v8::String> js_n_prop = js_obj->Get(env.local(), v8_str("n_prop"))
                                        .ToLocalChecked()
                                        .As<v8::String>();
1871
  CHECK(js_n_prop == heap_profiler->FindObjectById(n_prop->GetId()));
1872 1873 1874 1875 1876
}


TEST(GetHeapValueForDeletedObject) {
  LocalContext env;
1877
  v8::HandleScope scope(env->GetIsolate());
1878
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
1879 1880 1881 1882 1883

  // 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: {} } };");
1884
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
1885
  CHECK(ValidateSnapshot(snapshot));
1886
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
1887 1888 1889 1890
  const v8::HeapGraphNode* obj =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "a");
  const v8::HeapGraphNode* prop =
      GetProperty(env->GetIsolate(), obj, v8::HeapGraphEdge::kProperty, "p");
1891 1892 1893
  {
    // Perform the check inside a nested local scope to avoid creating a
    // reference to the object we are deleting.
1894
    v8::HandleScope scope(env->GetIsolate());
1895
    CHECK(heap_profiler->FindObjectById(prop->GetId())->IsObject());
1896 1897
  }
  CompileRun("delete a.p;");
1898
  CHECK(heap_profiler->FindObjectById(prop->GetId()).IsEmpty());
1899 1900 1901
}


1902
static int StringCmp(const char* ref, i::String* act) {
1903
  std::unique_ptr<char[]> s_act = act->ToCString();
1904
  int result = strcmp(ref, s_act.get());
1905
  if (result != 0)
1906
    fprintf(stderr, "Expected: \"%s\", Actual: \"%s\"\n", ref, s_act.get());
1907 1908 1909
  return result;
}

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
TEST(GetConstructor) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());

  CompileRun(
      "function Constructor1() {};\n"
      "var obj1 = new Constructor1();\n"
      "var Constructor2 = function() {};\n"
      "var obj2 = new Constructor2();\n"
      "var obj3 = {};\n"
      "obj3.__proto__ = { constructor: function Constructor3() {} };\n"
      "var obj4 = {};\n"
      "// Slow properties\n"
      "for (var i=0; i<2000; ++i) obj4[\"p\" + i] = i;\n"
      "obj4.__proto__ = { 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(env.local(), v8_str("obj1"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
  i::Handle<i::JSObject> js_obj1 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj1));
  CHECK(i::V8HeapExplorer::GetConstructor(*js_obj1));
  v8::Local<v8::Object> obj2 = js_global->Get(env.local(), v8_str("obj2"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
  i::Handle<i::JSObject> js_obj2 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj2));
  CHECK(i::V8HeapExplorer::GetConstructor(*js_obj2));
  v8::Local<v8::Object> obj3 = js_global->Get(env.local(), v8_str("obj3"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
  i::Handle<i::JSObject> js_obj3 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj3));
  CHECK(i::V8HeapExplorer::GetConstructor(*js_obj3));
  v8::Local<v8::Object> obj4 = js_global->Get(env.local(), v8_str("obj4"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
  i::Handle<i::JSObject> js_obj4 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj4));
  CHECK(i::V8HeapExplorer::GetConstructor(*js_obj4));
  v8::Local<v8::Object> obj5 = js_global->Get(env.local(), v8_str("obj5"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
  i::Handle<i::JSObject> js_obj5 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj5));
  CHECK(!i::V8HeapExplorer::GetConstructor(*js_obj5));
  v8::Local<v8::Object> obj6 = js_global->Get(env.local(), v8_str("obj6"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
  i::Handle<i::JSObject> js_obj6 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj6));
  CHECK(!i::V8HeapExplorer::GetConstructor(*js_obj6));
}
1967 1968 1969

TEST(GetConstructorName) {
  LocalContext env;
1970
  v8::HandleScope scope(env->GetIsolate());
1971 1972 1973 1974 1975 1976 1977

  CompileRun(
      "function Constructor1() {};\n"
      "var obj1 = new Constructor1();\n"
      "var Constructor2 = function() {};\n"
      "var obj2 = new Constructor2();\n"
      "var obj3 = {};\n"
1978
      "obj3.__proto__ = { constructor: function Constructor3() {} };\n"
1979 1980 1981
      "var obj4 = {};\n"
      "// Slow properties\n"
      "for (var i=0; i<2000; ++i) obj4[\"p\" + i] = i;\n"
1982
      "obj4.__proto__ = { constructor: function Constructor4() {} };\n"
1983 1984 1985 1986 1987
      "var obj5 = {};\n"
      "var obj6 = {};\n"
      "obj6.constructor = 6;");
  v8::Local<v8::Object> js_global =
      env->Global()->GetPrototype().As<v8::Object>();
1988 1989 1990
  v8::Local<v8::Object> obj1 = js_global->Get(env.local(), v8_str("obj1"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
1991 1992
  i::Handle<i::JSObject> js_obj1 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj1));
1993 1994
  CHECK_EQ(0, StringCmp(
      "Constructor1", i::V8HeapExplorer::GetConstructorName(*js_obj1)));
1995 1996 1997
  v8::Local<v8::Object> obj2 = js_global->Get(env.local(), v8_str("obj2"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
1998 1999
  i::Handle<i::JSObject> js_obj2 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj2));
2000 2001
  CHECK_EQ(0, StringCmp(
      "Constructor2", i::V8HeapExplorer::GetConstructorName(*js_obj2)));
2002 2003 2004
  v8::Local<v8::Object> obj3 = js_global->Get(env.local(), v8_str("obj3"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
2005 2006
  i::Handle<i::JSObject> js_obj3 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj3));
2007 2008
  CHECK_EQ(0, StringCmp("Constructor3",
                        i::V8HeapExplorer::GetConstructorName(*js_obj3)));
2009 2010 2011
  v8::Local<v8::Object> obj4 = js_global->Get(env.local(), v8_str("obj4"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
2012 2013
  i::Handle<i::JSObject> js_obj4 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj4));
2014 2015
  CHECK_EQ(0, StringCmp("Constructor4",
                        i::V8HeapExplorer::GetConstructorName(*js_obj4)));
2016 2017 2018
  v8::Local<v8::Object> obj5 = js_global->Get(env.local(), v8_str("obj5"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
2019 2020
  i::Handle<i::JSObject> js_obj5 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj5));
2021 2022
  CHECK_EQ(0, StringCmp(
      "Object", i::V8HeapExplorer::GetConstructorName(*js_obj5)));
2023 2024 2025
  v8::Local<v8::Object> obj6 = js_global->Get(env.local(), v8_str("obj6"))
                                   .ToLocalChecked()
                                   .As<v8::Object>();
2026 2027
  i::Handle<i::JSObject> js_obj6 =
      i::Handle<i::JSObject>::cast(v8::Utils::OpenHandle(*obj6));
2028 2029 2030
  CHECK_EQ(0, StringCmp(
      "Object", i::V8HeapExplorer::GetConstructorName(*js_obj6)));
}
2031

2032

2033
TEST(FastCaseAccessors) {
2034
  LocalContext env;
2035
  v8::HandleScope scope(env->GetIsolate());
2036
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2037 2038 2039 2040 2041 2042 2043 2044

  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");
2045
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2046
  CHECK(ValidateSnapshot(snapshot));
2047 2048

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2049
  CHECK(global);
2050 2051
  const v8::HeapGraphNode* obj1 = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "obj1");
2052
  CHECK(obj1);
2053
  const v8::HeapGraphNode* func;
2054 2055
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "get propWithGetter");
2056
  CHECK(func);
2057 2058
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "set propWithGetter");
2059
  CHECK(!func);
2060 2061
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "set propWithSetter");
2062
  CHECK(func);
2063 2064
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "get propWithSetter");
2065
  CHECK(!func);
2066
}
2067

2068

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
TEST(FastCaseRedefinedAccessors) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun(
      "var obj1 = {};\n"
      "Object.defineProperty(obj1, 'prop', { "
      "  get: function() { return 42; },\n"
      "  set: function(value) { return this.prop_ = value; },\n"
      "  configurable: true,\n"
      "  enumerable: true,\n"
      "});\n"
      "Object.defineProperty(obj1, 'prop', { "
      "  get: function() { return 153; },\n"
      "  set: function(value) { return this.prop_ = value; },\n"
      "  configurable: true,\n"
      "  enumerable: true,\n"
      "});\n");
  v8::Local<v8::Object> js_global =
      env->Global()->GetPrototype().As<v8::Object>();
2090
  i::Handle<i::JSReceiver> js_obj1 =
2091 2092 2093
      v8::Utils::OpenHandle(*js_global->Get(env.local(), v8_str("obj1"))
                                 .ToLocalChecked()
                                 .As<v8::Object>());
2094 2095
  USE(js_obj1);

2096
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2097 2098
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2099
  CHECK(global);
2100 2101
  const v8::HeapGraphNode* obj1 = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "obj1");
2102
  CHECK(obj1);
2103
  const v8::HeapGraphNode* func;
2104 2105
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "get prop");
2106
  CHECK(func);
2107 2108
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "set prop");
2109
  CHECK(func);
2110 2111 2112
}


2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
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");
2126
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2127
  CHECK(ValidateSnapshot(snapshot));
2128 2129

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2130
  CHECK(global);
2131 2132
  const v8::HeapGraphNode* obj1 = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "obj1");
2133
  CHECK(obj1);
2134
  const v8::HeapGraphNode* func;
2135 2136
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "get propWithGetter");
2137
  CHECK(func);
2138 2139
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "set propWithGetter");
2140
  CHECK(!func);
2141 2142
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "set propWithSetter");
2143
  CHECK(func);
2144 2145
  func = GetProperty(env->GetIsolate(), obj1, v8::HeapGraphEdge::kProperty,
                     "get propWithSetter");
2146
  CHECK(!func);
2147 2148 2149
}


2150
TEST(HiddenPropertiesFastCase) {
2151
  v8::Isolate* isolate = CcTest::isolate();
2152
  LocalContext env;
2153 2154
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
2155 2156 2157 2158

  CompileRun(
      "function C(x) { this.a = this; this.b = x; }\n"
      "c = new C(2012);\n");
2159
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2160
  CHECK(ValidateSnapshot(snapshot));
2161 2162
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* c =
2163
      GetProperty(isolate, global, v8::HeapGraphEdge::kProperty, "c");
2164
  CHECK(c);
2165
  const v8::HeapGraphNode* hidden_props =
2166
      GetProperty(isolate, global, v8::HeapGraphEdge::kProperty, "<symbol>");
2167
  CHECK(!hidden_props);
2168

2169 2170
  v8::Local<v8::Value> cHandle =
      env->Global()->Get(env.local(), v8_str("c")).ToLocalChecked();
2171
  CHECK(!cHandle.IsEmpty() && cHandle->IsObject());
2172 2173
  cHandle->ToObject(env.local())
      .ToLocalChecked()
2174 2175 2176 2177
      ->SetPrivate(env.local(),
                   v8::Private::ForApi(env->GetIsolate(), v8_str("key")),
                   v8_str("val"))
      .FromJust();
2178

2179
  snapshot = heap_profiler->TakeHeapSnapshot();
2180
  CHECK(ValidateSnapshot(snapshot));
2181
  global = GetGlobalObject(snapshot);
2182
  c = GetProperty(isolate, global, v8::HeapGraphEdge::kProperty, "c");
2183
  CHECK(c);
2184 2185
  hidden_props =
      GetProperty(isolate, c, v8::HeapGraphEdge::kProperty, "<symbol>");
2186
  CHECK(hidden_props);
2187
}
2188

2189

2190 2191 2192 2193 2194 2195
TEST(AccessorInfo) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun("function foo(x) { }\n");
2196
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2197 2198
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2199 2200
  const v8::HeapGraphNode* foo = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "foo");
2201
  CHECK(foo);
2202
  const v8::HeapGraphNode* map =
2203
      GetProperty(env->GetIsolate(), foo, v8::HeapGraphEdge::kInternal, "map");
2204
  CHECK(map);
2205 2206
  const v8::HeapGraphNode* descriptors = GetProperty(
      env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "descriptors");
2207
  CHECK(descriptors);
2208 2209
  const v8::HeapGraphNode* length_name = GetProperty(
      env->GetIsolate(), descriptors, v8::HeapGraphEdge::kInternal, "2");
2210
  CHECK(length_name);
2211 2212 2213 2214
  CHECK_EQ(0, strcmp("length", *v8::String::Utf8Value(env->GetIsolate(),
                                                      length_name->GetName())));
  const v8::HeapGraphNode* length_accessor = GetProperty(
      env->GetIsolate(), descriptors, v8::HeapGraphEdge::kInternal, "4");
2215
  CHECK(length_accessor);
2216
  CHECK_EQ(0, strcmp("system / AccessorInfo",
2217 2218 2219 2220
                     *v8::String::Utf8Value(env->GetIsolate(),
                                            length_accessor->GetName())));
  const v8::HeapGraphNode* name = GetProperty(
      env->GetIsolate(), length_accessor, v8::HeapGraphEdge::kInternal, "name");
2221
  CHECK(name);
2222
  const v8::HeapGraphNode* getter =
2223 2224
      GetProperty(env->GetIsolate(), length_accessor,
                  v8::HeapGraphEdge::kInternal, "getter");
2225
  CHECK(getter);
2226
  const v8::HeapGraphNode* setter =
2227 2228
      GetProperty(env->GetIsolate(), length_accessor,
                  v8::HeapGraphEdge::kInternal, "setter");
2229
  CHECK(setter);
2230 2231
}

2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
TEST(JSGeneratorObject) {
  v8::Isolate* isolate = CcTest::isolate();
  LocalContext env;
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();

  CompileRun(
      "function* foo() { yield 1; }\n"
      "g = foo();\n");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* g =
      GetProperty(isolate, global, v8::HeapGraphEdge::kProperty, "g");
  CHECK(g);
  const v8::HeapGraphNode* function = GetProperty(
      env->GetIsolate(), g, v8::HeapGraphEdge::kInternal, "function");
  CHECK(function);
  const v8::HeapGraphNode* context = GetProperty(
      env->GetIsolate(), g, v8::HeapGraphEdge::kInternal, "context");
  CHECK(context);
  const v8::HeapGraphNode* receiver = GetProperty(
      env->GetIsolate(), g, v8::HeapGraphEdge::kInternal, "receiver");
  CHECK(receiver);
  const v8::HeapGraphNode* parameters_and_registers =
      GetProperty(env->GetIsolate(), g, v8::HeapGraphEdge::kInternal,
                  "parameters_and_registers");
  CHECK(parameters_and_registers);
}
2261

2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
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() {
2272
  v8::Isolate* isolate = CcTest::isolate();
2273
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
2274
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2275
  CHECK(ValidateSnapshot(snapshot));
2276
  const v8::HeapGraphNode* gc_roots = GetNode(
2277
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "(GC roots)");
2278
  CHECK(gc_roots);
2279
  const v8::HeapGraphNode* global_handles = GetNode(
2280
      gc_roots, v8::HeapGraphNode::kSynthetic, "(Global handles)");
2281
  CHECK(global_handles);
2282 2283 2284 2285
  return HasWeakEdge(global_handles);
}


2286
static void PersistentHandleCallback(
2287
    const v8::WeakCallbackInfo<v8::Persistent<v8::Object> >& data) {
2288
  data.GetParameter()->Reset();
2289 2290 2291 2292 2293
}


TEST(WeakGlobalHandle) {
  LocalContext env;
2294
  v8::HandleScope scope(env->GetIsolate());
2295 2296 2297

  CHECK(!HasWeakGlobalHandle());

2298 2299 2300
  v8::Persistent<v8::Object> handle;

  handle.Reset(env->GetIsolate(), v8::Object::New(env->GetIsolate()));
2301 2302
  handle.SetWeak(&handle, PersistentHandleCallback,
                 v8::WeakCallbackType::kParameter);
2303 2304

  CHECK(HasWeakGlobalHandle());
2305 2306
  CcTest::CollectAllGarbage();
  EmptyMessageQueues(env->GetIsolate());
2307 2308 2309 2310 2311
}


TEST(SfiAndJsFunctionWeakRefs) {
  LocalContext env;
2312
  v8::HandleScope scope(env->GetIsolate());
2313
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2314 2315 2316

  CompileRun(
      "fun = (function (x) { return function () { return x + 1; } })(1);");
2317
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2318
  CHECK(ValidateSnapshot(snapshot));
2319
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2320
  CHECK(global);
2321 2322
  const v8::HeapGraphNode* fun = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "fun");
2323
  CHECK(!HasWeakEdge(fun));
2324 2325
  const v8::HeapGraphNode* shared = GetProperty(
      env->GetIsolate(), fun, v8::HeapGraphEdge::kInternal, "shared");
2326
  CHECK(!HasWeakEdge(shared));
2327
}
2328 2329


2330 2331
TEST(AllStrongGcRootsHaveNames) {
  LocalContext env;
2332
  v8::HandleScope scope(env->GetIsolate());
2333
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2334 2335

  CompileRun("foo = {};");
2336
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2337
  CHECK(ValidateSnapshot(snapshot));
2338
  const v8::HeapGraphNode* gc_roots = GetNode(
2339
      snapshot->GetRoot(), v8::HeapGraphNode::kSynthetic, "(GC roots)");
2340
  CHECK(gc_roots);
2341
  const v8::HeapGraphNode* strong_roots = GetNode(
2342
      gc_roots, v8::HeapGraphNode::kSynthetic, "(Strong roots)");
2343
  CHECK(strong_roots);
2344 2345 2346
  for (int i = 0; i < strong_roots->GetChildrenCount(); ++i) {
    const v8::HeapGraphEdge* edge = strong_roots->GetChild(i);
    CHECK_EQ(v8::HeapGraphEdge::kInternal, edge->GetType());
2347
    v8::String::Utf8Value name(env->GetIsolate(), edge->GetName());
2348 2349 2350
    CHECK(isalpha(**name));
  }
}
2351 2352 2353 2354


TEST(NoRefsToNonEssentialEntries) {
  LocalContext env;
2355
  v8::HandleScope scope(env->GetIsolate());
2356
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2357
  CompileRun("global_object = {};\n");
2358
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2359
  CHECK(ValidateSnapshot(snapshot));
2360
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2361 2362
  const v8::HeapGraphNode* global_object = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "global_object");
2363
  CHECK(global_object);
2364
  const v8::HeapGraphNode* properties =
2365 2366
      GetProperty(env->GetIsolate(), global_object,
                  v8::HeapGraphEdge::kInternal, "properties");
2367
  CHECK(!properties);
2368
  const v8::HeapGraphNode* elements =
2369 2370
      GetProperty(env->GetIsolate(), global_object,
                  v8::HeapGraphEdge::kInternal, "elements");
2371
  CHECK(!elements);
2372
}
2373 2374 2375 2376


TEST(MapHasDescriptorsAndTransitions) {
  LocalContext env;
2377
  v8::HandleScope scope(env->GetIsolate());
2378
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2379
  CompileRun("obj = { a: 10 };\n");
2380
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2381
  CHECK(ValidateSnapshot(snapshot));
2382
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2383 2384
  const v8::HeapGraphNode* global_object = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "obj");
2385
  CHECK(global_object);
2386

2387 2388
  const v8::HeapGraphNode* map = GetProperty(
      env->GetIsolate(), global_object, v8::HeapGraphEdge::kInternal, "map");
2389
  CHECK(map);
2390
  const v8::HeapGraphNode* own_descriptors = GetProperty(
2391
      env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "descriptors");
2392
  CHECK(own_descriptors);
2393
  const v8::HeapGraphNode* own_transitions = GetProperty(
2394
      env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "transitions");
2395
  CHECK(!own_transitions);
2396
}
2397 2398 2399 2400


TEST(ManyLocalsInSharedContext) {
  LocalContext env;
2401 2402
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2403
  int num_objects = 6000;
2404
  CompileRun(
2405
      "var n = 6000;"
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
      "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'));");
2418
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2419
  CHECK(ValidateSnapshot(snapshot));
2420

2421
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2422
  CHECK(global);
2423 2424
  const v8::HeapGraphNode* ok_object = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "ok");
2425
  CHECK(ok_object);
2426 2427
  const v8::HeapGraphNode* context_object = GetProperty(
      env->GetIsolate(), ok_object, v8::HeapGraphEdge::kInternal, "context");
2428
  CHECK(context_object);
2429 2430 2431 2432
  // 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.
2433 2434
  // ... 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
2435
    i::EmbeddedVector<char, 100> var_name;
2436
    i::SNPrintF(var_name, "f_%d", i);
2437 2438 2439
    const v8::HeapGraphNode* f_object =
        GetProperty(env->GetIsolate(), context_object,
                    v8::HeapGraphEdge::kContextVariable, var_name.start());
2440
    CHECK(f_object);
2441 2442
  }
}
2443 2444 2445 2446


TEST(AllocationSitesAreVisible) {
  LocalContext env;
2447 2448 2449
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
2450 2451 2452
  CompileRun(
      "fun = function () { var a = [3, 2, 1]; return a; }\n"
      "fun();");
2453
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2454
  CHECK(ValidateSnapshot(snapshot));
2455 2456

  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2457
  CHECK(global);
2458 2459
  const v8::HeapGraphNode* fun_code = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "fun");
2460
  CHECK(fun_code);
2461
  const v8::HeapGraphNode* feedback_cell =
2462
      GetProperty(env->GetIsolate(), fun_code, v8::HeapGraphEdge::kInternal,
2463 2464
                  "feedback_cell");
  CHECK(feedback_cell);
2465
  const v8::HeapGraphNode* vector = GetProperty(
2466
      env->GetIsolate(), feedback_cell, v8::HeapGraphEdge::kInternal, "value");
2467 2468 2469 2470
  CHECK_EQ(v8::HeapGraphNode::kArray, vector->GetType());
  CHECK_EQ(3, vector->GetChildrenCount());

  // The first value in the feedback vector should be the boilerplate,
2471
  // after an AllocationSite.
2472
  const v8::HeapGraphEdge* prop = vector->GetChild(2);
2473
  const v8::HeapGraphNode* allocation_site = prop->GetToNode();
2474
  v8::String::Utf8Value name(env->GetIsolate(), allocation_site->GetName());
2475
  CHECK_EQ(0, strcmp("system / AllocationSite", *name));
2476
  const v8::HeapGraphNode* transition_info =
2477 2478
      GetProperty(env->GetIsolate(), allocation_site,
                  v8::HeapGraphEdge::kInternal, "transition_info");
2479
  CHECK(transition_info);
2480 2481

  const v8::HeapGraphNode* elements =
2482 2483
      GetProperty(env->GetIsolate(), transition_info,
                  v8::HeapGraphEdge::kInternal, "elements");
2484
  CHECK(elements);
2485
  CHECK_EQ(v8::HeapGraphNode::kArray, elements->GetType());
2486 2487
  CHECK_EQ(v8::internal::FixedArray::SizeFor(3),
           static_cast<int>(elements->GetShallowSize()));
2488

2489
  v8::Local<v8::Value> array_val =
2490 2491
      heap_profiler->FindObjectById(transition_info->GetId());
  CHECK(array_val->IsArray());
2492
  v8::Local<v8::Array> array = v8::Local<v8::Array>::Cast(array_val);
2493
  // Verify the array is "a" in the code above.
2494 2495
  CHECK_EQ(3u, array->Length());
  CHECK(v8::Integer::New(isolate, 3)
2496 2497 2498 2499
            ->Equals(env.local(),
                     array->Get(env.local(), v8::Integer::New(isolate, 0))
                         .ToLocalChecked())
            .FromJust());
2500
  CHECK(v8::Integer::New(isolate, 2)
2501 2502 2503 2504
            ->Equals(env.local(),
                     array->Get(env.local(), v8::Integer::New(isolate, 1))
                         .ToLocalChecked())
            .FromJust());
2505
  CHECK(v8::Integer::New(isolate, 1)
2506 2507 2508 2509
            ->Equals(env.local(),
                     array->Get(env.local(), v8::Integer::New(isolate, 2))
                         .ToLocalChecked())
            .FromJust());
2510
}
2511 2512 2513 2514 2515 2516 2517


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");
2518
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2519 2520
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2521 2522
  const v8::HeapGraphNode* foo_func = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "foo");
2523
  CHECK(foo_func);
2524 2525
  const v8::HeapGraphNode* code = GetProperty(
      env->GetIsolate(), foo_func, v8::HeapGraphEdge::kInternal, "code");
2526
  CHECK(code);
2527
}
2528

2529 2530 2531
static const v8::HeapGraphNode* GetNodeByPath(v8::Isolate* isolate,
                                              const v8::HeapSnapshot* snapshot,
                                              const char* path[], int depth) {
2532 2533 2534 2535 2536 2537
  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();
2538 2539
      v8::String::Utf8Value edge_name(isolate, edge->GetName());
      v8::String::Utf8Value node_name(isolate, to_node->GetName());
2540
      i::EmbeddedVector<char, 100> name;
2541
      i::SNPrintF(name, "%s::%s", *edge_name, *node_name);
2542 2543 2544 2545 2546
      if (strstr(name.start(), path[current_depth])) {
        node = to_node;
        break;
      }
    }
2547
    if (i == count) return nullptr;
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
  }
  return node;
}


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

2561 2562
  const char* stub_path[] = {"::(GC roots)", "::(Strong roots)",
                             "code_stubs::", "::(StoreFastElementStub code)"};
2563 2564
  const v8::HeapGraphNode* node = GetNodeByPath(
      env->GetIsolate(), snapshot, stub_path, arraysize(stub_path));
2565
  CHECK(node);
2566

2567
  const char* builtin_path1[] = {"::(GC roots)", "::(Builtins)",
2568
                                 "::(KeyedLoadIC_Slow builtin)"};
2569 2570
  node = GetNodeByPath(env->GetIsolate(), snapshot, builtin_path1,
                       arraysize(builtin_path1));
2571
  CHECK(node);
2572

2573 2574
  const char* builtin_path2[] = {"::(GC roots)", "::(Builtins)",
                                 "::(CompileLazy builtin)"};
2575 2576
  node = GetNodeByPath(env->GetIsolate(), snapshot, builtin_path2,
                       arraysize(builtin_path2));
2577
  CHECK(node);
2578
  v8::String::Utf8Value node_name(env->GetIsolate(), node->GetName());
2579
  CHECK_EQ(0, strcmp("(CompileLazy builtin)", *node_name));
2580
}
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627


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();
2628
  for (int i = 0; node != nullptr && i < names.length(); i++) {
2629
    const char* name = names[i];
2630
    const std::vector<AllocationTraceNode*>& children = node->children();
2631
    node = nullptr;
2632 2633
    for (AllocationTraceNode* child : children) {
      unsigned index = child->function_info_index();
2634 2635
      AllocationTracker::FunctionInfo* info =
          tracker->function_info_list()[index];
2636
      if (info && strcmp(info->name, name) == 0) {
2637
        node = child;
2638 2639 2640 2641 2642 2643 2644 2645
        break;
      }
    }
  }
  return node;
}


2646 2647 2648 2649
TEST(ArrayGrowLeftTrim) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2650
  heap_profiler->StartTrackingHeapObjects(true);
2651 2652 2653 2654 2655 2656 2657 2658

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

2659
  const char* names[] = {""};
2660 2661
  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2662
  CHECK(tracker);
2663 2664 2665 2666 2667
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

2668
  AllocationTraceNode* node = FindNode(tracker, ArrayVector(names));
2669 2670 2671
  CHECK(node);
  CHECK_GE(node->allocation_count(), 2u);
  CHECK_GE(node->allocation_size(), 4u * 5u);
2672
  heap_profiler->StopTrackingHeapObjects();
2673 2674
}

2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
TEST(TrackHeapAllocationsWithInlining) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

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

  CompileRun(record_trace_tree_source);

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

  const char* names[] = {"", "start", "f_0_0"};
  AllocationTraceNode* node = FindNode(tracker, ArrayVector(names));
  CHECK(node);
2695
  CHECK_GE(node->allocation_count(), 8u);
2696 2697 2698
  CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
  heap_profiler->StopTrackingHeapObjects();
}
2699

2700
TEST(TrackHeapAllocationsWithoutInlining) {
2701
  i::FLAG_turbo_inlining = false;
2702 2703 2704
  // Disable inlining
  i::FLAG_max_inlined_bytecode_size = 0;
  i::FLAG_max_inlined_bytecode_size_small = 0;
2705 2706 2707 2708
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2709
  heap_profiler->StartTrackingHeapObjects(true);
2710 2711 2712

  CompileRun(record_trace_tree_source);

2713 2714
  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2715
  CHECK(tracker);
2716 2717 2718 2719 2720
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

2721
  const char* names[] = {"", "start", "f_0_0", "f_0_1", "f_0_2"};
2722
  AllocationTraceNode* node = FindNode(tracker, ArrayVector(names));
2723 2724
  CHECK(node);
  CHECK_GE(node->allocation_count(), 100u);
2725
  CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
2726
  heap_profiler->StopTrackingHeapObjects();
2727
}
2728 2729 2730


static const char* inline_heap_allocation_source =
2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
    "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"
    "%NeverOptimizeFunction(f_1);\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";
2748 2749 2750 2751 2752 2753 2754 2755


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

  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
2756
  const char* names[] = {"", "start", "f_0", "f_1"};
2757 2758
  // First check that normally all allocations are recorded.
  {
2759
    heap_profiler->StartTrackingHeapObjects(true);
2760 2761 2762

    CompileRun(inline_heap_allocation_source);

2763 2764
    AllocationTracker* tracker =
        reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2765
    CHECK(tracker);
2766 2767 2768 2769 2770
    // Resolve all function locations.
    tracker->PrepareForSerialization();
    // Print for better diagnostics in case of failure.
    tracker->trace_tree()->Print(tracker);

2771
    AllocationTraceNode* node = FindNode(tracker, ArrayVector(names));
2772 2773
    CHECK(node);
    CHECK_GE(node->allocation_count(), 100u);
2774
    CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
2775
    heap_profiler->StopTrackingHeapObjects();
2776 2777 2778
  }

  {
2779
    heap_profiler->StartTrackingHeapObjects(true);
2780 2781 2782 2783 2784 2785 2786 2787

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

2788 2789
    AllocationTracker* tracker =
        reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2790
    CHECK(tracker);
2791 2792 2793 2794 2795
    // Resolve all function locations.
    tracker->PrepareForSerialization();
    // Print for better diagnostics in case of failure.
    tracker->trace_tree()->Print(tracker);

2796
    AllocationTraceNode* node = FindNode(tracker, ArrayVector(names));
2797 2798
    CHECK(node);
    CHECK_LT(node->allocation_count(), 100u);
2799 2800

    CcTest::heap()->DisableInlineAllocation();
2801
    heap_profiler->StopTrackingHeapObjects();
2802 2803
  }
}
2804 2805


2806 2807 2808 2809 2810 2811 2812 2813
TEST(TrackV8ApiAllocation) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;

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

2814
  v8::Local<v8::Object> o1 = v8::Object::New(env->GetIsolate());
2815 2816 2817 2818
  o1->Clone();

  AllocationTracker* tracker =
      reinterpret_cast<i::HeapProfiler*>(heap_profiler)->allocation_tracker();
2819
  CHECK(tracker);
2820 2821 2822 2823 2824
  // Resolve all function locations.
  tracker->PrepareForSerialization();
  // Print for better diagnostics in case of failure.
  tracker->trace_tree()->Print(tracker);

2825
  AllocationTraceNode* node = FindNode(tracker, ArrayVector(names));
2826 2827
  CHECK(node);
  CHECK_GE(node->allocation_count(), 2u);
2828 2829 2830 2831 2832
  CHECK_GE(node->allocation_size(), 4 * node->allocation_count());
  heap_profiler->StopTrackingHeapObjects();
}


2833 2834 2835 2836 2837
TEST(ArrayBufferAndArrayBufferView) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun("arr1 = new Uint32Array(100);\n");
2838
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2839 2840
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2841 2842
  const v8::HeapGraphNode* arr1_obj = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "arr1");
2843
  CHECK(arr1_obj);
2844 2845
  const v8::HeapGraphNode* arr1_buffer = GetProperty(
      env->GetIsolate(), arr1_obj, v8::HeapGraphEdge::kInternal, "buffer");
2846
  CHECK(arr1_buffer);
2847
  const v8::HeapGraphNode* backing_store =
2848 2849
      GetProperty(env->GetIsolate(), arr1_buffer, v8::HeapGraphEdge::kInternal,
                  "backing_store");
2850
  CHECK(backing_store);
2851
  CHECK_EQ(400, static_cast<int>(backing_store->GetShallowSize()));
2852
}
2853 2854


2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
static int GetRetainersCount(const v8::HeapSnapshot* snapshot,
                             const v8::HeapGraphNode* node) {
  int count = 0;
  for (int i = 0, l = snapshot->GetNodesCount(); i < l; ++i) {
    const v8::HeapGraphNode* parent = snapshot->GetNode(i);
    for (int j = 0, l2 = parent->GetChildrenCount(); j < l2; ++j) {
      if (parent->GetChild(j)->GetToNode() == node) {
        ++count;
      }
    }
  }
  return count;
}


TEST(ArrayBufferSharedBackingStore) {
  LocalContext env;
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope handle_scope(isolate);
  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();

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

  CHECK_EQ(1024, static_cast<int>(ab_contents.ByteLength()));
  void* data = ab_contents.Data();
2884
  CHECK_NOT_NULL(data);
2885 2886 2887
  v8::Local<v8::ArrayBuffer> ab2 =
      v8::ArrayBuffer::New(isolate, data, ab_contents.ByteLength());
  CHECK(ab2->IsExternal());
2888 2889
  env->Global()->Set(env.local(), v8_str("ab1"), ab).FromJust();
  env->Global()->Set(env.local(), v8_str("ab2"), ab2).FromJust();
2890

2891 2892
  v8::Local<v8::Value> result = CompileRun("ab2.byteLength");
  CHECK_EQ(1024, result->Int32Value(env.local()).FromJust());
2893

2894
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2895
  CHECK(ValidateSnapshot(snapshot));
2896
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2897 2898
  const v8::HeapGraphNode* ab1_node = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "ab1");
2899
  CHECK(ab1_node);
2900
  const v8::HeapGraphNode* ab1_data =
2901 2902
      GetProperty(env->GetIsolate(), ab1_node, v8::HeapGraphEdge::kInternal,
                  "backing_store");
2903
  CHECK(ab1_data);
2904 2905
  const v8::HeapGraphNode* ab2_node = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "ab2");
2906
  CHECK(ab2_node);
2907
  const v8::HeapGraphNode* ab2_data =
2908 2909
      GetProperty(env->GetIsolate(), ab2_node, v8::HeapGraphEdge::kInternal,
                  "backing_store");
2910
  CHECK(ab2_data);
2911 2912 2913
  CHECK_EQ(ab1_data, ab2_data);
  CHECK_EQ(2, GetRetainersCount(snapshot, ab1_data));
  free(data);
2914 2915 2916
}


2917 2918 2919 2920
TEST(WeakContainers) {
  i::FLAG_allow_natives_syntax = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
Mythri's avatar
Mythri committed
2921
  if (!CcTest::i_isolate()->use_optimizer()) return;
2922 2923 2924 2925 2926 2927 2928 2929
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun(
      "function foo(a) { return a.x; }\n"
      "obj = {x : 123};\n"
      "foo(obj);\n"
      "foo(obj);\n"
      "%OptimizeFunctionOnNextCall(foo);\n"
      "foo(obj);\n");
2930
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
2931 2932
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
2933 2934
  const v8::HeapGraphNode* obj = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "obj");
2935
  CHECK(obj);
2936
  const v8::HeapGraphNode* map =
2937
      GetProperty(env->GetIsolate(), obj, v8::HeapGraphEdge::kInternal, "map");
2938
  CHECK(map);
2939 2940
  const v8::HeapGraphNode* dependent_code = GetProperty(
      env->GetIsolate(), map, v8::HeapGraphEdge::kInternal, "dependent_code");
2941 2942 2943 2944 2945
  if (!dependent_code) return;
  int count = dependent_code->GetChildrenCount();
  CHECK_NE(0, count);
  for (int i = 0; i < count; ++i) {
    const v8::HeapGraphEdge* prop = dependent_code->GetChild(i);
2946
    CHECK_EQ(v8::HeapGraphEdge::kInternal, prop->GetType());
2947 2948 2949
  }
}

2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
TEST(JSPromise) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun(
      "function A() {}\n"
      "function B() {}\n"
      "resolved = Promise.resolve(new A());\n"
      "rejected = Promise.reject(new B());\n"
      "pending = new Promise(() => 0);\n"
      "chained = pending.then(A, B);\n");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);

2965 2966 2967
  const v8::HeapGraphNode* resolved = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "resolved");
  CHECK(GetProperty(env->GetIsolate(), resolved, v8::HeapGraphEdge::kInternal,
2968
                    "reactions_or_result"));
2969 2970 2971 2972

  const v8::HeapGraphNode* rejected = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "rejected");
  CHECK(GetProperty(env->GetIsolate(), rejected, v8::HeapGraphEdge::kInternal,
2973
                    "reactions_or_result"));
2974 2975 2976 2977

  const v8::HeapGraphNode* pending = GetProperty(
      env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, "pending");
  CHECK(GetProperty(env->GetIsolate(), pending, v8::HeapGraphEdge::kInternal,
2978
                    "reactions_or_result"));
2979 2980 2981

  const char* objectNames[] = {"resolved", "rejected", "pending", "chained"};
  for (auto objectName : objectNames) {
2982 2983 2984
    const v8::HeapGraphNode* promise = GetProperty(
        env->GetIsolate(), global, v8::HeapGraphEdge::kProperty, objectName);
    EnsureNoUninstrumentedInternals(env->GetIsolate(), promise);
2985 2986
  }
}
2987

2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
TEST(HeapSnapshotScriptContext) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  CompileRun("class Foo{}; const foo = new Foo();");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* native_context =
      GetProperty(env->GetIsolate(), global, v8::HeapGraphEdge::kInternal,
                  "native_context");
  CHECK(native_context);
  const v8::HeapGraphNode* script_context_table =
      GetProperty(env->GetIsolate(), native_context,
                  v8::HeapGraphEdge::kInternal, "script_context_table");
  CHECK(script_context_table);
  bool found_foo = false;
  for (int i = 0, count = script_context_table->GetChildrenCount(); i < count;
       ++i) {
    const v8::HeapGraphNode* context =
        script_context_table->GetChild(i)->GetToNode();
    const v8::HeapGraphNode* foo = GetProperty(
        env->GetIsolate(), context, v8::HeapGraphEdge::kContextVariable, "foo");
    if (foo) {
      found_foo = true;
    }
  }
  CHECK(found_foo);
}

3019 3020
class EmbedderNode : public v8::EmbedderGraph::Node {
 public:
3021 3022 3023
  EmbedderNode(const char* name, size_t size,
               v8::EmbedderGraph::Node* wrapper_node = nullptr)
      : name_(name), size_(size), wrapper_node_(wrapper_node) {}
3024 3025 3026 3027

  // Graph::Node overrides.
  const char* Name() override { return name_; }
  size_t SizeInBytes() override { return size_; }
3028
  Node* WrapperNode() override { return wrapper_node_; }
3029 3030 3031 3032

 private:
  const char* name_;
  size_t size_;
3033
  Node* wrapper_node_;
3034 3035 3036 3037 3038 3039
};

class EmbedderRootNode : public EmbedderNode {
 public:
  explicit EmbedderRootNode(const char* name) : EmbedderNode(name, 0) {}
  // Graph::Node override.
3040
  bool IsRootNode() override { return true; }
3041 3042 3043 3044 3045 3046 3047
};

// Used to pass the global object to the BuildEmbedderGraph callback.
// Otherwise, the callback has to iterate the global handles to find the
// global object.
v8::Local<v8::Value>* global_object_pointer;

3048 3049
void BuildEmbedderGraph(v8::Isolate* v8_isolate, v8::EmbedderGraph* graph,
                        void* data) {
3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086
  using Node = v8::EmbedderGraph::Node;
  Node* global_node = graph->V8Node(*global_object_pointer);
  Node* embedder_node_A = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeA", 10)));
  Node* embedder_node_B = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeB", 20)));
  Node* embedder_node_C = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeC", 30)));
  Node* embedder_root = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderRootNode("EmbedderRoot")));
  graph->AddEdge(global_node, embedder_node_A);
  graph->AddEdge(embedder_node_A, embedder_node_B);
  graph->AddEdge(embedder_root, embedder_node_C);
  graph->AddEdge(embedder_node_C, global_node);
}

void CheckEmbedderGraphSnapshot(v8::Isolate* isolate,
                                const v8::HeapSnapshot* snapshot) {
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* embedder_node_A =
      GetChildByName(global, "EmbedderNodeA");
  CHECK_EQ(10, GetSize(embedder_node_A));
  const v8::HeapGraphNode* embedder_node_B =
      GetChildByName(embedder_node_A, "EmbedderNodeB");
  CHECK_EQ(20, GetSize(embedder_node_B));
  const v8::HeapGraphNode* embedder_root =
      GetRootChild(snapshot, "EmbedderRoot");
  CHECK(embedder_root);
  const v8::HeapGraphNode* embedder_node_C =
      GetChildByName(embedder_root, "EmbedderNodeC");
  CHECK_EQ(30, GetSize(embedder_node_C));
  const v8::HeapGraphNode* global_reference =
      GetChildByName(embedder_node_C, "Object");
  CHECK(global_reference);
}

TEST(EmbedderGraph) {
3087
  i::FLAG_heap_profiler_use_embedder_graph = true;
3088 3089 3090 3091 3092
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
  v8::Local<v8::Value> global_object =
      v8::Utils::ToLocal(i::Handle<i::JSObject>(
3093
          (isolate->context()->native_context()->global_object()), isolate));
3094 3095
  global_object_pointer = &global_object;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
3096
  heap_profiler->AddBuildEmbedderGraphCallback(BuildEmbedderGraph, nullptr);
3097 3098 3099 3100 3101
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  CheckEmbedderGraphSnapshot(env->GetIsolate(), snapshot);
}

3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
void BuildEmbedderGraphWithNamedEdges(v8::Isolate* v8_isolate,
                                      v8::EmbedderGraph* graph, void* data) {
  using Node = v8::EmbedderGraph::Node;
  Node* global_node = graph->V8Node(*global_object_pointer);
  Node* embedder_node_A = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeA", 10)));
  Node* embedder_node_B = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeB", 20)));
  Node* embedder_node_C = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeC", 30)));
  graph->AddEdge(global_node, embedder_node_A, "global_to_a");
  graph->AddEdge(embedder_node_A, embedder_node_B, "a_to_b");
  graph->AddEdge(embedder_node_B, embedder_node_C);
}

void CheckEmbedderGraphWithNamedEdges(v8::Isolate* isolate,
                                      const v8::HeapSnapshot* snapshot) {
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphEdge* global_to_a =
      GetEdgeByChildName(global, "EmbedderNodeA");
  CHECK(global_to_a);
  CHECK_EQ(v8::HeapGraphEdge::kInternal, global_to_a->GetType());
  CHECK(global_to_a->GetName()->IsString());
  CHECK_EQ(0, strcmp("global_to_a", GetName(global_to_a)));
  const v8::HeapGraphNode* embedder_node_A = global_to_a->GetToNode();
  CHECK_EQ(0, strcmp("EmbedderNodeA", GetName(embedder_node_A)));
  CHECK_EQ(10, GetSize(embedder_node_A));

  const v8::HeapGraphEdge* a_to_b =
      GetEdgeByChildName(embedder_node_A, "EmbedderNodeB");
  CHECK(a_to_b);
  CHECK(a_to_b->GetName()->IsString());
  CHECK_EQ(0, strcmp("a_to_b", GetName(a_to_b)));
  CHECK_EQ(v8::HeapGraphEdge::kInternal, a_to_b->GetType());
  const v8::HeapGraphNode* embedder_node_B = a_to_b->GetToNode();
  CHECK_EQ(0, strcmp("EmbedderNodeB", GetName(embedder_node_B)));
  CHECK_EQ(20, GetSize(embedder_node_B));

  const v8::HeapGraphEdge* b_to_c =
      GetEdgeByChildName(embedder_node_B, "EmbedderNodeC");
  CHECK(b_to_c);
  CHECK(b_to_c->GetName()->IsNumber());
  CHECK_EQ(v8::HeapGraphEdge::kElement, b_to_c->GetType());
  const v8::HeapGraphNode* embedder_node_C = b_to_c->GetToNode();
  CHECK_EQ(0, strcmp("EmbedderNodeC", GetName(embedder_node_C)));
  CHECK_EQ(30, GetSize(embedder_node_C));
}

TEST(EmbedderGraphWithNamedEdges) {
  i::FLAG_heap_profiler_use_embedder_graph = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
  v8::Local<v8::Value> global_object =
      v8::Utils::ToLocal(i::Handle<i::JSObject>(
          (isolate->context()->native_context()->global_object()), isolate));
  global_object_pointer = &global_object;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  heap_profiler->AddBuildEmbedderGraphCallback(BuildEmbedderGraphWithNamedEdges,
                                               nullptr);
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  CheckEmbedderGraphWithNamedEdges(env->GetIsolate(), snapshot);
}

3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222
struct GraphBuildingContext {
  int counter = 0;
};

void CheckEmbedderGraphSnapshotWithContext(
    v8::Isolate* isolate, const v8::HeapSnapshot* snapshot,
    const GraphBuildingContext* context) {
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  CHECK_GE(context->counter, 1);
  CHECK_LE(context->counter, 2);

  const v8::HeapGraphNode* embedder_node_A =
      GetChildByName(global, "EmbedderNodeA");
  CHECK_EQ(10, GetSize(embedder_node_A));

  const v8::HeapGraphNode* embedder_node_B =
      GetChildByName(global, "EmbedderNodeB");
  if (context->counter == 2) {
    CHECK_NOT_NULL(embedder_node_B);
    CHECK_EQ(20, GetSize(embedder_node_B));
  } else {
    CHECK_NULL(embedder_node_B);
  }
}

void BuildEmbedderGraphWithContext(v8::Isolate* v8_isolate,
                                   v8::EmbedderGraph* graph, void* data) {
  using Node = v8::EmbedderGraph::Node;
  GraphBuildingContext* context = static_cast<GraphBuildingContext*>(data);
  Node* global_node = graph->V8Node(*global_object_pointer);

  CHECK_GE(context->counter, 0);
  CHECK_LE(context->counter, 1);
  switch (context->counter++) {
    case 0: {
      Node* embedder_node_A = graph->AddNode(
          std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeA", 10)));
      graph->AddEdge(global_node, embedder_node_A);
      break;
    }
    case 1: {
      Node* embedder_node_B = graph->AddNode(
          std::unique_ptr<Node>(new EmbedderNode("EmbedderNodeB", 20)));
      graph->AddEdge(global_node, embedder_node_B);
      break;
    }
  }
}

TEST(EmbedderGraphMultipleCallbacks) {
  i::FLAG_heap_profiler_use_embedder_graph = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
  v8::Local<v8::Value> global_object =
      v8::Utils::ToLocal(i::Handle<i::JSObject>(
3223
          (isolate->context()->native_context()->global_object()), isolate));
3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
  global_object_pointer = &global_object;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  GraphBuildingContext context;

  heap_profiler->AddBuildEmbedderGraphCallback(BuildEmbedderGraphWithContext,
                                               &context);
  heap_profiler->AddBuildEmbedderGraphCallback(BuildEmbedderGraphWithContext,
                                               &context);
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK_EQ(context.counter, 2);
  CHECK(ValidateSnapshot(snapshot));
  CheckEmbedderGraphSnapshotWithContext(env->GetIsolate(), snapshot, &context);

  heap_profiler->RemoveBuildEmbedderGraphCallback(BuildEmbedderGraphWithContext,
                                                  &context);
  context.counter = 0;

  snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK_EQ(context.counter, 1);
  CHECK(ValidateSnapshot(snapshot));
  CheckEmbedderGraphSnapshotWithContext(env->GetIsolate(), snapshot, &context);
}

3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
TEST(StrongHandleAnnotation) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::Persistent<v8::Object> handle1, handle2;
  handle1.Reset(env->GetIsolate(), v8::Object::New(env->GetIsolate()));
  handle2.Reset(env->GetIsolate(), v8::Object::New(env->GetIsolate()));
  handle1.AnnotateStrongRetainer("my_label");
  handle2.AnnotateStrongRetainer("my_label");
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  const v8::HeapGraphNode* gc_roots = GetRootChild(snapshot, "(GC roots)");
  CHECK(gc_roots);
  const v8::HeapGraphNode* global_handles =
      GetChildByName(gc_roots, "(Global handles)");
  CHECK(global_handles);
  int found = 0;
  for (int i = 0, count = global_handles->GetChildrenCount(); i < count; ++i) {
    const v8::HeapGraphEdge* edge = global_handles->GetChild(i);
    v8::String::Utf8Value edge_name(CcTest::isolate(), edge->GetName());
    if (EndsWith(*edge_name, "my_label")) ++found;
  }
  CHECK_EQ(2, found);
}

3271
void BuildEmbedderGraphWithWrapperNode(v8::Isolate* v8_isolate,
3272
                                       v8::EmbedderGraph* graph, void* data) {
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282
  using Node = v8::EmbedderGraph::Node;
  Node* global_node = graph->V8Node(*global_object_pointer);
  Node* wrapper_node = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("WrapperNode / TAG", 10)));
  Node* embedder_node = graph->AddNode(std::unique_ptr<Node>(
      new EmbedderNode("EmbedderNode", 10, wrapper_node)));
  Node* other_node =
      graph->AddNode(std::unique_ptr<Node>(new EmbedderNode("OtherNode", 20)));
  graph->AddEdge(global_node, embedder_node);
  graph->AddEdge(wrapper_node, other_node);
3283 3284 3285 3286 3287 3288 3289 3290

  Node* wrapper_node2 = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNode("WrapperNode2", 10)));
  Node* embedder_node2 = graph->AddNode(std::unique_ptr<Node>(
      new EmbedderNode("EmbedderNode2", 10, wrapper_node2)));
  graph->AddEdge(global_node, embedder_node2);
  graph->AddEdge(embedder_node2, wrapper_node2);
  graph->AddEdge(wrapper_node2, other_node);
3291 3292 3293 3294 3295 3296 3297 3298 3299
}

TEST(EmbedderGraphWithWrapperNode) {
  i::FLAG_heap_profiler_use_embedder_graph = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
  v8::Local<v8::Value> global_object =
      v8::Utils::ToLocal(i::Handle<i::JSObject>(
3300
          (isolate->context()->native_context()->global_object()), isolate));
3301 3302
  global_object_pointer = &global_object;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
3303 3304
  heap_profiler->AddBuildEmbedderGraphCallback(
      BuildEmbedderGraphWithWrapperNode, nullptr);
3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* embedder_node =
      GetChildByName(global, "EmbedderNode / TAG");
  const v8::HeapGraphNode* other_node =
      GetChildByName(embedder_node, "OtherNode");
  CHECK(other_node);
  const v8::HeapGraphNode* wrapper_node =
      GetChildByName(embedder_node, "WrapperNode / TAG");
  CHECK(!wrapper_node);
3316 3317 3318 3319 3320 3321 3322 3323

  const v8::HeapGraphNode* embedder_node2 =
      GetChildByName(global, "EmbedderNode2");
  other_node = GetChildByName(embedder_node2, "OtherNode");
  CHECK(other_node);
  const v8::HeapGraphNode* wrapper_node2 =
      GetChildByName(embedder_node, "WrapperNode2");
  CHECK(!wrapper_node2);
3324 3325
}

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
class EmbedderNodeWithPrefix : public v8::EmbedderGraph::Node {
 public:
  EmbedderNodeWithPrefix(const char* prefix, const char* name)
      : prefix_(prefix), name_(name) {}

  // Graph::Node overrides.
  const char* Name() override { return name_; }
  size_t SizeInBytes() override { return 0; }
  const char* NamePrefix() override { return prefix_; }

 private:
  const char* prefix_;
  const char* name_;
};

void BuildEmbedderGraphWithPrefix(v8::Isolate* v8_isolate,
3342
                                  v8::EmbedderGraph* graph, void* data) {
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
  using Node = v8::EmbedderGraph::Node;
  Node* global_node = graph->V8Node(*global_object_pointer);
  Node* node = graph->AddNode(
      std::unique_ptr<Node>(new EmbedderNodeWithPrefix("Detached", "Node")));
  graph->AddEdge(global_node, node);
}

TEST(EmbedderGraphWithPrefix) {
  i::FLAG_heap_profiler_use_embedder_graph = true;
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
  v8::Local<v8::Value> global_object =
      v8::Utils::ToLocal(i::Handle<i::JSObject>(
3357
          (isolate->context()->native_context()->global_object()), isolate));
3358 3359
  global_object_pointer = &global_object;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
3360 3361
  heap_profiler->AddBuildEmbedderGraphCallback(BuildEmbedderGraphWithPrefix,
                                               nullptr);
3362 3363 3364 3365 3366 3367 3368
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
  const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
  const v8::HeapGraphNode* node = GetChildByName(global, "Detached Node");
  CHECK(node);
}

3369
static inline i::Address ToAddress(int n) { return static_cast<i::Address>(n); }
3370 3371 3372 3373

TEST(AddressToTraceMap) {
  i::AddressToTraceMap map;

3374
  CHECK_EQ(0u, map.GetTraceNodeId(ToAddress(150)));
3375 3376 3377

  // [0x100, 0x200) -> 1
  map.AddRange(ToAddress(0x100), 0x100, 1U);
3378 3379 3380 3381 3382
  CHECK_EQ(0u, map.GetTraceNodeId(ToAddress(0x50)));
  CHECK_EQ(1u, map.GetTraceNodeId(ToAddress(0x100)));
  CHECK_EQ(1u, map.GetTraceNodeId(ToAddress(0x150)));
  CHECK_EQ(0u, map.GetTraceNodeId(ToAddress(0x100 + 0x100)));
  CHECK_EQ(1u, map.size());
3383 3384 3385

  // [0x100, 0x200) -> 1, [0x200, 0x300) -> 2
  map.AddRange(ToAddress(0x200), 0x100, 2U);
3386
  CHECK_EQ(2u, map.GetTraceNodeId(ToAddress(0x2A0)));
3387
  CHECK_EQ(2u, map.size());
3388 3389 3390

  // [0x100, 0x180) -> 1, [0x180, 0x280) -> 3, [0x280, 0x300) -> 2
  map.AddRange(ToAddress(0x180), 0x100, 3U);
3391 3392 3393 3394
  CHECK_EQ(1u, map.GetTraceNodeId(ToAddress(0x17F)));
  CHECK_EQ(2u, map.GetTraceNodeId(ToAddress(0x280)));
  CHECK_EQ(3u, map.GetTraceNodeId(ToAddress(0x180)));
  CHECK_EQ(3u, map.size());
3395 3396 3397 3398

  // [0x100, 0x180) -> 1, [0x180, 0x280) -> 3, [0x280, 0x300) -> 2,
  // [0x400, 0x500) -> 4
  map.AddRange(ToAddress(0x400), 0x100, 4U);
3399 3400 3401 3402 3403 3404 3405
  CHECK_EQ(1u, map.GetTraceNodeId(ToAddress(0x17F)));
  CHECK_EQ(2u, map.GetTraceNodeId(ToAddress(0x280)));
  CHECK_EQ(3u, map.GetTraceNodeId(ToAddress(0x180)));
  CHECK_EQ(4u, map.GetTraceNodeId(ToAddress(0x450)));
  CHECK_EQ(0u, map.GetTraceNodeId(ToAddress(0x500)));
  CHECK_EQ(0u, map.GetTraceNodeId(ToAddress(0x350)));
  CHECK_EQ(4u, map.size());
3406 3407 3408

  // [0x100, 0x180) -> 1, [0x180, 0x200) -> 3, [0x200, 0x600) -> 5
  map.AddRange(ToAddress(0x200), 0x400, 5U);
3409 3410 3411
  CHECK_EQ(5u, map.GetTraceNodeId(ToAddress(0x200)));
  CHECK_EQ(5u, map.GetTraceNodeId(ToAddress(0x400)));
  CHECK_EQ(3u, map.size());
3412 3413 3414 3415

  // [0x100, 0x180) -> 1, [0x180, 0x200) -> 7, [0x200, 0x600) ->5
  map.AddRange(ToAddress(0x180), 0x80, 6U);
  map.AddRange(ToAddress(0x180), 0x80, 7U);
3416 3417 3418
  CHECK_EQ(7u, map.GetTraceNodeId(ToAddress(0x180)));
  CHECK_EQ(5u, map.GetTraceNodeId(ToAddress(0x200)));
  CHECK_EQ(3u, map.size());
3419 3420

  map.Clear();
3421 3422
  CHECK_EQ(0u, map.size());
  CHECK_EQ(0u, map.GetTraceNodeId(ToAddress(0x400)));
3423
}
3424 3425

static const v8::AllocationProfile::Node* FindAllocationProfileNode(
3426 3427
    v8::Isolate* isolate, v8::AllocationProfile& profile,
    const Vector<const char*>& names) {
3428 3429 3430 3431 3432 3433
  v8::AllocationProfile::Node* node = profile.GetRootNode();
  for (int i = 0; node != nullptr && i < names.length(); ++i) {
    const char* name = names[i];
    auto children = node->children;
    node = nullptr;
    for (v8::AllocationProfile::Node* child : children) {
3434
      v8::String::Utf8Value child_name(isolate, child->name);
3435 3436 3437 3438 3439 3440 3441 3442 3443
      if (strcmp(*child_name, name) == 0) {
        node = child;
        break;
      }
    }
  }
  return node;
}

3444 3445 3446 3447 3448 3449 3450 3451 3452
static void CheckNoZeroCountNodes(v8::AllocationProfile::Node* node) {
  for (auto alloc : node->allocations) {
    CHECK_GT(alloc.count, 0u);
  }
  for (auto child : node->children) {
    CheckNoZeroCountNodes(child);
  }
}

3453 3454 3455 3456 3457 3458 3459 3460
static int NumberOfAllocations(const v8::AllocationProfile::Node* node) {
  int count = 0;
  for (auto allocation : node->allocations) {
    count += allocation.count;
  }
  return count;
}

3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
static const char* simple_sampling_heap_profiler_script =
    "var A = [];\n"
    "function bar(size) { return new Array(size); }\n"
    "var foo = function() {\n"
    "  for (var i = 0; i < 1024; ++i) {\n"
    "    A[i] = bar(1024);\n"
    "  }\n"
    "}\n"
    "foo();";

3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485
TEST(SamplingHeapProfiler) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  // Turn off always_opt. Inlining can cause stack traces to be shorter than
  // what we expect in this test.
  v8::internal::FLAG_always_opt = false;

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  // Sample should be empty if requested before sampling has started.
  {
    v8::AllocationProfile* profile = heap_profiler->GetAllocationProfile();
3486
    CHECK_NULL(profile);
3487 3488 3489
  }

  {
3490
    heap_profiler->StartSamplingHeapProfiler(1024);
3491
    CompileRun(simple_sampling_heap_profiler_script);
3492

3493
    std::unique_ptr<v8::AllocationProfile> profile(
3494
        heap_profiler->GetAllocationProfile());
3495
    CHECK(profile);
3496 3497

    const char* names[] = {"", "foo", "bar"};
3498 3499
    auto node_bar = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                              ArrayVector(names));
3500 3501 3502 3503 3504 3505 3506 3507
    CHECK(node_bar);

    heap_profiler->StopSamplingHeapProfiler();
  }

  // Samples should get cleared once sampling is stopped.
  {
    v8::AllocationProfile* profile = heap_profiler->GetAllocationProfile();
3508
    CHECK_NULL(profile);
3509 3510 3511 3512 3513 3514 3515 3516
  }

  // A more complicated test cases with deeper call graph and dynamically
  // generated function names.
  {
    heap_profiler->StartSamplingHeapProfiler(64);
    CompileRun(record_trace_tree_source);

3517
    std::unique_ptr<v8::AllocationProfile> profile(
3518
        heap_profiler->GetAllocationProfile());
3519
    CHECK(profile);
3520 3521

    const char* names1[] = {"", "start", "f_0_0", "f_0_1", "f_0_2"};
3522 3523
    auto node1 = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                           ArrayVector(names1));
3524 3525 3526
    CHECK(node1);

    const char* names2[] = {"", "generateFunctions"};
3527 3528
    auto node2 = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                           ArrayVector(names2));
3529 3530 3531 3532
    CHECK(node2);

    heap_profiler->StopSamplingHeapProfiler();
  }
3533 3534 3535 3536 3537 3538 3539 3540 3541

  // A test case with scripts unloaded before profile gathered
  {
    heap_profiler->StartSamplingHeapProfiler(64);
    CompileRun(
        "for (var i = 0; i < 1024; i++) {\n"
        "  eval(\"new Array(100)\");\n"
        "}\n");

3542
    CcTest::CollectAllGarbage();
3543

3544
    std::unique_ptr<v8::AllocationProfile> profile(
3545
        heap_profiler->GetAllocationProfile());
3546
    CHECK(profile);
3547

3548 3549
    CheckNoZeroCountNodes(profile->GetRootNode());

3550 3551
    heap_profiler->StopSamplingHeapProfiler();
  }
3552 3553
}

3554 3555 3556 3557 3558 3559 3560 3561 3562
TEST(SamplingHeapProfilerRateAgnosticEstimates) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  // Turn off always_opt. Inlining can cause stack traces to be shorter than
  // what we expect in this test.
  v8::internal::FLAG_always_opt = false;

3563 3564 3565
  // Disable compilation cache to force compilation in both cases
  v8::internal::FLAG_compilation_cache = false;

3566 3567 3568 3569 3570 3571
  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  // stress_incremental_marking adds randomness to the test.
  v8::internal::FLAG_stress_incremental_marking = false;

3572 3573 3574
  // warmup compilation
  CompileRun(simple_sampling_heap_profiler_script);

3575 3576 3577 3578 3579 3580 3581 3582 3583
  int count_1024 = 0;
  {
    heap_profiler->StartSamplingHeapProfiler(1024);
    CompileRun(simple_sampling_heap_profiler_script);

    std::unique_ptr<v8::AllocationProfile> profile(
        heap_profiler->GetAllocationProfile());
    CHECK(profile);

3584 3585 3586 3587 3588
    const char* path_to_foo[] = {"", "foo"};
    auto node_foo = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                              ArrayVector(path_to_foo));
    CHECK(node_foo);
    const char* path_to_bar[] = {"", "foo", "bar"};
3589
    auto node_bar = FindAllocationProfileNode(env->GetIsolate(), *profile,
3590
                                              ArrayVector(path_to_bar));
3591 3592
    CHECK(node_bar);

3593 3594
    // Function bar can be inlined in foo.
    count_1024 = NumberOfAllocations(node_foo) + NumberOfAllocations(node_bar);
3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607

    heap_profiler->StopSamplingHeapProfiler();
  }

  // Sampling at a higher rate should give us similar numbers of objects.
  {
    heap_profiler->StartSamplingHeapProfiler(128);
    CompileRun(simple_sampling_heap_profiler_script);

    std::unique_ptr<v8::AllocationProfile> profile(
        heap_profiler->GetAllocationProfile());
    CHECK(profile);

3608 3609 3610 3611 3612
    const char* path_to_foo[] = {"", "foo"};
    auto node_foo = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                              ArrayVector(path_to_foo));
    CHECK(node_foo);
    const char* path_to_bar[] = {"", "foo", "bar"};
3613
    auto node_bar = FindAllocationProfileNode(env->GetIsolate(), *profile,
3614
                                              ArrayVector(path_to_bar));
3615 3616
    CHECK(node_bar);

3617 3618 3619
    // Function bar can be inlined in foo.
    int count_128 =
        NumberOfAllocations(node_foo) + NumberOfAllocations(node_bar);
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629

    // We should have similar unsampled counts of allocations. Though
    // we will sample different numbers of objects at different rates,
    // the unsampling process should produce similar final estimates
    // at the true number of allocations. However, the process to
    // determine these unsampled counts is probabilisitic so we need to
    // account for error.
    double max_count = std::max(count_128, count_1024);
    double min_count = std::min(count_128, count_1024);
    double percent_difference = (max_count - min_count) / min_count;
3630
    CHECK_LT(percent_difference, 0.1);
3631 3632 3633 3634

    heap_profiler->StopSamplingHeapProfiler();
  }
}
3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647

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

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  heap_profiler->StartSamplingHeapProfiler(256);

  for (int i = 0; i < 8 * 1024; ++i) v8::Object::New(env->GetIsolate());

3648
  std::unique_ptr<v8::AllocationProfile> profile(
3649
      heap_profiler->GetAllocationProfile());
3650
  CHECK(profile);
3651
  const char* names[] = {"(V8 API)"};
3652 3653
  auto node = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                        ArrayVector(names));
3654 3655 3656 3657
  CHECK(node);

  heap_profiler->StopSamplingHeapProfiler();
}
3658

3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703
TEST(SamplingHeapProfilerApiSamples) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  heap_profiler->StartSamplingHeapProfiler(1024);

  size_t count = 8 * 1024;
  for (size_t i = 0; i < count; ++i) v8::Object::New(env->GetIsolate());

  std::unique_ptr<v8::AllocationProfile> profile(
      heap_profiler->GetAllocationProfile());
  CHECK(profile);

  std::vector<v8::AllocationProfile::Node*> nodes_to_visit;
  std::unordered_set<uint32_t> node_ids;
  nodes_to_visit.push_back(profile->GetRootNode());
  while (!nodes_to_visit.empty()) {
    v8::AllocationProfile::Node* node = nodes_to_visit.back();
    nodes_to_visit.pop_back();
    CHECK_LT(0, node->node_id);
    CHECK_EQ(0, node_ids.count(node->node_id));
    node_ids.insert(node->node_id);
    nodes_to_visit.insert(nodes_to_visit.end(), node->children.begin(),
                          node->children.end());
  }

  size_t total_size = 0;
  std::unordered_set<uint64_t> samples_set;
  for (auto& sample : profile->GetSamples()) {
    total_size += sample.size * sample.count;
    CHECK_EQ(0, samples_set.count(sample.sample_id));
    CHECK_EQ(1, node_ids.count(sample.node_id));
    CHECK_GT(sample.node_id, 0);
    CHECK_GT(sample.sample_id, 0);
    samples_set.insert(sample.sample_id);
  }
  size_t object_size = total_size / count;
  CHECK_GE(object_size, sizeof(void*) * 2);
  heap_profiler->StopSamplingHeapProfiler();
}

3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722
TEST(SamplingHeapProfilerLeftTrimming) {
  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  heap_profiler->StartSamplingHeapProfiler(64);

  CompileRun(
      "for (var j = 0; j < 500; ++j) {\n"
      "  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"
      "}\n");

3723
  CcTest::CollectGarbage(v8::internal::NEW_SPACE);
3724 3725 3726 3727
  // Should not crash.

  heap_profiler->StopSamplingHeapProfiler();
}
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746

TEST(SamplingHeapProfilerPretenuredInlineAllocations) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_expose_gc = true;

  CcTest::InitializeVM();
  if (!CcTest::i_isolate()->use_optimizer() || i::FLAG_always_opt) return;
  if (i::FLAG_gc_global || i::FLAG_stress_compaction ||
      i::FLAG_stress_incremental_marking) {
    return;
  }

  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

3747
  // Grow new space until maximum capacity reached.
3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772
  while (!CcTest::heap()->new_space()->IsAtMaximumCapacity()) {
    CcTest::heap()->new_space()->Grow();
  }

  i::ScopedVector<char> source(1024);
  i::SNPrintF(source,
              "var number_elements = %d;"
              "var elements = new Array(number_elements);"
              "function f() {"
              "  for (var i = 0; i < number_elements; i++) {"
              "    elements[i] = [{}, {}, {}];"
              "  }"
              "  return elements[number_elements - 1];"
              "};"
              "f(); gc();"
              "f(); f();"
              "%%OptimizeFunctionOnNextCall(f);"
              "f();"
              "f;",
              i::AllocationSite::kPretenureMinimumCreated + 1);

  v8::Local<v8::Function> f =
      v8::Local<v8::Function>::Cast(CompileRun(source.start()));

  // Make sure the function is producing pre-tenured objects.
3773
  auto res = f->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
3774 3775 3776 3777 3778 3779 3780
  i::Handle<i::JSObject> o = i::Handle<i::JSObject>::cast(
      v8::Utils::OpenHandle(*v8::Local<v8::Object>::Cast(res)));
  CHECK(CcTest::heap()->InOldSpace(o->elements()));
  CHECK(CcTest::heap()->InOldSpace(*o));

  // Call the function and profile it.
  heap_profiler->StartSamplingHeapProfiler(64);
3781
  for (int i = 0; i < 80; ++i) {
3782
    f->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799
  }

  std::unique_ptr<v8::AllocationProfile> profile(
      heap_profiler->GetAllocationProfile());
  CHECK(profile);
  heap_profiler->StopSamplingHeapProfiler();

  const char* names[] = {"f"};
  auto node_f = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                          ArrayVector(names));
  CHECK(node_f);

  int count = 0;
  for (auto allocation : node_f->allocations) {
    count += allocation.count;
  }

3800
  CHECK_GE(count, 8000);
3801
}
3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826

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

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  heap_profiler->StartSamplingHeapProfiler(512 * 1024);

  for (int i = 0; i < 8 * 1024; ++i) {
    CcTest::i_isolate()->factory()->NewFixedArray(1024);
  }

  std::unique_ptr<v8::AllocationProfile> profile(
      heap_profiler->GetAllocationProfile());
  CHECK(profile);
  const char* names[] = {"(EXTERNAL)"};
  auto node = FindAllocationProfileNode(env->GetIsolate(), *profile,
                                        ArrayVector(names));
  CHECK(node);

  heap_profiler->StopSamplingHeapProfiler();
}
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837

TEST(HeapSnapshotPrototypeNotJSReceiver) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();
  CompileRun(
      "function object() {}"
      "object.prototype = 42;");
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
}
3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883

TEST(SamplingHeapProfilerSampleDuringDeopt) {
  i::FLAG_allow_natives_syntax = true;

  v8::HandleScope scope(v8::Isolate::GetCurrent());
  LocalContext env;
  v8::HeapProfiler* heap_profiler = env->GetIsolate()->GetHeapProfiler();

  // Suppress randomness to avoid flakiness in tests.
  v8::internal::FLAG_sampling_heap_profiler_suppress_randomness = true;

  // Small sample interval to force each object to be sampled.
  heap_profiler->StartSamplingHeapProfiler(i::kPointerSize);

  // Lazy deopt from runtime call from inlined callback function.
  const char* source =
      "var b = "
      "  [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];"
      "(function f() {"
      "  var result = 0;"
      "  var lazyDeopt = function(deopt) {"
      "    var callback = function(v,i,o) {"
      "      result += i;"
      "      if (i == 13 && deopt) {"
      "          %DeoptimizeNow();"
      "      }"
      "      return v;"
      "    };"
      "    b.map(callback);"
      "  };"
      "  lazyDeopt();"
      "  lazyDeopt();"
      "  %OptimizeFunctionOnNextCall(lazyDeopt);"
      "  lazyDeopt();"
      "  lazyDeopt(true);"
      "  lazyDeopt();"
      "})();";

  CompileRun(source);
  // Should not crash.

  std::unique_ptr<v8::AllocationProfile> profile(
      heap_profiler->GetAllocationProfile());
  CHECK(profile);
  heap_profiler->StopSamplingHeapProfiler();
}
3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903

TEST(WeakReference) {
  v8::Isolate* isolate = CcTest::isolate();
  i::Isolate* i_isolate = CcTest::i_isolate();
  i::Factory* factory = i_isolate->factory();
  i::HandleScope scope(i_isolate);
  LocalContext env;

  // Create a FeedbackVector.
  v8::Local<v8::Script> script =
      v8::Script::Compile(isolate->GetCurrentContext(),
                          v8::String::NewFromUtf8(isolate, "function foo() {}",
                                                  v8::NewStringType::kNormal)
                              .ToLocalChecked())
          .ToLocalChecked();
  v8::MaybeLocal<v8::Value> value = script->Run(isolate->GetCurrentContext());
  CHECK(!value.IsEmpty());

  i::Handle<i::Object> obj = v8::Utils::OpenHandle(*script);
  i::Handle<i::SharedFunctionInfo> shared_function =
3904 3905
      i::Handle<i::SharedFunctionInfo>(i::JSFunction::cast(*obj)->shared(),
                                       i_isolate);
3906 3907 3908
  i::Handle<i::FeedbackVector> fv = factory->NewFeedbackVector(shared_function);

  // Create a Code.
3909
  i::Assembler assm(i::AssemblerOptions{}, nullptr, 0);
3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922
  assm.nop();  // supported on all architectures
  i::CodeDesc desc;
  assm.GetCode(i_isolate, &desc);
  i::Handle<i::Code> code =
      factory->NewCode(desc, i::Code::STUB, i::Handle<i::Code>());
  CHECK(code->IsCode());

  fv->set_optimized_code_weak_or_smi(i::HeapObjectReference::Weak(*code));

  v8::HeapProfiler* heap_profiler = isolate->GetHeapProfiler();
  const v8::HeapSnapshot* snapshot = heap_profiler->TakeHeapSnapshot();
  CHECK(ValidateSnapshot(snapshot));
}
3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964

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

  heap_profiler->StartSamplingHeapProfiler(100);

  heap_profiler->TakeHeapSnapshot();
  // Causes the StringsStorage to be deleted.
  heap_profiler->DeleteAllHeapSnapshots();

  // Triggers an allocation sample that tries to use the StringsStorage.
  for (int i = 0; i < 2 * 1024; ++i) {
    CompileRun(
        "new Array(64);"
        "new Uint8Array(16);");
  }

  heap_profiler->StopSamplingHeapProfiler();
}

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

  heap_profiler->StartTrackingHeapObjects(true);

  heap_profiler->TakeHeapSnapshot();
  // Causes the StringsStorage to be deleted.
  heap_profiler->DeleteAllHeapSnapshots();

  // Triggers an allocations that try to use the StringsStorage.
  for (int i = 0; i < 2 * 1024; ++i) {
    CompileRun(
        "new Array(64);"
        "new Uint8Array(16);");
  }

  heap_profiler->StopTrackingHeapObjects();
}