microtask-queue-unittest.cc 23.3 KB
Newer Older
1 2 3 4
// Copyright 2018 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
#include "src/execution/microtask-queue.h"
6 7 8 9 10 11

#include <algorithm>
#include <functional>
#include <memory>
#include <vector>

12
#include "include/v8-function.h"
13
#include "src/heap/factory.h"
14
#include "src/objects/foreign.h"
15 16
#include "src/objects/js-array-inl.h"
#include "src/objects/js-objects-inl.h"
17
#include "src/objects/objects-inl.h"
18
#include "src/objects/promise-inl.h"
19
#include "src/objects/visitors.h"
20 21 22 23 24 25 26 27 28 29 30 31 32
#include "test/unittests/test-utils.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace v8 {
namespace internal {

using Closure = std::function<void()>;

void RunStdFunction(void* data) {
  std::unique_ptr<Closure> f(static_cast<Closure*>(data));
  (*f)();
}

33
template <typename TMixin>
34
class WithFinalizationRegistryMixin : public TMixin {
35
 public:
36 37
  WithFinalizationRegistryMixin() = default;
  ~WithFinalizationRegistryMixin() override = default;
38 39 40
  WithFinalizationRegistryMixin(const WithFinalizationRegistryMixin&) = delete;
  WithFinalizationRegistryMixin& operator=(
      const WithFinalizationRegistryMixin&) = delete;
41

42
  static void SetUpTestSuite() {
43 44
    CHECK_NULL(save_flags_);
    save_flags_ = new SaveFlags();
45
    FLAG_expose_gc = true;
46
    FLAG_allow_natives_syntax = true;
47
    TMixin::SetUpTestSuite();
48 49
  }

50 51
  static void TearDownTestSuite() {
    TMixin::TearDownTestSuite();
52 53 54
    CHECK_NOT_NULL(save_flags_);
    delete save_flags_;
    save_flags_ = nullptr;
55 56 57
  }

 private:
58
  static SaveFlags* save_flags_;
59 60
};

61
template <typename TMixin>
62 63 64 65 66 67 68
SaveFlags* WithFinalizationRegistryMixin<TMixin>::save_flags_ = nullptr;

using TestWithNativeContextAndFinalizationRegistry =  //
    WithInternalIsolateMixin<                         //
        WithContextMixin<                             //
            WithFinalizationRegistryMixin<            //
                WithIsolateScopeMixin<                //
69
                    WithIsolateMixin<                 //
70 71
                        WithDefaultPlatformMixin<     //
                            ::testing::Test>>>>>>;
72

73 74 75 76 77 78 79 80 81
namespace {

void DummyPromiseHook(PromiseHookType type, Local<Promise> promise,
                      Local<Value> parent) {}

}  // namespace

class MicrotaskQueueTest : public TestWithNativeContextAndFinalizationRegistry,
                           public ::testing::WithParamInterface<bool> {
82 83 84 85 86 87 88 89 90 91
 public:
  template <typename F>
  Handle<Microtask> NewMicrotask(F&& f) {
    Handle<Foreign> runner =
        factory()->NewForeign(reinterpret_cast<Address>(&RunStdFunction));
    Handle<Foreign> data = factory()->NewForeign(
        reinterpret_cast<Address>(new Closure(std::forward<F>(f))));
    return factory()->NewCallbackTask(runner, data);
  }

92 93
  void SetUp() override {
    microtask_queue_ = MicrotaskQueue::New(isolate());
94
    native_context()->set_microtask_queue(isolate(), microtask_queue());
95 96 97 98 99 100

    if (GetParam()) {
      // Use a PromiseHook to switch the implementation to ResolvePromise
      // runtime, instead of ResolvePromise builtin.
      v8_isolate()->SetPromiseHook(&DummyPromiseHook);
    }
101 102
  }

103
  void TearDown() override {
104 105 106 107 108 109 110 111 112 113 114
    if (microtask_queue()) {
      microtask_queue()->RunMicrotasks(isolate());
      context()->DetachGlobal();
    }
  }

  MicrotaskQueue* microtask_queue() const { return microtask_queue_.get(); }

  void ClearTestMicrotaskQueue() {
    context()->DetachGlobal();
    microtask_queue_ = nullptr;
115
  }
116

117 118 119 120 121
  template <size_t N>
  Handle<Name> NameFromChars(const char (&chars)[N]) {
    return isolate()->factory()->NewStringFromStaticChars(chars);
  }

122 123
 private:
  std::unique_ptr<MicrotaskQueue> microtask_queue_;
124 125 126 127 128 129 130
};

class RecordingVisitor : public RootVisitor {
 public:
  RecordingVisitor() = default;
  ~RecordingVisitor() override = default;

131 132 133
  void VisitRootPointers(Root root, const char* description,
                         FullObjectSlot start, FullObjectSlot end) override {
    for (FullObjectSlot current = start; current != end; ++current) {
134 135 136 137
      visited_.push_back(*current);
    }
  }

138
  const std::vector<Object>& visited() const { return visited_; }
139 140

