test-embedder-tracing.cc 47.5 KB
Newer Older
1 2 3 4
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7
#include <unordered_map>
#include <vector>

8
#include "include/v8.h"
9
#include "src/api/api-inl.h"
10
#include "src/heap/heap-inl.h"
11
#include "src/heap/safepoint.h"
12
#include "src/objects/module.h"
13
#include "src/objects/objects-inl.h"
14 15 16
#include "src/objects/script.h"
#include "src/objects/shared-function-info.h"
#include "test/cctest/cctest.h"
17
#include "test/cctest/heap/heap-utils.h"
18 19

namespace v8 {
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
namespace internal {
namespace heap {

namespace {

v8::Local<v8::Object> ConstructTraceableJSApiObject(
    v8::Local<v8::Context> context, void* first_field, void* second_field) {
  v8::EscapableHandleScope scope(context->GetIsolate());
  v8::Local<v8::FunctionTemplate> function_t =
      v8::FunctionTemplate::New(context->GetIsolate());
  v8::Local<v8::ObjectTemplate> instance_t = function_t->InstanceTemplate();
  instance_t->SetInternalFieldCount(2);
  v8::Local<v8::Function> function =
      function_t->GetFunction(context).ToLocalChecked();
  v8::Local<v8::Object> instance =
      function->NewInstance(context).ToLocalChecked();
  instance->SetAlignedPointerInInternalField(0, first_field);
  instance->SetAlignedPointerInInternalField(1, second_field);
  CHECK(!instance.IsEmpty());
  i::Handle<i::JSReceiver> js_obj = v8::Utils::OpenHandle(*instance);
41
  CHECK_EQ(i::JS_API_OBJECT_TYPE, js_obj->map().instance_type());
42 43 44
  return scope.Escape(instance);
}

45 46
enum class TracePrologueBehavior { kNoop, kCallV8WriteBarrier };

47 48
class TestEmbedderHeapTracer final : public v8::EmbedderHeapTracer {
 public:
49
  TestEmbedderHeapTracer() = default;
50 51 52
  TestEmbedderHeapTracer(TracePrologueBehavior prologue_behavior,
                         v8::Global<v8::Array> array)
      : prologue_behavior_(prologue_behavior), array_(std::move(array)) {}
53 54 55 56 57 58 59

  void RegisterV8References(
      const std::vector<std::pair<void*, void*>>& embedder_fields) final {
    registered_from_v8_.insert(registered_from_v8_.end(),
                               embedder_fields.begin(), embedder_fields.end());
  }

60
  void AddReferenceForTracing(v8::TracedGlobal<v8::Value>* global) {
61
    to_register_with_v8_.push_back(global);
62 63
  }

64 65 66 67
  void AddReferenceForTracing(v8::TracedReference<v8::Value>* ref) {
    to_register_with_v8_references_.push_back(ref);
  }

68
  bool AdvanceTracing(double deadline_in_ms) final {
69
    for (auto global : to_register_with_v8_) {
70
      RegisterEmbedderReference(global->As<v8::Data>());
71 72
    }
    to_register_with_v8_.clear();
73 74 75 76
    for (auto ref : to_register_with_v8_references_) {
      RegisterEmbedderReference(ref->As<v8::Data>());
    }
    to_register_with_v8_references_.clear();
77
    return true;
78 79
  }

80 81
  bool IsTracingDone() final { return to_register_with_v8_.empty(); }

82
  void TracePrologue(EmbedderHeapTracer::TraceFlags) final {
83 84 85 86 87 88 89
    if (prologue_behavior_ == TracePrologueBehavior::kCallV8WriteBarrier) {
      auto local = array_.Get(isolate());
      local->Set(local->CreationContext(), 0, v8::Object::New(isolate()))
          .Check();
    }
  }

90
  void TraceEpilogue(TraceSummary*) final {}
91
  void EnterFinalPause(EmbedderStackState) final {}
92 93 94 95 96 97 98 99

  bool IsRegisteredFromV8(void* first_field) const {
    for (auto pair : registered_from_v8_) {
      if (pair.first == first_field) return true;
    }
    return false;
  }

100 101 102 103 104 105 106 107
  void ConsiderTracedGlobalAsRoot(bool value) {
    consider_traced_global_as_root_ = value;
  }

