test-thread-termination.cc 35.3 KB
Newer Older
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 26 27
// Copyright 2009 the V8 project authors. All rights reserved.
// 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.

28
#include "src/api-inl.h"
29
#include "src/isolate.h"
30
#include "src/objects-inl.h"
31 32
#include "src/v8.h"
#include "test/cctest/cctest.h"
33

34
#include "src/base/platform/platform.h"
35

36
v8::base::Semaphore* semaphore = nullptr;
37

38
void Signal(const v8::FunctionCallbackInfo<v8::Value>& args) {
39 40 41 42
  semaphore->Signal();
}


43
void TerminateCurrentThread(const v8::FunctionCallbackInfo<v8::Value>& args) {
44 45
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
  args.GetIsolate()->TerminateExecution();
46 47
}

48
void Fail(const v8::FunctionCallbackInfo<v8::Value>& args) { UNREACHABLE(); }
49

50
void Loop(const v8::FunctionCallbackInfo<v8::Value>& args) {
51 52 53 54
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
  v8::MaybeLocal<v8::Value> result =
      CompileRun(args.GetIsolate()->GetCurrentContext(),
                 "try { doloop(); fail(); } catch(e) { fail(); }");
55
  CHECK(result.IsEmpty());
56
  CHECK(args.GetIsolate()->IsExecutionTerminating());
57 58 59
}


60
void DoLoop(const v8::FunctionCallbackInfo<v8::Value>& args) {
61
  v8::TryCatch try_catch(args.GetIsolate());
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
  v8::MaybeLocal<v8::Value> result =
      CompileRun(args.GetIsolate()->GetCurrentContext(),
                 "function f() {"
                 "  var term = true;"
                 "  try {"
                 "    while(true) {"
                 "      if (term) terminate();"
                 "      term = false;"
                 "    }"
                 "    fail();"
                 "  } catch(e) {"
                 "    fail();"
                 "  }"
                 "}"
                 "f()");
  CHECK(result.IsEmpty());
79 80 81 82
  CHECK(try_catch.HasCaught());
  CHECK(try_catch.Exception()->IsNull());
  CHECK(try_catch.Message().IsEmpty());
  CHECK(!try_catch.CanContinue());
83
  CHECK(args.GetIsolate()->IsExecutionTerminating());
84 85 86
}


87
void DoLoopNoCall(const v8::FunctionCallbackInfo<v8::Value>& args) {
88
  v8::TryCatch try_catch(args.GetIsolate());
89 90 91 92 93 94 95 96 97
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
  v8::MaybeLocal<v8::Value> result =
      CompileRun(args.GetIsolate()->GetCurrentContext(),
                 "var term = true;"
                 "while(true) {"
                 "  if (term) terminate();"
                 "  term = false;"
                 "}");
  CHECK(result.IsEmpty());
98 99 100 101
  CHECK(try_catch.HasCaught());
  CHECK(try_catch.Exception()->IsNull());
  CHECK(try_catch.Message().IsEmpty());
  CHECK(!try_catch.CanContinue());
102
  CHECK(args.GetIsolate()->IsExecutionTerminating());
103 104 105
}


106 107
v8::Local<v8::ObjectTemplate> CreateGlobalTemplate(
    v8::Isolate* isolate, v8::FunctionCallback terminate,
108
    v8::FunctionCallback doloop) {
109 110
  v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
  global->Set(v8_str("terminate"),
111
              v8::FunctionTemplate::New(isolate, terminate));
112 113 114
  global->Set(v8_str("fail"), v8::FunctionTemplate::New(isolate, Fail));
  global->Set(v8_str("loop"), v8::FunctionTemplate::New(isolate, Loop));
  global->Set(v8_str("doloop"), v8::FunctionTemplate::New(isolate, doloop));
115 116 117 118 119 120 121
  return global;
}


// Test that a single thread of JavaScript execution can terminate
// itself.
TEST(TerminateOnlyV8ThreadFromThreadItself) {
122
  v8::HandleScope scope(CcTest::isolate());
123
  v8::Local<v8::ObjectTemplate> global =
124
      CreateGlobalTemplate(CcTest::isolate(), TerminateCurrentThread, DoLoop);
125
  v8::Local<v8::Context> context =
126
      v8::Context::New(CcTest::isolate(), nullptr, global);
127
  v8::Context::Scope context_scope(context);
128
  CHECK(!CcTest::isolate()->IsExecutionTerminating());
129
  // Run a loop that will be infinite if thread termination does not work.
130 131 132 133
  v8::MaybeLocal<v8::Value> result =
      CompileRun(CcTest::isolate()->GetCurrentContext(),
                 "try { loop(); fail(); } catch(e) { fail(); }");
  CHECK(result.IsEmpty());
134
  // Test that we can run the code again after thread termination.
135 136 137 138
  CHECK(!CcTest::isolate()->IsExecutionTerminating());
  result = CompileRun(CcTest::isolate()->GetCurrentContext(),
                      "try { loop(); fail(); } catch(e) { fail(); }");
  CHECK(result.IsEmpty());
139 140 141 142 143 144
}