 private:
141
  std::vector<Object> visited_;
142 143 144
};

// Sanity check. Ensure a microtask is stored in a queue and run.
145
TEST_P(MicrotaskQueueTest, EnqueueAndRun) {
146
  bool ran = false;
147 148 149
  EXPECT_EQ(0, microtask_queue()->capacity());
  EXPECT_EQ(0, microtask_queue()->size());
  microtask_queue()->EnqueueMicrotask(*NewMicrotask([&ran] {
150 151 152
    EXPECT_FALSE(ran);
    ran = true;
  }));
153 154
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity, microtask_queue()->capacity());
  EXPECT_EQ(1, microtask_queue()->size());
155
  EXPECT_EQ(1, microtask_queue()->RunMicrotasks(isolate()));
156
  EXPECT_TRUE(ran);
157
  EXPECT_EQ(0, microtask_queue()->size());
158 159 160
}

// Check for a buffer growth.
161
TEST_P(MicrotaskQueueTest, BufferGrowth) {
162 163 164
  int count = 0;

  // Enqueue and flush the queue first to have non-zero |start_|.
165
  microtask_queue()->EnqueueMicrotask(
166
      *NewMicrotask([&count] { EXPECT_EQ(0, count++); }));
167
  EXPECT_EQ(1, microtask_queue()->RunMicrotasks(isolate()));
168

169 170 171
  EXPECT_LT(0, microtask_queue()->capacity());
  EXPECT_EQ(0, microtask_queue()->size());
  EXPECT_EQ(1, microtask_queue()->start());
172 173 174

  // Fill the queue with Microtasks.
  for (int i = 1; i <= MicrotaskQueue::kMinimumCapacity; ++i) {
175
    microtask_queue()->EnqueueMicrotask(
176 177
        *NewMicrotask([&count, i] { EXPECT_EQ(i, count++); }));
  }
178 179
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity, microtask_queue()->capacity());
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity, microtask_queue()->size());
180 181

  // Add another to grow the ring buffer.
182
  microtask_queue()->EnqueueMicrotask(*NewMicrotask(
183 184
      [&] { EXPECT_EQ(MicrotaskQueue::kMinimumCapacity + 1, count++); }));

185 186
  EXPECT_LT(MicrotaskQueue::kMinimumCapacity, microtask_queue()->capacity());
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity + 1, microtask_queue()->size());
187 188

  // Run all pending Microtasks to ensure they run in the proper order.
189 190
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity + 1,
            microtask_queue()->RunMicrotasks(isolate()));
191 192 193 194
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity + 2, count);
}