  bool IsRootForNonTracingGC(const v8::TracedGlobal<v8::Value>& handle) final {
    return consider_traced_global_as_root_;
  }

108 109
 private:
  std::vector<std::pair<void*, void*>> registered_from_v8_;
110
  std::vector<v8::TracedGlobal<v8::Value>*> to_register_with_v8_;
111
  std::vector<v8::TracedReference<v8::Value>*> to_register_with_v8_references_;
112
  bool consider_traced_global_as_root_ = true;
113 114
  TracePrologueBehavior prologue_behavior_ = TracePrologueBehavior::kNoop;
  v8::Global<v8::Array> array_;
115 116 117 118 119 120 121 122 123 124
};

}  // namespace

TEST(V8RegisteringEmbedderReference) {
  // Tests that wrappers are properly registered with the embedder heap
  // tracer.
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
125
  TestEmbedderHeapTracer tracer;
126
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  v8::HandleScope scope(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);

  void* first_field = reinterpret_cast<void*>(0x2);
  v8::Local<v8::Object> api_object =
      ConstructTraceableJSApiObject(context, first_field, nullptr);
  CHECK(!api_object.IsEmpty());
  CcTest::CollectGarbage(i::OLD_SPACE);
  CHECK(tracer.IsRegisteredFromV8(first_field));
}

TEST(EmbedderRegisteringV8Reference) {
  // Tests that references that are registered by the embedder heap tracer are
  // considered live by V8.
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
145
  TestEmbedderHeapTracer tracer;
146
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
147 148 149 150
  v8::HandleScope scope(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);

151
  v8::TracedGlobal<v8::Value> g;
152 153
  {
    v8::HandleScope inner_scope(isolate);
154
    v8::Local<v8::Value> o =
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        v8::Local<v8::Object>::New(isolate, v8::Object::New(isolate));
    g.Reset(isolate, o);
  }
  tracer.AddReferenceForTracing(&g);
  CcTest::CollectGarbage(i::OLD_SPACE);
  CHECK(!g.IsEmpty());
}

namespace {

void ResurrectingFinalizer(
    const v8::WeakCallbackInfo<v8::Global<v8::Object>>& data) {
  data.GetParameter()->ClearWeak();
}

}  // namespace

TEST(TracingInRevivedSubgraph) {
  // Tests that wrappers are traced when they are contained with in a subgraph
  // that is revived by a finalizer.
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
178
  TestEmbedderHeapTracer tracer;
179
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  v8::HandleScope scope(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);

  v8::Global<v8::Object> g;
  void* first_field = reinterpret_cast<void*>(0x4);
  {
    v8::HandleScope inner_scope(isolate);
    v8::Local<v8::Object> api_object =
        ConstructTraceableJSApiObject(context, first_field, nullptr);
    CHECK(!api_object.IsEmpty());
    v8::Local<v8::Object> o =
        v8::Local<v8::Object>::New(isolate, v8::Object::New(isolate));
    o->Set(context, v8_str("link"), api_object).FromJust();
    g.Reset(isolate, o);
    g.SetWeak(&g, ResurrectingFinalizer, v8::WeakCallbackType::kFinalizer);
  }
  CcTest::CollectGarbage(i::OLD_SPACE);
  CHECK(tracer.IsRegisteredFromV8(first_field));
}

TEST(TracingInEphemerons) {
  // Tests that wrappers that are part of ephemerons are traced.
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
206
  TestEmbedderHeapTracer tracer;
207
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  v8::HandleScope scope(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);

  v8::Local<v8::Object> key =
      v8::Local<v8::Object>::New(isolate, v8::Object::New(isolate));
  void* first_field = reinterpret_cast<void*>(0x8);
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  Handle<JSWeakMap> weak_map = i_isolate->factory()->NewJSWeakMap();
  {
    v8::HandleScope inner_scope(isolate);
    v8::Local<v8::Object> api_object =
        ConstructTraceableJSApiObject(context, first_field, nullptr);
    CHECK(!api_object.IsEmpty());
    Handle<JSObject> js_key =
223
        handle(JSObject::cast(*v8::Utils::OpenHandle(*key)), i_isolate);
224
    Handle<JSReceiver> js_api_object = v8::Utils::OpenHandle(*api_object);
225
    int32_t hash = js_key->GetOrCreateHash(i_isolate).value();
226 227 228 229 230 231
    JSWeakCollection::Set(weak_map, js_key, js_api_object, hash);
  }
  CcTest::CollectGarbage(i::OLD_SPACE);
  CHECK(tracer.IsRegisteredFromV8(first_field));
}

232 233 234 235 236
TEST(FinalizeTracingIsNoopWhenNotMarking) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  Isolate* i_isolate = CcTest::i_isolate();
237
  TestEmbedderHeapTracer tracer;
238
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

  // Finalize a potentially running garbage collection.
  i_isolate->heap()->CollectGarbage(OLD_SPACE,
                                    GarbageCollectionReason::kTesting);
  CHECK(i_isolate->heap()->incremental_marking()->IsStopped());

  int gc_counter = i_isolate->heap()->gc_count();
  tracer.FinalizeTracing();
  CHECK(i_isolate->heap()->incremental_marking()->IsStopped());
  CHECK_EQ(gc_counter, i_isolate->heap()->gc_count());
}

TEST(FinalizeTracingWhenMarking) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  Isolate* i_isolate = CcTest::i_isolate();
256
  TestEmbedderHeapTracer tracer;
257
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
258 259 260 261 262 263 264 265 266 267

  // Finalize a potentially running garbage collection.
  i_isolate->heap()->CollectGarbage(OLD_SPACE,
                                    GarbageCollectionReason::kTesting);
  if (i_isolate->heap()->mark_compact_collector()->sweeping_in_progress()) {
    i_isolate->heap()->mark_compact_collector()->EnsureSweepingCompleted();
  }
  CHECK(i_isolate->heap()->incremental_marking()->IsStopped());