// Test that a single thread of JavaScript execution can terminate
// itself in a loop that performs no calls.
TEST(TerminateOnlyV8ThreadFromThreadItselfNoLoop) {
145
  v8::HandleScope scope(CcTest::isolate());
146
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
147
      CcTest::isolate(), TerminateCurrentThread, DoLoopNoCall);
148
  v8::Local<v8::Context> context =
149
      v8::Context::New(CcTest::isolate(), nullptr, global);
150
  v8::Context::Scope context_scope(context);
151
  CHECK(!CcTest::isolate()->IsExecutionTerminating());
152
  // Run a loop that will be infinite if thread termination does not work.
153 154 155 156 157
  static const char* source = "try { loop(); fail(); } catch(e) { fail(); }";
  v8::MaybeLocal<v8::Value> result =
      CompileRun(CcTest::isolate()->GetCurrentContext(), source);
  CHECK(result.IsEmpty());
  CHECK(!CcTest::isolate()->IsExecutionTerminating());
158
  // Test that we can run the code again after thread termination.
159 160
  result = CompileRun(CcTest::isolate()->GetCurrentContext(), source);
  CHECK(result.IsEmpty());
161 162 163
}


164
class TerminatorThread : public v8::base::Thread {
165
 public:
166
  explicit TerminatorThread(i::Isolate* isolate)
167 168
      : Thread(Options("TerminatorThread")),
        isolate_(reinterpret_cast<v8::Isolate*>(isolate)) {}
169
  void Run() override {
170
    semaphore->Wait();
171 172
    CHECK(!isolate_->IsExecutionTerminating());
    isolate_->TerminateExecution();
173
  }
174 175 176

 private:
  v8::Isolate* isolate_;
177 178
};

179
void TestTerminatingSlowOperation(const char* source) {
180
  semaphore = new v8::base::Semaphore(0);
181
  TerminatorThread thread(CcTest::i_isolate());
182 183
  thread.Start();

184
  v8::HandleScope scope(CcTest::isolate());
185
  v8::Local<v8::ObjectTemplate> global =
186
      CreateGlobalTemplate(CcTest::isolate(), Signal, DoLoop);
187
  v8::Local<v8::Context> context =
188
      v8::Context::New(CcTest::isolate(), nullptr, global);
189
  v8::Context::Scope context_scope(context);
190 191
  CHECK(!CcTest::isolate()->IsExecutionTerminating());
  v8::MaybeLocal<v8::Value> result =
192
      CompileRun(CcTest::isolate()->GetCurrentContext(), source);
193
  CHECK(result.IsEmpty());
194 195
  thread.Join();
  delete semaphore;
196
  semaphore = nullptr;
197 198
}

199 200 201 202 203 204 205
// Test that a single thread of JavaScript execution can be terminated
// from the side by another thread.
TEST(TerminateOnlyV8ThreadFromOtherThread) {
  // Run a loop that will be infinite if thread termination does not work.
  TestTerminatingSlowOperation("try { loop(); fail(); } catch(e) { fail(); }");
}

206 207
// Test that execution can be terminated from within JSON.stringify.
TEST(TerminateJsonStringify) {
208 209 210 211 212 213 214
  TestTerminatingSlowOperation(
      "var x = [];"
      "x[2**31]=1;"
      "terminate();"
      "JSON.stringify(x);"
      "fail();");
}
215

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
TEST(TerminateBigIntMultiplication) {
  TestTerminatingSlowOperation(
      "terminate();"
      "var a = 5n ** 555555n;"
      "var b = 3n ** 3333333n;"
      "a * b;"
      "fail();");
}

TEST(TerminateBigIntDivision) {
  TestTerminatingSlowOperation(
      "var a = 2n ** 2222222n;"
      "var b = 3n ** 333333n;"
      "terminate();"
      "a / b;"
      "fail();");
}

TEST(TerminateBigIntToString) {
  TestTerminatingSlowOperation(
      "var a = 2n ** 2222222n;"
      "terminate();"
      "a.toString();"
      "fail();");
240
}
241

242 243 244
int call_count = 0;


245
void TerminateOrReturnObject(const v8::FunctionCallbackInfo<v8::Value>& args) {
246
  if (++call_count == 10) {
247 248
    CHECK(!args.GetIsolate()->IsExecutionTerminating());
    args.GetIsolate()->TerminateExecution();
249
    return;
250
  }
251
  v8::Local<v8::Object> result = v8::Object::New(args.GetIsolate());
252 253 254 255
  v8::Maybe<bool> val =
      result->Set(args.GetIsolate()->GetCurrentContext(), v8_str("x"),
                  v8::Integer::New(args.GetIsolate(), 42));
  CHECK(val.FromJust());
256
  args.GetReturnValue().Set(result);
257 258 259
}