// MicrotaskQueue instances form a doubly linked list.
195
TEST_P(MicrotaskQueueTest, InstanceChain) {
196 197
  ClearTestMicrotaskQueue();

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
  MicrotaskQueue* default_mtq = isolate()->default_microtask_queue();
  ASSERT_TRUE(default_mtq);
  EXPECT_EQ(default_mtq, default_mtq->next());
  EXPECT_EQ(default_mtq, default_mtq->prev());

  // Create two instances, and check their connection.
  // The list contains all instances in the creation order, and the next of the
  // last instance is the first instance:
  //   default_mtq -> mtq1 -> mtq2 -> default_mtq.
  std::unique_ptr<MicrotaskQueue> mtq1 = MicrotaskQueue::New(isolate());
  std::unique_ptr<MicrotaskQueue> mtq2 = MicrotaskQueue::New(isolate());
  EXPECT_EQ(default_mtq->next(), mtq1.get());
  EXPECT_EQ(mtq1->next(), mtq2.get());
  EXPECT_EQ(mtq2->next(), default_mtq);
  EXPECT_EQ(default_mtq, mtq1->prev());
  EXPECT_EQ(mtq1.get(), mtq2->prev());
  EXPECT_EQ(mtq2.get(), default_mtq->prev());

  // Deleted item should be also removed from the list.
  mtq1 = nullptr;
  EXPECT_EQ(default_mtq->next(), mtq2.get());
  EXPECT_EQ(mtq2->next(), default_mtq);
  EXPECT_EQ(default_mtq, mtq2->prev());
  EXPECT_EQ(mtq2.get(), default_mtq->prev());
}

// Pending Microtasks in MicrotaskQueues are strong roots. Ensure they are
// visited exactly once.
226
TEST_P(MicrotaskQueueTest, VisitRoot) {
227 228
  // Ensure that the ring buffer has separate in-use region.
  for (int i = 0; i < MicrotaskQueue::kMinimumCapacity / 2 + 1; ++i) {
229
    microtask_queue()->EnqueueMicrotask(*NewMicrotask([] {}));
230
  }
231 232
  EXPECT_EQ(MicrotaskQueue::kMinimumCapacity / 2 + 1,
            microtask_queue()->RunMicrotasks(isolate()));
233

234
  std::vector<Object> expected;
235 236 237
  for (int i = 0; i < MicrotaskQueue::kMinimumCapacity / 2 + 1; ++i) {
    Handle<Microtask> microtask = NewMicrotask([] {});
    expected.push_back(*microtask);
238
    microtask_queue()->EnqueueMicrotask(*microtask);
239
  }
240 241
  EXPECT_GT(microtask_queue()->start() + microtask_queue()->size(),
            microtask_queue()->capacity());
242 243

  RecordingVisitor visitor;
244
  microtask_queue()->IterateMicrotasks(&visitor);
245

246
  std::vector<Object> actual = visitor.visited();
247 248 249 250 251
  std::sort(expected.begin(), expected.end());
  std::sort(actual.begin(), actual.end());
  EXPECT_EQ(expected, actual);
}