  i::IncrementalMarking* marking = i_isolate->heap()->incremental_marking();
268 269 270 271 272
  {
    SafepointScope scope(i_isolate->heap());
    marking->Start(i::GarbageCollectionReason::kTesting);
  }

273 274 275 276 277 278
  // Sweeping is not runing so we should immediately start marking.
  CHECK(marking->IsMarking());
  tracer.FinalizeTracing();
  CHECK(marking->IsStopped());
}

279 280
TEST(GarbageCollectionForTesting) {
  ManualGCScope manual_gc;
281
  i::FLAG_expose_gc = true;
282 283 284
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  Isolate* i_isolate = CcTest::i_isolate();
285
  TestEmbedderHeapTracer tracer;
286
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
287 288

  int saved_gc_counter = i_isolate->heap()->gc_count();
289 290
  tracer.GarbageCollectionForTesting(
      EmbedderHeapTracer::EmbedderStackState::kMayContainHeapPointers);
291 292 293
  CHECK_GT(i_isolate->heap()->gc_count(), saved_gc_counter);
}

294 295 296 297 298 299 300 301 302 303 304
namespace {

void ConstructJSObject(v8::Isolate* isolate, v8::Local<v8::Context> context,
                       v8::TracedGlobal<v8::Object>* global) {
  v8::HandleScope scope(isolate);
  v8::Local<v8::Object> object(v8::Object::New(isolate));
  CHECK(!object.IsEmpty());
  *global = v8::TracedGlobal<v8::Object>(isolate, object);
  CHECK(!global->IsEmpty());
}

305
template <typename T>
306
void ConstructJSApiObject(v8::Isolate* isolate, v8::Local<v8::Context> context,
307
                          T* global) {
308 309 310 311
  v8::HandleScope scope(isolate);
  v8::Local<v8::Object> object(
      ConstructTraceableJSApiObject(context, nullptr, nullptr));
  CHECK(!object.IsEmpty());
312
  *global = T(isolate, object);
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
  CHECK(!global->IsEmpty());
}

enum class SurvivalMode { kSurvives, kDies };

template <typename ModifierFunction, typename ConstructTracedGlobalFunction>
void TracedGlobalTest(v8::Isolate* isolate,
                      ConstructTracedGlobalFunction construct_function,
                      ModifierFunction modifier_function, void (*gc_function)(),
                      SurvivalMode survives) {
  v8::HandleScope scope(isolate);
  v8::Local<v8::Context> context = v8::Context::New(isolate);
  v8::Context::Scope context_scope(context);

  v8::TracedGlobal<v8::Object> global;
  construct_function(isolate, context, &global);
329
  CHECK(InCorrectGeneration(isolate, global));
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  modifier_function(global);
  gc_function();
  CHECK_IMPLIES(survives == SurvivalMode::kSurvives, !global.IsEmpty());
  CHECK_IMPLIES(survives == SurvivalMode::kDies, global.IsEmpty());
}

}  // namespace

TEST(TracedGlobalReset) {
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);

  v8::TracedGlobal<v8::Object> traced;
  ConstructJSObject(isolate, isolate->GetCurrentContext(), &traced);
  CHECK(!traced.IsEmpty());
  traced.Reset();
  CHECK(traced.IsEmpty());
}

TEST(TracedGlobalInStdVector) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);

  std::vector<v8::TracedGlobal<v8::Object>> vec;
  {
    v8::HandleScope scope(isolate);
    vec.emplace_back(isolate, v8::Object::New(isolate));
  }
  CHECK(!vec[0].IsEmpty());
  InvokeMarkSweep();
  CHECK(vec[0].IsEmpty());
}

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
TEST(TracedGlobalCopyWithDestructor) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();

  const size_t initial_count = global_handles->handles_count();
  v8::TracedGlobal<v8::Object> global1;
  {
    v8::HandleScope scope(isolate);
    global1.Reset(isolate, v8::Object::New(isolate));
  }
  v8::TracedGlobal<v8::Object> global2(global1);
  v8::TracedGlobal<v8::Object> global3;
  global3 = global2;
  CHECK_EQ(initial_count + 3, global_handles->handles_count());
  CHECK(!global1.IsEmpty());
  CHECK_EQ(global1, global2);
  CHECK_EQ(global2, global3);
  {
    v8::HandleScope scope(isolate);
    auto tmp = v8::Local<v8::Object>::New(isolate, global3);
    CHECK(!tmp.IsEmpty());
    InvokeMarkSweep();
  }
  CHECK_EQ(initial_count + 3, global_handles->handles_count());
  CHECK(!global1.IsEmpty());
  CHECK_EQ(global1, global2);
  CHECK_EQ(global2, global3);
  InvokeMarkSweep();
  CHECK_EQ(initial_count, global_handles->handles_count());
  CHECK(global1.IsEmpty());
  CHECK_EQ(global1, global2);
  CHECK_EQ(global2, global3);
}

TEST(TracedGlobalCopyNoDestructor) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();

  const size_t initial_count = global_handles->handles_count();
411
  v8::TracedReference<v8::Value> global1;
412 413 414 415
  {
    v8::HandleScope scope(isolate);
    global1.Reset(isolate, v8::Object::New(isolate));
  }
416 417
  v8::TracedReference<v8::Value> global2(global1);
  v8::TracedReference<v8::Value> global3;
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
  global3 = global2;
  CHECK_EQ(initial_count + 3, global_handles->handles_count());
  CHECK(!global1.IsEmpty());
  CHECK_EQ(global1, global2);
  CHECK_EQ(global2, global3);
  {
    v8::HandleScope scope(isolate);
    auto tmp = v8::Local<v8::Value>::New(isolate, global3);
    CHECK(!tmp.IsEmpty());
    InvokeMarkSweep();
  }
  CHECK_EQ(initial_count + 3, global_handles->handles_count());
  CHECK(!global1.IsEmpty());
  CHECK_EQ(global1, global2);
  CHECK_EQ(global2, global3);
  InvokeMarkSweep();
  CHECK_EQ(initial_count, global_handles->handles_count());
}

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
TEST(TracedGlobalInStdUnorderedMap) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);

  std::unordered_map<int, v8::TracedGlobal<v8::Object>> map;
  {
    v8::HandleScope scope(isolate);
    map.emplace(std::piecewise_construct, std::forward_as_tuple(1),
                std::forward_as_tuple(isolate, v8::Object::New(isolate)));
  }
  CHECK(!map[1].IsEmpty());
  InvokeMarkSweep();
  CHECK(map[1].IsEmpty());
}

TEST(TracedGlobalToUnmodifiedJSObjectDiesOnMarkSweep) {
  CcTest::InitializeVM();
  TracedGlobalTest(
      CcTest::isolate(), ConstructJSObject,
      [](const TracedGlobal<v8::Object>& global) {}, InvokeMarkSweep,
      SurvivalMode::kDies);
}