260
void LoopGetProperty(const v8::FunctionCallbackInfo<v8::Value>& args) {
261
  v8::TryCatch try_catch(args.GetIsolate());
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
  v8::MaybeLocal<v8::Value> result =
      CompileRun(args.GetIsolate()->GetCurrentContext(),
                 "function f() {"
                 "  try {"
                 "    while(true) {"
                 "      terminate_or_return_object().x;"
                 "    }"
                 "    fail();"
                 "  } catch(e) {"
                 "    (function() {})();"  // trigger stack check.
                 "    fail();"
                 "  }"
                 "}"
                 "f()");
  CHECK(result.IsEmpty());
278 279 280 281
  CHECK(try_catch.HasCaught());
  CHECK(try_catch.Exception()->IsNull());
  CHECK(try_catch.Message().IsEmpty());
  CHECK(!try_catch.CanContinue());
282
  CHECK(args.GetIsolate()->IsExecutionTerminating());
283 284 285 286 287
}


// Test that we correctly handle termination exceptions if they are
// triggered by the creation of error objects in connection with ICs.
288
TEST(TerminateLoadICException) {
289 290
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
291 292 293 294 295
  v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
  global->Set(v8_str("terminate_or_return_object"),
              v8::FunctionTemplate::New(isolate, TerminateOrReturnObject));
  global->Set(v8_str("fail"), v8::FunctionTemplate::New(isolate, Fail));
  global->Set(v8_str("loop"),
296
              v8::FunctionTemplate::New(isolate, LoopGetProperty));
297

298
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
299
  v8::Context::Scope context_scope(context);
300
  CHECK(!isolate->IsExecutionTerminating());
301
  // Run a loop that will be infinite if thread termination does not work.
302
  static const char* source = "try { loop(); fail(); } catch(e) { fail(); }";
303
  call_count = 0;
304 305 306
  v8::MaybeLocal<v8::Value> result =
      CompileRun(isolate->GetCurrentContext(), source);
  CHECK(result.IsEmpty());
307
  // Test that we can run the code again after thread termination.
308
  CHECK(!isolate->IsExecutionTerminating());
309
  call_count = 0;
310 311
  result = CompileRun(isolate->GetCurrentContext(), source);
  CHECK(result.IsEmpty());
312
}
313

314

315 316 317
v8::Persistent<v8::String> reenter_script_1;
v8::Persistent<v8::String> reenter_script_2;

318
void ReenterAfterTermination(const v8::FunctionCallbackInfo<v8::Value>& args) {
319
  v8::TryCatch try_catch(args.GetIsolate());
320
  v8::Isolate* isolate = args.GetIsolate();
321
  CHECK(!isolate->IsExecutionTerminating());
322 323
  v8::Local<v8::String> script =
      v8::Local<v8::String>::New(isolate, reenter_script_1);
324 325
  v8::MaybeLocal<v8::Value> result = CompileRun(script);
  CHECK(result.IsEmpty());
326 327 328 329
  CHECK(try_catch.HasCaught());
  CHECK(try_catch.Exception()->IsNull());
  CHECK(try_catch.Message().IsEmpty());
  CHECK(!try_catch.CanContinue());
330
  CHECK(try_catch.HasTerminated());
331
  CHECK(isolate->IsExecutionTerminating());
332
  script = v8::Local<v8::String>::New(isolate, reenter_script_2);
333 334 335
  v8::MaybeLocal<v8::Script> compiled_script =
      v8::Script::Compile(isolate->GetCurrentContext(), script);
  CHECK(compiled_script.IsEmpty());
336 337
}

338

339 340 341
// Test that reentry into V8 while the termination exception is still pending
// (has not yet unwound the 0-level JS frame) does not crash.
TEST(TerminateAndReenterFromThreadItself) {
342 343
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
344
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
345
      isolate, TerminateCurrentThread, ReenterAfterTermination);
346
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
347
  v8::Context::Scope context_scope(context);
348
  CHECK(!v8::Isolate::GetCurrent()->IsExecutionTerminating());
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  // Create script strings upfront as it won't work when terminating.
  reenter_script_1.Reset(isolate, v8_str(
                                      "function f() {"
                                      "  var term = true;"
                                      "  try {"
                                      "    while(true) {"
                                      "      if (term) terminate();"
                                      "      term = false;"
                                      "    }"
                                      "    fail();"
                                      "  } catch(e) {"
                                      "    fail();"
                                      "  }"
                                      "}"
                                      "f()"));
  reenter_script_2.Reset(isolate, v8_str("function f() { fail(); } f()"));
  CompileRun("try { loop(); fail(); } catch(e) { fail(); }");
366
  CHECK(!isolate->IsExecutionTerminating());