252
TEST_P(MicrotaskQueueTest, PromiseHandlerContext) {
253
  microtask_queue()->set_microtasks_policy(MicrotasksPolicy::kExplicit);
254 255 256 257 258 259
  Local<v8::Context> v8_context2 = v8::Context::New(v8_isolate());
  Local<v8::Context> v8_context3 = v8::Context::New(v8_isolate());
  Local<v8::Context> v8_context4 = v8::Context::New(v8_isolate());
  Handle<Context> context2 = Utils::OpenHandle(*v8_context2, isolate());
  Handle<Context> context3 = Utils::OpenHandle(*v8_context3, isolate());
  Handle<Context> context4 = Utils::OpenHandle(*v8_context3, isolate());
260 261 262
  context2->native_context().set_microtask_queue(isolate(), microtask_queue());
  context3->native_context().set_microtask_queue(isolate(), microtask_queue());
  context4->native_context().set_microtask_queue(isolate(), microtask_queue());
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

  Handle<JSFunction> handler;
  Handle<JSProxy> proxy;
  Handle<JSProxy> revoked_proxy;
  Handle<JSBoundFunction> bound;

  // Create a JSFunction on |context2|
  {
    v8::Context::Scope scope(v8_context2);
    handler = RunJS<JSFunction>("()=>{}");
    EXPECT_EQ(*context2,
              *JSReceiver::GetContextForMicrotask(handler).ToHandleChecked());
  }

  // Create a JSProxy on |context3|.
  {
    v8::Context::Scope scope(v8_context3);
    ASSERT_TRUE(
        v8_context3->Global()
            ->Set(v8_context3, NewString("handler"), Utils::ToLocal(handler))
            .FromJust());
    proxy = RunJS<JSProxy>("new Proxy(handler, {})");
    revoked_proxy = RunJS<JSProxy>(
        "let {proxy, revoke} = Proxy.revocable(handler, {});"
        "revoke();"
        "proxy");
    EXPECT_EQ(*context2,
              *JSReceiver::GetContextForMicrotask(proxy).ToHandleChecked());
    EXPECT_TRUE(JSReceiver::GetContextForMicrotask(revoked_proxy).is_null());
  }

  // Create a JSBoundFunction on |context4|.
  // Note that its CreationContext and ContextForTaskCancellation is |context2|.
  {
    v8::Context::Scope scope(v8_context4);
    ASSERT_TRUE(
        v8_context4->Global()
            ->Set(v8_context4, NewString("handler"), Utils::ToLocal(handler))
            .FromJust());
    bound = RunJS<JSBoundFunction>("handler.bind()");
    EXPECT_EQ(*context2,
              *JSReceiver::GetContextForMicrotask(bound).ToHandleChecked());
  }

  // Give the objects to the main context.
  SetGlobalProperty("handler", Utils::ToLocal(handler));
  SetGlobalProperty("proxy", Utils::ToLocal(proxy));
  SetGlobalProperty("revoked_proxy", Utils::ToLocal(revoked_proxy));
  SetGlobalProperty("bound", Utils::ToLocal(Handle<JSReceiver>::cast(bound)));
  RunJS(
      "Promise.resolve().then(handler);"
      "Promise.reject().catch(proxy);"
      "Promise.resolve().then(revoked_proxy);"
      "Promise.resolve().then(bound);");

  ASSERT_EQ(4, microtask_queue()->size());
  Handle<Microtask> microtask1(microtask_queue()->get(0), isolate());
  ASSERT_TRUE(microtask1->IsPromiseFulfillReactionJobTask());
  EXPECT_EQ(*context2,
            Handle<PromiseFulfillReactionJobTask>::cast(microtask1)->context());

  Handle<Microtask> microtask2(microtask_queue()->get(1), isolate());
  ASSERT_TRUE(microtask2->IsPromiseRejectReactionJobTask());
  EXPECT_EQ(*context2,
            Handle<PromiseRejectReactionJobTask>::cast(microtask2)->context());

  Handle<Microtask> microtask3(microtask_queue()->get(2), isolate());
  ASSERT_TRUE(microtask3->IsPromiseFulfillReactionJobTask());
  // |microtask3| corresponds to a PromiseReaction for |revoked_proxy|.
  // As |revoked_proxy| doesn't have a context, the current context should be
  // used as the fallback context.
  EXPECT_EQ(*native_context(),
            Handle<PromiseFulfillReactionJobTask>::cast(microtask3)->context());

  Handle<Microtask> microtask4(microtask_queue()->get(3), isolate());
  ASSERT_TRUE(microtask4->IsPromiseFulfillReactionJobTask());
  EXPECT_EQ(*context2,
            Handle<PromiseFulfillReactionJobTask>::cast(microtask4)->context());

  v8_context4->DetachGlobal();
  v8_context3->DetachGlobal();
  v8_context2->DetachGlobal();
}

347
TEST_P(MicrotaskQueueTest, DetachGlobal_Enqueue) {
348 349 350 351 352 353 354 355 356 357 358
  EXPECT_EQ(0, microtask_queue()->size());

  // Detach MicrotaskQueue from the current context.
  context()->DetachGlobal();

  // No microtask should be enqueued after DetachGlobal call.
  EXPECT_EQ(0, microtask_queue()->size());
  RunJS("Promise.resolve().then(()=>{})");
  EXPECT_EQ(0, microtask_queue()->size());
}