TEST(TracedGlobalToUnmodifiedJSObjectSurvivesMarkSweepWhenHeldAliveOtherwise) {
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> strong_global;
  TracedGlobalTest(
      CcTest::isolate(), ConstructJSObject,
      [isolate, &strong_global](const TracedGlobal<v8::Object>& global) {
        v8::HandleScope scope(isolate);
        strong_global = v8::Global<v8::Object>(isolate, global.Get(isolate));
      },
      InvokeMarkSweep, SurvivalMode::kSurvives);
}

TEST(TracedGlobalToUnmodifiedJSObjectSurvivesScavenge) {
476
  if (FLAG_single_generation) return;
477 478 479 480 481 482 483 484 485
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TracedGlobalTest(
      CcTest::isolate(), ConstructJSObject,
      [](const TracedGlobal<v8::Object>& global) {}, InvokeScavenge,
      SurvivalMode::kSurvives);
}

TEST(TracedGlobalToUnmodifiedJSObjectSurvivesScavengeWhenExcludedFromRoots) {
486
  if (FLAG_single_generation) return;
487 488 489
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
490
  TestEmbedderHeapTracer tracer;
491
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
492 493 494 495 496 497 498 499
  tracer.ConsiderTracedGlobalAsRoot(false);
  TracedGlobalTest(
      CcTest::isolate(), ConstructJSObject,
      [](const TracedGlobal<v8::Object>& global) {}, InvokeScavenge,
      SurvivalMode::kSurvives);
}

TEST(TracedGlobalToUnmodifiedJSApiObjectSurvivesScavengePerDefault) {
500
  if (FLAG_single_generation) return;
501 502 503
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
504
  TestEmbedderHeapTracer tracer;
505
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
506 507
  tracer.ConsiderTracedGlobalAsRoot(true);
  TracedGlobalTest(
508
      CcTest::isolate(), ConstructJSApiObject<TracedGlobal<v8::Object>>,
509 510 511 512 513
      [](const TracedGlobal<v8::Object>& global) {}, InvokeScavenge,
      SurvivalMode::kSurvives);
}

TEST(TracedGlobalToUnmodifiedJSApiObjectDiesOnScavengeWhenExcludedFromRoots) {
514
  if (FLAG_single_generation) return;
515 516 517
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
518
  TestEmbedderHeapTracer tracer;
519
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
520 521
  tracer.ConsiderTracedGlobalAsRoot(false);
  TracedGlobalTest(
522
      CcTest::isolate(), ConstructJSApiObject<TracedGlobal<v8::Object>>,
523 524 525 526 527 528 529 530 531
      [](const TracedGlobal<v8::Object>& global) {}, InvokeScavenge,
      SurvivalMode::kDies);
}

TEST(TracedGlobalWrapperClassId) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
532
  TestEmbedderHeapTracer tracer;
533
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
534 535 536 537 538 539 540 541

  v8::TracedGlobal<v8::Object> traced;
  ConstructJSObject(isolate, isolate->GetCurrentContext(), &traced);
  CHECK_EQ(0, traced.WrapperClassId());
  traced.SetWrapperClassId(17);
  CHECK_EQ(17, traced.WrapperClassId());
}

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
TEST(TracedReferenceHandlesMarking) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::TracedReference<v8::Value> live;
  v8::TracedReference<v8::Value> dead;
  live.Reset(isolate, v8::Undefined(isolate));
  dead.Reset(isolate, v8::Undefined(isolate));
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
  {
    TestEmbedderHeapTracer tracer;
    heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
    tracer.AddReferenceForTracing(&live);
    const size_t initial_count = global_handles->handles_count();
    InvokeMarkSweep();
    const size_t final_count = global_handles->handles_count();
    // Handles are black allocated, so the first GC does not collect them.
    CHECK_EQ(initial_count, final_count);
  }

  {
    TestEmbedderHeapTracer tracer;
    heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
    tracer.AddReferenceForTracing(&live);
    const size_t initial_count = global_handles->handles_count();
    InvokeMarkSweep();
    const size_t final_count = global_handles->handles_count();
    CHECK_EQ(initial_count, final_count + 1);
  }
}

TEST(TracedReferenceHandlesDoNotLeak) {
  // TracedReference handles are not cleared by the destructor of the embedder
  // object. To avoid leaks we need to mark these handles during GC.
  // This test checks that unmarked handles do not leak.
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::TracedReference<v8::Value> ref;
  ref.Reset(isolate, v8::Undefined(isolate));
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
  const size_t initial_count = global_handles->handles_count();
  // We need two GCs because handles are black allocated.
  InvokeMarkSweep();
  InvokeMarkSweep();
  const size_t final_count = global_handles->handles_count();
  CHECK_EQ(initial_count, final_count + 1);
}

TEST(TracedGlobalHandlesAreRetained) {
  // TracedGlobal handles are cleared by the destructor of the embedder object.
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::TracedGlobal<v8::Value> global;
  global.Reset(isolate, v8::Undefined(isolate));
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
  const size_t initial_count = global_handles->handles_count();
  // We need two GCs because handles are black allocated.
  InvokeMarkSweep();
  InvokeMarkSweep();
  const size_t final_count = global_handles->handles_count();
  CHECK_EQ(initial_count, final_count);
}

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
namespace {

class TracedGlobalVisitor final
    : public v8::EmbedderHeapTracer::TracedGlobalHandleVisitor {
 public:
  ~TracedGlobalVisitor() override = default;
  void VisitTracedGlobalHandle(const TracedGlobal<Value>& value) final {
    if (value.WrapperClassId() == 57) {
      count_++;
    }
  }

  size_t count() const { return count_; }

 private:
  size_t count_ = 0;
};

}  // namespace

TEST(TracedGlobalIteration) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
635
  TestEmbedderHeapTracer tracer;