367
  // Check we can run JS again after termination.
368 369 370
  CHECK(CompileRun("function f() { return true; } f()")->IsTrue());
  reenter_script_1.Reset();
  reenter_script_2.Reset();
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 411
TEST(TerminateAndReenterFromThreadItselfWithOuterTryCatch) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
      isolate, TerminateCurrentThread, ReenterAfterTermination);
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
  v8::Context::Scope context_scope(context);
  CHECK(!v8::Isolate::GetCurrent()->IsExecutionTerminating());
  // Create script strings upfront as it won't work when terminating.
  reenter_script_1.Reset(isolate, v8_str("function f() {"
                                         "  var term = true;"
                                         "  try {"
                                         "    while(true) {"
                                         "      if (term) terminate();"
                                         "      term = false;"
                                         "    }"
                                         "    fail();"
                                         "  } catch(e) {"
                                         "    fail();"
                                         "  }"
                                         "}"
                                         "f()"));
  reenter_script_2.Reset(isolate, v8_str("function f() { fail(); } f()"));
  {
    v8::TryCatch try_catch(isolate);
    CompileRun("try { loop(); fail(); } catch(e) { fail(); }");
    CHECK(try_catch.HasCaught());
    CHECK(try_catch.Exception()->IsNull());
    CHECK(try_catch.Message().IsEmpty());
    CHECK(!try_catch.CanContinue());
    CHECK(try_catch.HasTerminated());
    CHECK(isolate->IsExecutionTerminating());
  }
  CHECK(!isolate->IsExecutionTerminating());
  // Check we can run JS again after termination.
  CHECK(CompileRun("function f() { return true; } f()")->IsTrue());
  reenter_script_1.Reset();
  reenter_script_2.Reset();
}
412

413
void DoLoopCancelTerminate(const v8::FunctionCallbackInfo<v8::Value>& args) {
414
  v8::TryCatch try_catch(args.GetIsolate());
415 416 417 418 419 420 421 422 423 424
  CHECK(!v8::Isolate::GetCurrent()->IsExecutionTerminating());
  v8::MaybeLocal<v8::Value> result =
      CompileRun(args.GetIsolate()->GetCurrentContext(),
                 "var term = true;"
                 "while(true) {"
                 "  if (term) terminate();"
                 "  term = false;"
                 "}"
                 "fail();");
  CHECK(result.IsEmpty());
425 426 427 428
  CHECK(try_catch.HasCaught());
  CHECK(try_catch.Exception()->IsNull());
  CHECK(try_catch.Message().IsEmpty());
  CHECK(!try_catch.CanContinue());
429
  CHECK(v8::Isolate::GetCurrent()->IsExecutionTerminating());
430
  CHECK(try_catch.HasTerminated());
431 432
  CcTest::isolate()->CancelTerminateExecution();
  CHECK(!v8::Isolate::GetCurrent()->IsExecutionTerminating());
433 434
}

435

436 437 438
// Test that a single thread of JavaScript execution can terminate
// itself and then resume execution.
TEST(TerminateCancelTerminateFromThreadItself) {
439
  v8::Isolate* isolate = CcTest::isolate();
440
  v8::HandleScope scope(isolate);
441
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
442
      isolate, TerminateCurrentThread, DoLoopCancelTerminate);
443
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
444
  v8::Context::Scope context_scope(context);
445
  CHECK(!CcTest::isolate()->IsExecutionTerminating());
446
  // Check that execution completed with correct return value.
447 448 449 450 451 452
  v8::Local<v8::Value> result =
      CompileRun(isolate->GetCurrentContext(),
                 "try { doloop(); } catch(e) { fail(); } 'completed';")
          .ToLocalChecked();
  CHECK(result->Equals(isolate->GetCurrentContext(), v8_str("completed"))
            .FromJust());
453
}
454 455 456


void MicrotaskShouldNotRun(const v8::FunctionCallbackInfo<v8::Value>& info) {
457
  UNREACHABLE();
458 459 460 461 462 463 464 465
}


void MicrotaskLoopForever(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Isolate* isolate = info.GetIsolate();
  v8::HandleScope scope(isolate);
  // Enqueue another should-not-run task to ensure we clean out the queue
  // when we terminate.
466 467 468
  isolate->EnqueueMicrotask(
      v8::Function::New(isolate->GetCurrentContext(), MicrotaskShouldNotRun)
          .ToLocalChecked());
469
  CompileRun("terminate(); while (true) { }");
470
  CHECK(v8::Isolate::GetCurrent()->IsExecutionTerminating());
471 472 473 474
}