359
TEST_P(MicrotaskQueueTest, DetachGlobal_Run) {
360
  microtask_queue()->set_microtasks_policy(MicrotasksPolicy::kExplicit);
361 362 363 364 365 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
  EXPECT_EQ(0, microtask_queue()->size());

  // Enqueue microtasks to the current context.
  Handle<JSArray> ran = RunJS<JSArray>(
      "var ran = [false, false, false, false];"
      "Promise.resolve().then(() => { ran[0] = true; });"
      "Promise.reject().catch(() => { ran[1] = true; });"
      "ran");

  Handle<JSFunction> function =
      RunJS<JSFunction>("(function() { ran[2] = true; })");
  Handle<CallableTask> callable =
      factory()->NewCallableTask(function, Utils::OpenHandle(*context()));
  microtask_queue()->EnqueueMicrotask(*callable);

  // The handler should not run at this point.
  const int kNumExpectedTasks = 3;
  for (int i = 0; i < kNumExpectedTasks; ++i) {
    EXPECT_TRUE(
        Object::GetElement(isolate(), ran, i).ToHandleChecked()->IsFalse());
  }
  EXPECT_EQ(kNumExpectedTasks, microtask_queue()->size());

  // Detach MicrotaskQueue from the current context.
  context()->DetachGlobal();

  // RunMicrotasks processes pending Microtasks, but Microtasks that are
  // associated to a detached context should be cancelled and should not take
  // effect.
  microtask_queue()->RunMicrotasks(isolate());
  EXPECT_EQ(0, microtask_queue()->size());
  for (int i = 0; i < kNumExpectedTasks; ++i) {
    EXPECT_TRUE(
        Object::GetElement(isolate(), ran, i).ToHandleChecked()->IsFalse());
  }
}

398
TEST_P(MicrotaskQueueTest, DetachGlobal_PromiseResolveThenableJobTask) {
399
  microtask_queue()->set_microtasks_policy(MicrotasksPolicy::kExplicit);
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
  RunJS(
      "var resolve;"
      "var promise = new Promise(r => { resolve = r; });"
      "promise.then(() => {});"
      "resolve({});");

  // A PromiseResolveThenableJobTask is pending in the MicrotaskQueue.
  EXPECT_EQ(1, microtask_queue()->size());

  // Detach MicrotaskQueue from the current context.
  context()->DetachGlobal();

  // RunMicrotasks processes the pending Microtask, but Microtasks that are
  // associated to a detached context should be cancelled and should not take
  // effect.
  // As PromiseResolveThenableJobTask queues another task for resolution,
  // the return value is 2 if it ran.
  EXPECT_EQ(1, microtask_queue()->RunMicrotasks(isolate()));
  EXPECT_EQ(0, microtask_queue()->size());
}

421
TEST_P(MicrotaskQueueTest, DetachGlobal_ResolveThenableForeignThen) {
422
  microtask_queue()->set_microtasks_policy(MicrotasksPolicy::kExplicit);
423 424 425 426 427 428 429 430 431 432 433
  Handle<JSArray> result = RunJS<JSArray>(
      "let result = [false];"
      "result");
  Handle<JSFunction> then = RunJS<JSFunction>("() => { result[0] = true; }");

  Handle<JSPromise> stale_promise;

  {
    // Create a context with its own microtask queue.
    std::unique_ptr<MicrotaskQueue> sub_microtask_queue =
        MicrotaskQueue::New(isolate());
434
    sub_microtask_queue->set_microtasks_policy(MicrotasksPolicy::kExplicit);
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    Local<v8::Context> sub_context = v8::Context::New(
        v8_isolate(),
        /* extensions= */ nullptr,
        /* global_template= */ MaybeLocal<ObjectTemplate>(),
        /* global_object= */ MaybeLocal<Value>(),
        /* internal_fields_deserializer= */ DeserializeInternalFieldsCallback(),
        sub_microtask_queue.get());

    {
      v8::Context::Scope scope(sub_context);
      CHECK(sub_context->Global()
                ->Set(sub_context, NewString("then"),
                      Utils::ToLocal(Handle<JSReceiver>::cast(then)))
                .FromJust());

      ASSERT_EQ(0, microtask_queue()->size());
      ASSERT_EQ(0, sub_microtask_queue->size());
      ASSERT_TRUE(Object::GetElement(isolate(), result, 0)
                      .ToHandleChecked()
                      ->IsFalse());

      // With a regular thenable, a microtask is queued on the sub-context.
      RunJS<JSPromise>("Promise.resolve({ then: cb => cb(1) })");
      EXPECT_EQ(0, microtask_queue()->size());
      EXPECT_EQ(1, sub_microtask_queue->size());
      EXPECT_TRUE(Object::GetElement(isolate(), result, 0)
                      .ToHandleChecked()
                      ->IsFalse());

      // But when the `then` method comes from another context, a microtask is
      // instead queued on the main context.
      stale_promise = RunJS<JSPromise>("Promise.resolve({ then })");
      EXPECT_EQ(1, microtask_queue()->size());
      EXPECT_EQ(1, sub_microtask_queue->size());
      EXPECT_TRUE(Object::GetElement(isolate(), result, 0)
                      .ToHandleChecked()
                      ->IsFalse());
    }

    sub_context->DetachGlobal();
  }

  EXPECT_EQ(1, microtask_queue()->size());
  EXPECT_TRUE(
      Object::GetElement(isolate(), result, 0).ToHandleChecked()->IsFalse());

  EXPECT_EQ(1, microtask_queue()->RunMicrotasks(isolate()));
  EXPECT_EQ(0, microtask_queue()->size());
  EXPECT_TRUE(
      Object::GetElement(isolate(), result, 0).ToHandleChecked()->IsTrue());
}