636
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
637 638 639 640 641 642 643 644 645 646 647 648 649

  v8::TracedGlobal<v8::Object> traced;
  ConstructJSObject(isolate, isolate->GetCurrentContext(), &traced);
  CHECK(!traced.IsEmpty());
  traced.SetWrapperClassId(57);
  TracedGlobalVisitor visitor;
  {
    v8::HandleScope scope(isolate);
    tracer.IterateTracedGlobalHandles(&visitor);
  }
  CHECK_EQ(1, visitor.count());
}

650 651 652 653 654 655 656 657 658 659 660 661 662
namespace {

void FinalizationCallback(const WeakCallbackInfo<void>& data) {
  v8::TracedGlobal<v8::Object>* traced =
      reinterpret_cast<v8::TracedGlobal<v8::Object>*>(data.GetParameter());
  CHECK_EQ(reinterpret_cast<void*>(0x4), data.GetInternalField(0));
  CHECK_EQ(reinterpret_cast<void*>(0x8), data.GetInternalField(1));
  traced->Reset();
}

}  // namespace

TEST(TracedGlobalSetFinalizationCallbackScavenge) {
663
  if (FLAG_single_generation) return;
664 665 666 667 668 669
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  TestEmbedderHeapTracer tracer;
  tracer.ConsiderTracedGlobalAsRoot(false);
670
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691

  v8::TracedGlobal<v8::Object> traced;
  ConstructJSApiObject(isolate, isolate->GetCurrentContext(), &traced);
  CHECK(!traced.IsEmpty());
  {
    v8::HandleScope scope(isolate);
    auto local = traced.Get(isolate);
    local->SetAlignedPointerInInternalField(0, reinterpret_cast<void*>(0x4));
    local->SetAlignedPointerInInternalField(1, reinterpret_cast<void*>(0x8));
  }
  traced.SetFinalizationCallback(&traced, FinalizationCallback);
  heap::InvokeScavenge();
  CHECK(traced.IsEmpty());
}

TEST(TracedGlobalSetFinalizationCallbackMarkSweep) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  TestEmbedderHeapTracer tracer;
692
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707

  v8::TracedGlobal<v8::Object> traced;
  ConstructJSApiObject(isolate, isolate->GetCurrentContext(), &traced);
  CHECK(!traced.IsEmpty());
  {
    v8::HandleScope scope(isolate);
    auto local = traced.Get(isolate);
    local->SetAlignedPointerInInternalField(0, reinterpret_cast<void*>(0x4));
    local->SetAlignedPointerInInternalField(1, reinterpret_cast<void*>(0x8));
  }
  traced.SetFinalizationCallback(&traced, FinalizationCallback);
  heap::InvokeMarkSweep();
  CHECK(traced.IsEmpty());
}

708 709 710 711 712 713 714 715 716 717 718 719 720 721
TEST(TracePrologueCallingIntoV8WriteBarrier) {
  // Regression test: https://crbug.com/940003
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Global<v8::Array> global;
  {
    v8::HandleScope scope(isolate);
    auto local = v8::Array::New(isolate, 10);
    global.Reset(isolate, local);
  }
  TestEmbedderHeapTracer tracer(TracePrologueBehavior::kCallV8WriteBarrier,
                                std::move(global));
722
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
723
  SimulateIncrementalMarking(CcTest::i_isolate()->heap());
724 725 726
  // Finish GC to avoid removing the tracer while GC is running which may end up
  // in an infinite loop because of unprocessed objects.
  heap::InvokeMarkSweep();
727 728
}

729 730 731 732 733 734 735
TEST(TracedGlobalWithDestructor) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
736
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
737

738 739
  const size_t initial_count = global_handles->handles_count();
  auto* traced = new v8::TracedGlobal<v8::Object>();
740 741 742
  {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
743
        isolate->GetCurrentContext(), nullptr, nullptr));
744 745 746
    CHECK(traced->IsEmpty());
    *traced = v8::TracedGlobal<v8::Object>(isolate, object);
    CHECK(!traced->IsEmpty());
747
    CHECK_EQ(initial_count + 1, global_handles->handles_count());
748
  }
749 750 751
  delete traced;
  CHECK_EQ(initial_count, global_handles->handles_count());
  // GC should not need to clear the handle.
752
  heap::InvokeMarkSweep();
753
  CHECK_EQ(initial_count, global_handles->handles_count());
754 755 756 757 758 759 760 761 762
}

TEST(TracedGlobalNoDestructor) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
763
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();
764

765
  const size_t initial_count = global_handles->handles_count();
766 767
  char* memory = new char[sizeof(v8::TracedReference<v8::Value>)];
  auto* traced = new (memory) v8::TracedReference<v8::Value>();
768 769 770
  {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Value> object(ConstructTraceableJSApiObject(
771
        isolate->GetCurrentContext(), nullptr, nullptr));
772
    CHECK(traced->IsEmpty());
773
    *traced = v8::TracedReference<v8::Value>(isolate, object);
774
    CHECK(!traced->IsEmpty());
775
    CHECK_EQ(initial_count + 1, global_handles->handles_count());
776
  }
777
  traced->~TracedReference<v8::Value>();
778 779
  CHECK_EQ(initial_count + 1, global_handles->handles_count());
  // GC should clear the handle.
780
  heap::InvokeMarkSweep();
781
  CHECK_EQ(initial_count, global_handles->handles_count());
782 783 784
  delete[] memory;
}

785 786 787 788 789 790 791 792 793 794
namespace {

class EmptyEmbedderHeapTracer : public v8::EmbedderHeapTracer {
 public:
  void RegisterV8References(
      const std::vector<std::pair<void*, void*>>& embedder_fields) final {}