TEST(TerminateFromOtherThreadWhileMicrotaskRunning) {
475
  semaphore = new v8::base::Semaphore(0);
476 477 478 479
  TerminatorThread thread(CcTest::i_isolate());
  thread.Start();

  v8::Isolate* isolate = CcTest::isolate();
480
  isolate->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
481
  v8::HandleScope scope(isolate);
482
  v8::Local<v8::ObjectTemplate> global =
483
      CreateGlobalTemplate(CcTest::isolate(), Signal, DoLoop);
484
  v8::Local<v8::Context> context =
485
      v8::Context::New(CcTest::isolate(), nullptr, global);
486
  v8::Context::Scope context_scope(context);
487 488 489
  isolate->EnqueueMicrotask(
      v8::Function::New(isolate->GetCurrentContext(), MicrotaskLoopForever)
          .ToLocalChecked());
490 491
  // The second task should never be run because we bail out if we're
  // terminating.
492 493 494
  isolate->EnqueueMicrotask(
      v8::Function::New(isolate->GetCurrentContext(), MicrotaskShouldNotRun)
          .ToLocalChecked());
495 496
  isolate->RunMicrotasks();

497
  isolate->CancelTerminateExecution();
498 499 500 501
  isolate->RunMicrotasks();  // should not run MicrotaskShouldNotRun

  thread.Join();
  delete semaphore;
502
  semaphore = nullptr;
503
}
504 505 506 507 508 509 510 511 512 513 514 515 516


static int callback_counter = 0;


static void CounterCallback(v8::Isolate* isolate, void* data) {
  callback_counter++;
}


TEST(PostponeTerminateException) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
517
  v8::Local<v8::ObjectTemplate> global =
518
      CreateGlobalTemplate(CcTest::isolate(), TerminateCurrentThread, DoLoop);
519
  v8::Local<v8::Context> context =
520
      v8::Context::New(CcTest::isolate(), nullptr, global);
521 522
  v8::Context::Scope context_scope(context);

523
  v8::TryCatch try_catch(isolate);
524 525 526 527 528
  static const char* terminate_and_loop =
      "terminate(); for (var i = 0; i < 10000; i++);";

  { // Postpone terminate execution interrupts.
    i::PostponeInterruptsScope p1(CcTest::i_isolate(),
529
                                  i::StackGuard::TERMINATE_EXECUTION);
530 531

    // API interrupts should still be triggered.
532
    CcTest::isolate()->RequestInterrupt(&CounterCallback, nullptr);
533 534 535 536 537 538 539 540 541 542
    CHECK_EQ(0, callback_counter);
    CompileRun(terminate_and_loop);
    CHECK(!try_catch.HasTerminated());
    CHECK_EQ(1, callback_counter);

    { // Postpone API interrupts as well.
      i::PostponeInterruptsScope p2(CcTest::i_isolate(),
                                    i::StackGuard::API_INTERRUPT);

      // None of the two interrupts should trigger.
543
      CcTest::isolate()->RequestInterrupt(&CounterCallback, nullptr);
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
      CompileRun(terminate_and_loop);
      CHECK(!try_catch.HasTerminated());
      CHECK_EQ(1, callback_counter);
    }

    // Now the previously requested API interrupt should trigger.
    CompileRun(terminate_and_loop);
    CHECK(!try_catch.HasTerminated());
    CHECK_EQ(2, callback_counter);
  }

  // Now the previously requested terminate execution interrupt should trigger.
  CompileRun("for (var i = 0; i < 10000; i++);");
  CHECK(try_catch.HasTerminated());
  CHECK_EQ(2, callback_counter);
}
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 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
static void AssertTerminatedCodeRun(v8::Isolate* isolate) {
  v8::TryCatch try_catch(isolate);
  CompileRun("for (var i = 0; i < 10000; i++);");
  CHECK(try_catch.HasTerminated());
}

static void AssertFinishedCodeRun(v8::Isolate* isolate) {
  v8::TryCatch try_catch(isolate);
  CompileRun("for (var i = 0; i < 10000; i++);");
  CHECK(!try_catch.HasTerminated());
}