TEST_P(MicrotaskQueueTest, DetachGlobal_HandlerContext) {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
  // EnqueueMicrotask should use the context associated to the handler instead
  // of the current context. E.g.
  //   // At Context A.
  //   let resolved = Promise.resolve();
  //   // Call DetachGlobal on A, so that microtasks associated to A is
  //   // cancelled.
  //
  //   // At Context B.
  //   let handler = () => {
  //     console.log("here");
  //   };
  //   // The microtask to run |handler| should be associated to B instead of A,
  //   // so that handler runs even |resolved| is on the detached context A.
  //   resolved.then(handler);

  Handle<JSReceiver> results = isolate()->factory()->NewJSObjectWithNullProto();

  // These belong to a stale Context.
  Handle<JSPromise> stale_resolved_promise;
  Handle<JSPromise> stale_rejected_promise;
  Handle<JSReceiver> stale_handler;

  Local<v8::Context> sub_context = v8::Context::New(v8_isolate());
  {
    v8::Context::Scope scope(sub_context);
    stale_resolved_promise = RunJS<JSPromise>("Promise.resolve()");
    stale_rejected_promise = RunJS<JSPromise>("Promise.reject()");
    stale_handler = RunJS<JSReceiver>(
        "(results, label) => {"
        "  results[label] = true;"
        "}");
  }
  // DetachGlobal() cancells all microtasks associated to the context.
  sub_context->DetachGlobal();
  sub_context.Clear();

  SetGlobalProperty("results", Utils::ToLocal(results));
  SetGlobalProperty(
      "stale_resolved_promise",
      Utils::ToLocal(Handle<JSReceiver>::cast(stale_resolved_promise)));
  SetGlobalProperty(
      "stale_rejected_promise",
      Utils::ToLocal(Handle<JSReceiver>::cast(stale_rejected_promise)));
  SetGlobalProperty("stale_handler", Utils::ToLocal(stale_handler));

  // Set valid handlers to stale promises.
  RunJS(
      "stale_resolved_promise.then(() => {"
      "  results['stale_resolved_promise'] = true;"
      "})");
  RunJS(
      "stale_rejected_promise.catch(() => {"
      "  results['stale_rejected_promise'] = true;"
      "})");
  microtask_queue()->RunMicrotasks(isolate());
543 544 545 546 547 548
  EXPECT_TRUE(JSReceiver::HasProperty(isolate(), results,
                                      NameFromChars("stale_resolved_promise"))
                  .FromJust());
  EXPECT_TRUE(JSReceiver::HasProperty(isolate(), results,
                                      NameFromChars("stale_rejected_promise"))
                  .FromJust());
549 550 551 552 553 554 555 556 557

  // Set stale handlers to valid promises.
  RunJS(
      "Promise.resolve("
      "    stale_handler.bind(null, results, 'stale_handler_resolve'))");
  RunJS(
      "Promise.reject("
      "    stale_handler.bind(null, results, 'stale_handler_reject'))");
  microtask_queue()->RunMicrotasks(isolate());
558 559 560 561 562 563
  EXPECT_FALSE(JSReceiver::HasProperty(isolate(), results,
                                       NameFromChars("stale_handler_resolve"))
                   .FromJust());
  EXPECT_FALSE(JSReceiver::HasProperty(isolate(), results,
                                       NameFromChars("stale_handler_reject"))
                   .FromJust());
564 565
}