  bool AdvanceTracing(double deadline_in_ms) final { return true; }
  bool IsTracingDone() final { return true; }
  void TracePrologue(EmbedderHeapTracer::TraceFlags) final {}
795
  void TraceEpilogue(TraceSummary*) final {}
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
  void EnterFinalPause(EmbedderStackState) final {}
};

// EmbedderHeapTracer that can optimize Scavenger handling when used with
// TraceGlobal handles that have destructors.
class EmbedderHeapTracerDestructorNonTracingClearing final
    : public EmptyEmbedderHeapTracer {
 public:
  explicit EmbedderHeapTracerDestructorNonTracingClearing(
      uint16_t class_id_to_optimize)
      : class_id_to_optimize_(class_id_to_optimize) {}

  bool IsRootForNonTracingGC(const v8::TracedGlobal<v8::Value>& handle) final {
    return handle.WrapperClassId() != class_id_to_optimize_;
  }

 private:
  uint16_t class_id_to_optimize_;
};

// EmbedderHeapTracer that can optimize Scavenger handling when used with
// TraceGlobal handles without destructors.
class EmbedderHeapTracerNoDestructorNonTracingClearing final
    : public EmptyEmbedderHeapTracer {
 public:
  explicit EmbedderHeapTracerNoDestructorNonTracingClearing(
      uint16_t class_id_to_optimize)
      : class_id_to_optimize_(class_id_to_optimize) {}

825 826
  bool IsRootForNonTracingGC(
      const v8::TracedReference<v8::Value>& handle) final {
827 828 829 830
    return handle.WrapperClassId() != class_id_to_optimize_;
  }

  void ResetHandleInNonTracingGC(
831
      const v8::TracedReference<v8::Value>& handle) final {
832 833 834 835
    if (handle.WrapperClassId() != class_id_to_optimize_) return;

    // Convention (for test): Objects that are optimized have their first field
    // set as a back pointer.
836 837
    TracedReferenceBase<v8::Value>* original_handle =
        reinterpret_cast<TracedReferenceBase<v8::Value>*>(
838 839 840 841 842 843 844 845 846 847
            v8::Object::GetAlignedPointerFromInternalField(
                handle.As<v8::Object>(), 0));
    original_handle->Reset();
  }

 private:
  uint16_t class_id_to_optimize_;
};

template <typename T>
848 849 850 851
void SetupOptimizedAndNonOptimizedHandle(v8::Isolate* isolate,
                                         uint16_t optimized_class_id,
                                         T* optimized_handle,
                                         T* non_optimized_handle) {
852 853 854 855 856
  v8::HandleScope scope(isolate);

  v8::Local<v8::Object> optimized_object(ConstructTraceableJSApiObject(
      isolate->GetCurrentContext(), optimized_handle, nullptr));
  CHECK(optimized_handle->IsEmpty());
857
  *optimized_handle = T(isolate, optimized_object);
858 859 860 861 862 863
  CHECK(!optimized_handle->IsEmpty());
  optimized_handle->SetWrapperClassId(optimized_class_id);

  v8::Local<v8::Object> non_optimized_object(ConstructTraceableJSApiObject(
      isolate->GetCurrentContext(), nullptr, nullptr));
  CHECK(non_optimized_handle->IsEmpty());
864
  *non_optimized_handle = T(isolate, non_optimized_object);
865 866 867 868 869 870
  CHECK(!non_optimized_handle->IsEmpty());
}

}  // namespace

TEST(TracedGlobalDestructorReclaimedOnScavenge) {
871
  if (FLAG_single_generation) return;
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  constexpr uint16_t kClassIdToOptimize = 17;
  EmbedderHeapTracerDestructorNonTracingClearing tracer(kClassIdToOptimize);
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();

  const size_t initial_count = global_handles->handles_count();
  auto* optimized_handle = new v8::TracedGlobal<v8::Object>();
  auto* non_optimized_handle = new v8::TracedGlobal<v8::Object>();
  SetupOptimizedAndNonOptimizedHandle(isolate, kClassIdToOptimize,
                                      optimized_handle, non_optimized_handle);
  CHECK_EQ(initial_count + 2, global_handles->handles_count());
  heap::InvokeScavenge();
  CHECK_EQ(initial_count + 1, global_handles->handles_count());
  CHECK(optimized_handle->IsEmpty());
  delete optimized_handle;
  CHECK(!non_optimized_handle->IsEmpty());
  delete non_optimized_handle;
  CHECK_EQ(initial_count, global_handles->handles_count());
}

TEST(TracedGlobalNoDestructorReclaimedOnScavenge) {
897
  if (FLAG_single_generation) return;
898 899 900 901 902 903 904 905 906 907
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  constexpr uint16_t kClassIdToOptimize = 23;
  EmbedderHeapTracerNoDestructorNonTracingClearing tracer(kClassIdToOptimize);
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(isolate, &tracer);
  i::GlobalHandles* global_handles = CcTest::i_isolate()->global_handles();

  const size_t initial_count = global_handles->handles_count();
908 909
  auto* optimized_handle = new v8::TracedReference<v8::Value>();
  auto* non_optimized_handle = new v8::TracedReference<v8::Value>();
910 911 912 913 914 915 916 917 918 919 920 921 922
  SetupOptimizedAndNonOptimizedHandle(isolate, kClassIdToOptimize,
                                      optimized_handle, non_optimized_handle);
  CHECK_EQ(initial_count + 2, global_handles->handles_count());
  heap::InvokeScavenge();
  CHECK_EQ(initial_count + 1, global_handles->handles_count());
  CHECK(optimized_handle->IsEmpty());
  delete optimized_handle;
  CHECK(!non_optimized_handle->IsEmpty());
  non_optimized_handle->Reset();
  delete non_optimized_handle;
  CHECK_EQ(initial_count, global_handles->handles_count());
}