TEST(SafeForTerminateException) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
  v8::Local<v8::Context> context = v8::Context::New(CcTest::isolate());
  v8::Context::Scope context_scope(context);

  {  // Checks safe for termination scope.
    i::PostponeInterruptsScope p1(CcTest::i_isolate(),
                                  i::StackGuard::TERMINATE_EXECUTION);
    isolate->TerminateExecution();
    AssertFinishedCodeRun(isolate);
    {
      i::SafeForInterruptsScope p2(CcTest::i_isolate(),
                                   i::StackGuard::TERMINATE_EXECUTION);
      AssertTerminatedCodeRun(isolate);
      AssertFinishedCodeRun(isolate);
      isolate->TerminateExecution();
    }
    AssertFinishedCodeRun(isolate);
    isolate->CancelTerminateExecution();
  }

  isolate->TerminateExecution();
  {  // no scope -> postpone
    i::PostponeInterruptsScope p1(CcTest::i_isolate(),
                                  i::StackGuard::TERMINATE_EXECUTION);
    AssertFinishedCodeRun(isolate);
    {  // postpone -> postpone
      i::PostponeInterruptsScope p2(CcTest::i_isolate(),
                                    i::StackGuard::TERMINATE_EXECUTION);
      AssertFinishedCodeRun(isolate);

      {  // postpone -> safe
        i::SafeForInterruptsScope p3(CcTest::i_isolate(),
                                     i::StackGuard::TERMINATE_EXECUTION);
        AssertTerminatedCodeRun(isolate);
        isolate->TerminateExecution();

        {  // safe -> safe
          i::SafeForInterruptsScope p4(CcTest::i_isolate(),
                                       i::StackGuard::TERMINATE_EXECUTION);
          AssertTerminatedCodeRun(isolate);
          isolate->TerminateExecution();

          {  // safe -> postpone
            i::PostponeInterruptsScope p5(CcTest::i_isolate(),
                                          i::StackGuard::TERMINATE_EXECUTION);
            AssertFinishedCodeRun(isolate);
          }  // postpone -> safe

          AssertTerminatedCodeRun(isolate);
          isolate->TerminateExecution();
        }  // safe -> safe

        AssertTerminatedCodeRun(isolate);
        isolate->TerminateExecution();
      }  // safe -> postpone

      AssertFinishedCodeRun(isolate);
    }  // postpone -> postpone

    AssertFinishedCodeRun(isolate);
  }  // postpone -> no scope
  AssertTerminatedCodeRun(isolate);

  isolate->TerminateExecution();
  {  // no scope -> safe
    i::SafeForInterruptsScope p1(CcTest::i_isolate(),
                                 i::StackGuard::TERMINATE_EXECUTION);
    AssertTerminatedCodeRun(isolate);
  }  // safe -> no scope
  AssertFinishedCodeRun(isolate);

  {  // no scope -> postpone
    i::PostponeInterruptsScope p1(CcTest::i_isolate(),
                                  i::StackGuard::TERMINATE_EXECUTION);
    isolate->TerminateExecution();
    {  // postpone -> safe
      i::SafeForInterruptsScope p2(CcTest::i_isolate(),
                                   i::StackGuard::TERMINATE_EXECUTION);
      AssertTerminatedCodeRun(isolate);
    }  // safe -> postpone
  }    // postpone -> no scope
  AssertFinishedCodeRun(isolate);
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

  {  // no scope -> postpone
    i::PostponeInterruptsScope p1(CcTest::i_isolate(),
                                  i::StackGuard::TERMINATE_EXECUTION);
    {  // postpone -> safe
      i::SafeForInterruptsScope p2(CcTest::i_isolate(),
                                   i::StackGuard::TERMINATE_EXECUTION);
      {  // safe -> postpone
        i::PostponeInterruptsScope p3(CcTest::i_isolate(),
                                      i::StackGuard::TERMINATE_EXECUTION);
        isolate->TerminateExecution();
      }  // postpone -> safe
      AssertTerminatedCodeRun(isolate);
    }  // safe -> postpone
  }    // postpone -> no scope
672
}
673

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
void RequestTermianteAndCallAPI(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetIsolate()->TerminateExecution();
  AssertFinishedCodeRun(args.GetIsolate());
}

UNINITIALIZED_TEST(IsolateSafeForTerminationMode) {
  v8::Isolate::CreateParams create_params;
  create_params.only_terminate_in_safe_scope = true;
  create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  {
    v8::Isolate::Scope isolate_scope(isolate);
    v8::HandleScope handle_scope(isolate);
    v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
    global->Set(v8_str("terminateAndCallAPI"),
                v8::FunctionTemplate::New(isolate, RequestTermianteAndCallAPI));
    v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
    v8::Context::Scope context_scope(context);

    // Should postpone termination without safe scope.
    isolate->TerminateExecution();
    AssertFinishedCodeRun(isolate);
    {
      v8::Isolate::SafeForTerminationScope safe_scope(isolate);
      AssertTerminatedCodeRun(isolate);
    }
    AssertFinishedCodeRun(isolate);

    {
      isolate->TerminateExecution();
      AssertFinishedCodeRun(isolate);
      i::PostponeInterruptsScope p1(i_isolate,
                                    i::StackGuard::TERMINATE_EXECUTION);
      {
        // SafeForTermination overrides postpone.
        v8::Isolate::SafeForTerminationScope safe_scope(isolate);
        AssertTerminatedCodeRun(isolate);
      }
      AssertFinishedCodeRun(isolate);
    }

    {
      v8::Isolate::SafeForTerminationScope safe_scope(isolate);
      // Request terminate and call API recursively.
      CompileRun("terminateAndCallAPI()");
      AssertTerminatedCodeRun(isolate);
    }

    {
      i::PostponeInterruptsScope p1(i_isolate,
                                    i::StackGuard::TERMINATE_EXECUTION);
      // Request terminate and call API recursively.
      CompileRun("terminateAndCallAPI()");
      AssertFinishedCodeRun(isolate);
    }
    AssertFinishedCodeRun(isolate);
    {
      v8::Isolate::SafeForTerminationScope safe_scope(isolate);
      AssertTerminatedCodeRun(isolate);
    }
  }
  isolate->Dispose();
}