566
TEST_P(MicrotaskQueueTest, DetachGlobal_Chain) {
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
  Handle<JSPromise> stale_rejected_promise;

  Local<v8::Context> sub_context = v8::Context::New(v8_isolate());
  {
    v8::Context::Scope scope(sub_context);
    stale_rejected_promise = RunJS<JSPromise>("Promise.reject()");
  }
  sub_context->DetachGlobal();
  sub_context.Clear();

  SetGlobalProperty(
      "stale_rejected_promise",
      Utils::ToLocal(Handle<JSReceiver>::cast(stale_rejected_promise)));
  Handle<JSArray> result = RunJS<JSArray>(
      "let result = [false];"
      "stale_rejected_promise"
      "  .then(() => {})"
      "  .catch(() => {"
      "    result[0] = true;"
      "  });"
      "result");
  microtask_queue()->RunMicrotasks(isolate());
  EXPECT_TRUE(
      Object::GetElement(isolate(), result, 0).ToHandleChecked()->IsTrue());
}

593
TEST_P(MicrotaskQueueTest, DetachGlobal_InactiveHandler) {
594 595 596
  Local<v8::Context> sub_context = v8::Context::New(v8_isolate());
  Utils::OpenHandle(*sub_context)
      ->native_context()
597
      .set_microtask_queue(isolate(), microtask_queue());
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

  Handle<JSArray> result;
  Handle<JSFunction> stale_handler;
  Handle<JSPromise> stale_promise;
  {
    v8::Context::Scope scope(sub_context);
    result = RunJS<JSArray>("var result = [false, false]; result");
    stale_handler = RunJS<JSFunction>("() => { result[0] = true; }");
    stale_promise = RunJS<JSPromise>(
        "var stale_promise = new Promise(()=>{});"
        "stale_promise");
    RunJS("stale_promise.then(() => { result [1] = true; });");
  }
  sub_context->DetachGlobal();
  sub_context.Clear();

  // The context of |stale_handler| and |stale_promise| is detached at this
  // point.
  // Ensure that resolution handling for |stale_handler| is cancelled without
  // crash. Also, the resolution of |stale_promise| is also cancelled.

  SetGlobalProperty("stale_handler", Utils::ToLocal(stale_handler));
  RunJS("%EnqueueMicrotask(stale_handler)");

  v8_isolate()->EnqueueMicrotask(Utils::ToLocal(stale_handler));

  JSPromise::Fulfill(
      stale_promise,
      handle(ReadOnlyRoots(isolate()).undefined_value(), isolate()));

  microtask_queue()->RunMicrotasks(isolate());
  EXPECT_TRUE(
      Object::GetElement(isolate(), result, 0).ToHandleChecked()->IsFalse());
  EXPECT_TRUE(
      Object::GetElement(isolate(), result, 1).ToHandleChecked()->IsFalse());
}

635
TEST_P(MicrotaskQueueTest, MicrotasksScope) {
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  ASSERT_NE(isolate()->default_microtask_queue(), microtask_queue());
  microtask_queue()->set_microtasks_policy(MicrotasksPolicy::kScoped);

  bool ran = false;
  {
    MicrotasksScope scope(v8_isolate(), microtask_queue(),
                          MicrotasksScope::kRunMicrotasks);
    microtask_queue()->EnqueueMicrotask(*NewMicrotask([&ran]() {
      EXPECT_FALSE(ran);
      ran = true;
    }));
  }
  EXPECT_TRUE(ran);
}

651 652 653 654 655 656
INSTANTIATE_TEST_SUITE_P(
    , MicrotaskQueueTest, ::testing::Values(false, true),
    [](const ::testing::TestParamInfo<MicrotaskQueueTest::ParamType>& info) {
      return info.param ? "runtime" : "builtin";
    });

657 658
}  // namespace internal
}  // namespace v8