923 924
namespace {

925 926
template <typename T>
V8_NOINLINE void OnStackTest(TestEmbedderHeapTracer* tracer) {
927 928
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> observer;
929
  T stack_ref;
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
  {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
    stack_ref.Reset(isolate, object);
    observer.Reset(isolate, object);
    observer.SetWeak();
  }
  CHECK(!observer.IsEmpty());
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
}

V8_NOINLINE void CreateTracedReferenceInDeepStack(
    v8::Isolate* isolate, v8::Global<v8::Object>* observer) {
  v8::TracedReference<v8::Value> stack_ref;
  v8::HandleScope scope(isolate);
  v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
      isolate->GetCurrentContext(), nullptr, nullptr));
  stack_ref.Reset(isolate, object);
  observer->Reset(isolate, object);
  observer->SetWeak();
}

954
V8_NOINLINE void TracedReferenceNotifyEmptyStackTest(
955 956 957 958 959 960 961 962 963 964
    TestEmbedderHeapTracer* tracer) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> observer;
  CreateTracedReferenceInDeepStack(isolate, &observer);
  CHECK(!observer.IsEmpty());
  tracer->NotifyEmptyEmbedderStack();
  heap::InvokeMarkSweep();
  CHECK(observer.IsEmpty());
}

965 966 967 968 969
enum class Operation {
  kCopy,
  kMove,
};

970 971 972 973 974 975 976 977 978 979 980 981 982
template <typename T>
void PerformOperation(Operation op, T* lhs, T* rhs) {
  switch (op) {
    case Operation::kMove:
      *lhs = std::move(*rhs);
      break;
    case Operation::kCopy:
      *lhs = *rhs;
      rhs->Reset();
      break;
  }
}

983 984 985 986 987 988
enum class TargetHandling {
  kNonInitialized,
  kInitializedYoungGen,
  kInitializedOldGen
};

989
template <typename T>
990 991
V8_NOINLINE void StackToHeapTest(TestEmbedderHeapTracer* tracer, Operation op,
                                 TargetHandling target_handling) {
992 993
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> observer;
994 995
  T stack_handle;
  T* heap_handle = new T();
996 997 998 999
  if (target_handling != TargetHandling::kNonInitialized) {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> to_object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
1000 1001 1002
    CHECK(InCorrectGeneration(*v8::Utils::OpenHandle(*to_object)));
    if (!FLAG_single_generation &&
        target_handling == TargetHandling::kInitializedOldGen) {
1003 1004 1005 1006 1007 1008
      heap::InvokeScavenge();
      heap::InvokeScavenge();
      CHECK(!i::Heap::InYoungGeneration(*v8::Utils::OpenHandle(*to_object)));
    }
    heap_handle->Reset(isolate, to_object);
  }
1009 1010 1011 1012 1013 1014 1015 1016 1017
  {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
    stack_handle.Reset(isolate, object);
    observer.Reset(isolate, object);
    observer.SetWeak();
  }
  CHECK(!observer.IsEmpty());
1018
  tracer->AddReferenceForTracing(heap_handle);
1019 1020 1021
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
  tracer->AddReferenceForTracing(heap_handle);
1022
  PerformOperation(op, heap_handle, &stack_handle);
1023 1024 1025 1026 1027 1028 1029
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
  heap::InvokeMarkSweep();
  CHECK(observer.IsEmpty());
  delete heap_handle;
}

1030
template <typename T>
1031 1032
V8_NOINLINE void HeapToStackTest(TestEmbedderHeapTracer* tracer, Operation op,
                                 TargetHandling target_handling) {
1033 1034
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> observer;
1035 1036
  T stack_handle;
  T* heap_handle = new T();
1037 1038 1039 1040
  if (target_handling != TargetHandling::kNonInitialized) {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> to_object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
1041 1042 1043
    CHECK(InCorrectGeneration(*v8::Utils::OpenHandle(*to_object)));
    if (!FLAG_single_generation &&
        target_handling == TargetHandling::kInitializedOldGen) {
1044 1045 1046 1047 1048 1049
      heap::InvokeScavenge();
      heap::InvokeScavenge();
      CHECK(!i::Heap::InYoungGeneration(*v8::Utils::OpenHandle(*to_object)));
    }
    stack_handle.Reset(isolate, to_object);
  }
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
    heap_handle->Reset(isolate, object);
    observer.Reset(isolate, object);
    observer.SetWeak();
  }
  CHECK(!observer.IsEmpty());
  tracer->AddReferenceForTracing(heap_handle);
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
1062
  PerformOperation(op, &stack_handle, heap_handle);
1063 1064 1065 1066 1067
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
  stack_handle.Reset();
  heap::InvokeMarkSweep();
  CHECK(observer.IsEmpty());
1068
  delete heap_handle;
1069 1070
}

1071
template <typename T>
1072 1073
V8_NOINLINE void StackToStackTest(TestEmbedderHeapTracer* tracer, Operation op,
                                  TargetHandling target_handling) {
1074 1075
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> observer;
1076 1077
  T stack_handle1;
  T stack_handle2;
1078 1079 1080 1081
  if (target_handling != TargetHandling::kNonInitialized) {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> to_object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
1082 1083 1084
    CHECK(InCorrectGeneration(*v8::Utils::OpenHandle(*to_object)));
    if (!FLAG_single_generation &&
        target_handling == TargetHandling::kInitializedOldGen) {
1085 1086 1087 1088 1089 1090
      heap::InvokeScavenge();
      heap::InvokeScavenge();
      CHECK(!i::Heap::InYoungGeneration(*v8::Utils::OpenHandle(*to_object)));
    }
    stack_handle2.Reset(isolate, to_object);
  }
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  {
    v8::HandleScope scope(isolate);
    v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
        isolate->GetCurrentContext(), nullptr, nullptr));
    stack_handle1.Reset(isolate, object);
    observer.Reset(isolate, object);
    observer.SetWeak();
  }
  CHECK(!observer.IsEmpty());
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
1102
  PerformOperation(op, &stack_handle2, &stack_handle1);