740 741 742
TEST(ErrorObjectAfterTermination) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
743
  v8::Local<v8::Context> context = v8::Context::New(CcTest::isolate());
744
  v8::Context::Scope context_scope(context);
745
  isolate->TerminateExecution();
746
  v8::Local<v8::Value> error = v8::Exception::Error(v8_str("error"));
jgruber's avatar
jgruber committed
747
  CHECK(error->IsNativeError());
748
}
749 750 751


void InnerTryCallTerminate(const v8::FunctionCallbackInfo<v8::Value>& args) {
752 753 754 755 756
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
  v8::Local<v8::Object> global = CcTest::global();
  v8::Local<v8::Function> loop = v8::Local<v8::Function>::Cast(
      global->Get(CcTest::isolate()->GetCurrentContext(), v8_str("loop"))
          .ToLocalChecked());
757
  i::MaybeHandle<i::Object> exception;
758
  i::MaybeHandle<i::Object> result =
759
      i::Execution::TryCall(CcTest::i_isolate(), v8::Utils::OpenHandle((*loop)),
760 761
                            v8::Utils::OpenHandle((*global)), 0, nullptr,
                            i::Execution::MessageHandling::kReport, &exception);
762 763
  CHECK(result.is_null());
  // TryCall ignores terminate execution, but rerequests the interrupt.
764
  CHECK(!args.GetIsolate()->IsExecutionTerminating());
765 766 767 768 769 770 771
  CHECK(CompileRun("1 + 1;").IsEmpty());
}


TEST(TerminationInInnerTryCall) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
772
  v8::Local<v8::ObjectTemplate> global_template = CreateGlobalTemplate(
773 774 775 776
      CcTest::isolate(), TerminateCurrentThread, DoLoopNoCall);
  global_template->Set(
      v8_str("inner_try_call_terminate"),
      v8::FunctionTemplate::New(isolate, InnerTryCallTerminate));
777
  v8::Local<v8::Context> context =
778
      v8::Context::New(CcTest::isolate(), nullptr, global_template);
779 780
  v8::Context::Scope context_scope(context);
  {
781
    v8::TryCatch try_catch(isolate);
782 783 784
    CompileRun("inner_try_call_terminate()");
    CHECK(try_catch.HasTerminated());
  }
785 786 787 788
  v8::Maybe<int32_t> result = CompileRun("2 + 2")->Int32Value(
      v8::Isolate::GetCurrent()->GetCurrentContext());
  CHECK_EQ(4, result.FromJust());
  CHECK(!v8::Isolate::GetCurrent()->IsExecutionTerminating());
789 790 791 792 793 794 795
}


TEST(TerminateAndTryCall) {
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate* isolate = CcTest::isolate();
  v8::HandleScope scope(isolate);
796
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
797
      isolate, TerminateCurrentThread, DoLoopCancelTerminate);
798
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
799
  v8::Context::Scope context_scope(context);
800
  CHECK(!isolate->IsExecutionTerminating());
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
  {
    v8::TryCatch try_catch(isolate);
    CHECK(!isolate->IsExecutionTerminating());
    // Terminate execution has been triggered inside TryCall, but re-requested
    // to trigger later.
    CHECK(CompileRun("terminate(); reference_error();").IsEmpty());
    CHECK(try_catch.HasCaught());
    CHECK(!isolate->IsExecutionTerminating());
    v8::Local<v8::Value> value =
        CcTest::global()
            ->Get(isolate->GetCurrentContext(), v8_str("terminate"))
            .ToLocalChecked();
    CHECK(value->IsFunction());
    // The first stack check after terminate has been re-requested fails.
    CHECK(CompileRun("1 + 1").IsEmpty());
    CHECK(isolate->IsExecutionTerminating());
  }
818
  // V8 then recovers.
819 820 821 822
  v8::Maybe<int32_t> result = CompileRun("2 + 2")->Int32Value(
      v8::Isolate::GetCurrent()->GetCurrentContext());
  CHECK_EQ(4, result.FromJust());
  CHECK(!isolate->IsExecutionTerminating());
823
}
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840

class ConsoleImpl : public v8::debug::ConsoleDelegate {
 private:
  void Log(const v8::debug::ConsoleCallArguments& args,
           const v8::debug::ConsoleContext&) override {
    CompileRun("1 + 1");
  }
};