1103 1104 1105 1106 1107 1108 1109
  heap::InvokeMarkSweep();
  CHECK(!observer.IsEmpty());
  stack_handle2.Reset();
  heap::InvokeMarkSweep();
  CHECK(observer.IsEmpty());
}

1110
template <typename T>
1111 1112 1113 1114 1115 1116 1117 1118
V8_NOINLINE void TracedReferenceCleanedTest(TestEmbedderHeapTracer* tracer) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
      isolate->GetCurrentContext(), nullptr, nullptr));
  const size_t before =
      CcTest::i_isolate()->global_handles()->NumberOfOnStackHandlesForTesting();
  for (int i = 0; i < 100; i++) {
1119
    T stack_handle;
1120 1121 1122 1123 1124 1125 1126
    stack_handle.Reset(isolate, object);
  }
  CHECK_EQ(before + 1, CcTest::i_isolate()
                           ->global_handles()
                           ->NumberOfOnStackHandlesForTesting());
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
V8_NOINLINE void TracedGlobalDestructorTest(TestEmbedderHeapTracer* tracer) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::Global<v8::Object> observer;
  {
    v8::TracedGlobal<v8::Value> stack_handle;
    {
      v8::HandleScope scope(isolate);
      v8::Local<v8::Object> object(ConstructTraceableJSApiObject(
          isolate->GetCurrentContext(), nullptr, nullptr));
      stack_handle.Reset(isolate, object);
      observer.Reset(isolate, object);
      observer.SetWeak();
    }
    CHECK(!observer.IsEmpty());
    heap::InvokeMarkSweep();
    CHECK(!observer.IsEmpty());
  }
  heap::InvokeMarkSweep();
  CHECK(observer.IsEmpty());
}

1148 1149 1150 1151 1152 1153 1154 1155 1156
}  // namespace

TEST(TracedReferenceOnStack) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1157
  OnStackTest<v8::TracedReference<v8::Value>>(&tracer);
1158 1159
}

1160
TEST(TracedGlobalOnStack) {
1161 1162 1163 1164 1165 1166
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1167
  OnStackTest<v8::TracedGlobal<v8::Value>>(&tracer);
1168 1169
}

1170
TEST(TracedReferenceCleaned) {
1171 1172 1173 1174 1175 1176
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1177
  TracedReferenceCleanedTest<v8::TracedReference<v8::Value>>(&tracer);
1178 1179
}

1180
TEST(TracedGlobalCleaned) {
1181 1182 1183 1184 1185 1186
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1187
  TracedReferenceCleanedTest<v8::TracedGlobal<v8::Value>>(&tracer);
1188 1189
}

1190 1191
TEST(TracedReferenceMove) {
  using ReferenceType = v8::TracedReference<v8::Value>;
1192 1193 1194 1195 1196 1197
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
  StackToHeapTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kNonInitialized);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedYoungGen);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedOldGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kNonInitialized);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedYoungGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedOldGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                  TargetHandling::kNonInitialized);
  StackToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                  TargetHandling::kInitializedYoungGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                  TargetHandling::kInitializedOldGen);
1216 1217
}

1218 1219
TEST(TracedReferenceCopy) {
  using ReferenceType = v8::TracedReference<v8::Value>;
1220 1221 1222 1223 1224 1225
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  StackToHeapTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kNonInitialized);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedYoungGen);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedOldGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kNonInitialized);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedYoungGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedOldGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                  TargetHandling::kNonInitialized);
  StackToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                  TargetHandling::kInitializedYoungGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                  TargetHandling::kInitializedOldGen);
1244 1245
}

1246
TEST(TracedGlobalMove) {
1247
  using ReferenceType = v8::TracedGlobal<v8::Value>;
1248 1249 1250 1251 1252 1253
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
  StackToHeapTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kNonInitialized);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedYoungGen);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedOldGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kNonInitialized);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedYoungGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                 TargetHandling::kInitializedOldGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                  TargetHandling::kNonInitialized);
  StackToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                  TargetHandling::kInitializedYoungGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kMove,
                                  TargetHandling::kInitializedOldGen);
1272 1273
}

1274 1275
TEST(TracedGlobalCopy) {
  using ReferenceType = v8::TracedGlobal<v8::Value>;
1276 1277 1278 1279 1280 1281
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
  StackToHeapTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kNonInitialized);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedYoungGen);
  StackToHeapTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedOldGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kNonInitialized);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedYoungGen);
  HeapToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                 TargetHandling::kInitializedOldGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                  TargetHandling::kNonInitialized);
  StackToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                  TargetHandling::kInitializedYoungGen);
  StackToStackTest<ReferenceType>(&tracer, Operation::kCopy,
                                  TargetHandling::kInitializedOldGen);
1300 1301
}

1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
TEST(TracedGlobalDestructor) {
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
  TracedGlobalDestructorTest(&tracer);
}

TEST(NotifyEmptyStack) {
1313 1314 1315 1316 1317 1318
  ManualGCScope manual_gc;
  CcTest::InitializeVM();
  TestEmbedderHeapTracer tracer;
  heap::TemporaryEmbedderHeapTracerScope tracer_scope(CcTest::isolate(),
                                                      &tracer);
  tracer.SetStackStart(&manual_gc);
1319
  TracedReferenceNotifyEmptyStackTest(&tracer);
1320 1321
}

1322 1323 1324
}  // namespace heap
}  // namespace internal
}  // namespace v8