TEST(TerminateConsole) {
  i::FLAG_allow_natives_syntax = true;
  v8::Isolate* isolate = CcTest::isolate();
  ConsoleImpl console;
  v8::debug::SetConsoleDelegate(isolate, &console);
  v8::HandleScope scope(isolate);
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
      isolate, TerminateCurrentThread, DoLoopCancelTerminate);
841
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
842 843 844 845 846 847
  v8::Context::Scope context_scope(context);
  CHECK(!isolate->IsExecutionTerminating());
  v8::TryCatch try_catch(isolate);
  CHECK(!isolate->IsExecutionTerminating());
  CHECK(CompileRun("terminate(); console.log(); fail();").IsEmpty());
  CHECK(try_catch.HasCaught());
848
  CHECK(isolate->IsExecutionTerminating());
849
}
850 851 852 853 854 855 856

class TerminatorSleeperThread : public v8::base::Thread {
 public:
  explicit TerminatorSleeperThread(v8::Isolate* isolate, int sleep_ms)
      : Thread(Options("TerminatorSlepperThread")),
        isolate_(isolate),
        sleep_ms_(sleep_ms) {}
857
  void Run() override {
858 859 860 861 862 863 864 865 866 867 868
    v8::base::OS::Sleep(v8::base::TimeDelta::FromMilliseconds(sleep_ms_));
    CHECK(!isolate_->IsExecutionTerminating());
    isolate_->TerminateExecution();
  }

 private:
  v8::Isolate* isolate_;
  int sleep_ms_;
};

TEST(TerminateRegExp) {
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
  // The regexp interpreter does not support preemption.
  if (!i::FLAG_regexp_interpret_all) {
    i::FLAG_allow_natives_syntax = true;
    v8::Isolate* isolate = CcTest::isolate();
    v8::HandleScope scope(isolate);
    v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
        isolate, TerminateCurrentThread, DoLoopCancelTerminate);
    v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
    v8::Context::Scope context_scope(context);
    CHECK(!isolate->IsExecutionTerminating());
    v8::TryCatch try_catch(isolate);
    CHECK(!isolate->IsExecutionTerminating());
    CHECK(!CompileRun("var re = /(x+)+y$/; re.test('x');").IsEmpty());
    TerminatorSleeperThread terminator(isolate, 100);
    terminator.Start();
    CHECK(CompileRun("re.test('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); fail();")
              .IsEmpty());
    CHECK(try_catch.HasCaught());
    CHECK(isolate->IsExecutionTerminating());
  }
889
}
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

TEST(TerminateInMicrotask) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::Locker locker(isolate);
  isolate->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  v8::HandleScope scope(isolate);
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
      isolate, TerminateCurrentThread, DoLoopCancelTerminate);
  v8::Local<v8::Context> context1 = v8::Context::New(isolate, nullptr, global);
  v8::Local<v8::Context> context2 = v8::Context::New(isolate, nullptr, global);
  v8::TryCatch try_catch(isolate);
  {
    v8::Context::Scope context_scope(context1);
    CHECK(!isolate->IsExecutionTerminating());
    CHECK(!CompileRun("Promise.resolve().then(function() {"
                      "terminate(); loop(); fail();})")
               .IsEmpty());
    CHECK(!try_catch.HasCaught());
  }
  {
    v8::Context::Scope context_scope(context2);
    CHECK(context2 == isolate->GetCurrentContext());
912
    CHECK(context2 == isolate->GetEnteredOrMicrotaskContext());
913 914 915
    CHECK(!isolate->IsExecutionTerminating());
    isolate->RunMicrotasks();
    CHECK(context2 == isolate->GetCurrentContext());
916
    CHECK(context2 == isolate->GetEnteredOrMicrotaskContext());
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    CHECK(try_catch.HasCaught());
    CHECK(try_catch.HasTerminated());
  }
  CHECK(!isolate->IsExecutionTerminating());
}

void TerminationMicrotask(void* data) {
  CcTest::isolate()->TerminateExecution();
  CompileRun("");
}

void UnreachableMicrotask(void* data) { UNREACHABLE(); }

TEST(TerminateInApiMicrotask) {
  v8::Isolate* isolate = CcTest::isolate();
  v8::Locker locker(isolate);
  isolate->SetMicrotasksPolicy(v8::MicrotasksPolicy::kExplicit);
  v8::HandleScope scope(isolate);
  v8::Local<v8::ObjectTemplate> global = CreateGlobalTemplate(
      isolate, TerminateCurrentThread, DoLoopCancelTerminate);
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
  v8::TryCatch try_catch(isolate);
  {
    v8::Context::Scope context_scope(context);
    CHECK(!isolate->IsExecutionTerminating());
    isolate->EnqueueMicrotask(TerminationMicrotask);
    isolate->EnqueueMicrotask(UnreachableMicrotask);
    isolate->RunMicrotasks();
    CHECK(try_catch.HasCaught());
    CHECK(try_catch.HasTerminated());
  }
  CHECK(!isolate->IsExecutionTerminating());
}