test-debug.cc 153 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// 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.

#include <stdlib.h>

30
#include "src/init/v8.h"
31

32
#include "src/api/api-inl.h"
33
#include "src/codegen/compilation-cache.h"
34
#include "src/debug/debug-interface.h"
35
#include "src/debug/debug.h"
36
#include "src/deoptimizer/deoptimizer.h"
37
#include "src/execution/frames.h"
38
#include "src/objects/objects-inl.h"
39
#include "src/snapshot/natives.h"
40
#include "src/snapshot/snapshot.h"
41
#include "src/utils/utils.h"
42
#include "test/cctest/cctest.h"
43 44

using ::v8::internal::Handle;
45
using ::v8::internal::StepNone;  // From StepAction enum
46 47 48 49 50 51
using ::v8::internal::StepIn;  // From StepAction enum
using ::v8::internal::StepNext;  // From StepAction enum
using ::v8::internal::StepOut;  // From StepAction enum

// --- H e l p e r   F u n c t i o n s

52 53
// Compile and run the supplied source and return the requested function.
static v8::Local<v8::Function> CompileFunction(v8::Isolate* isolate,
54 55
                                               const char* source,
                                               const char* function_name) {
56 57 58 59 60 61
  CompileRunChecked(isolate, source);
  v8::Local<v8::String> name = v8_str(isolate, function_name);
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
  v8::MaybeLocal<v8::Value> maybe_function =
      context->Global()->Get(context, name);
  return v8::Local<v8::Function>::Cast(maybe_function.ToLocalChecked());
62 63
}

64 65

// Compile and run the supplied source and return the requested function.
66
static v8::Local<v8::Function> CompileFunction(LocalContext* env,
67
                                               const char* source,
68
                                               const char* function_name) {
69
  return CompileFunction((*env)->GetIsolate(), source, function_name);
70
}
71

72
// Is there any debug info for the function?
73
static bool HasBreakInfo(v8::Local<v8::Function> fun) {
74 75
  Handle<v8::internal::JSFunction> f =
      Handle<v8::internal::JSFunction>::cast(v8::Utils::OpenHandle(*fun));
76
  Handle<v8::internal::SharedFunctionInfo> shared(f->shared(), f->GetIsolate());
77
  return shared->HasBreakInfo();
78 79
}

80 81 82 83
// Set a break point in a function with a position relative to function start,
// and return the associated break point number.
static i::Handle<i::BreakPoint> SetBreakPoint(v8::Local<v8::Function> fun,
                                              int position,
84
                                              const char* condition = nullptr) {
85 86
  i::Handle<i::JSFunction> function =
      i::Handle<i::JSFunction>::cast(v8::Utils::OpenHandle(*fun));
87
  position += function->shared().StartPosition();
88 89
  static int break_point_index = 0;
  i::Isolate* isolate = function->GetIsolate();
90 91 92
  i::Handle<i::String> condition_string =
      condition ? isolate->factory()->NewStringFromAsciiChecked(condition)
                : isolate->factory()->empty_string();
93
  i::Debug* debug = isolate->debug();
94 95
  i::Handle<i::BreakPoint> break_point =
      isolate->factory()->NewBreakPoint(++break_point_index, condition_string);
96

97 98
  debug->SetBreakpoint(handle(function->shared(), isolate), break_point,
                       &position);
99 100
  return break_point;
}
101 102


103 104 105 106 107
static void ClearBreakPoint(i::Handle<i::BreakPoint> break_point) {
  v8::internal::Isolate* isolate = CcTest::i_isolate();
  v8::internal::Debug* debug = isolate->debug();
  debug->ClearBreakPoint(break_point);
}
108 109 110 111


// Change break on exception.
static void ChangeBreakOnException(bool caught, bool uncaught) {
112
  v8::internal::Debug* debug = CcTest::i_isolate()->debug();
113 114
  debug->ChangeBreakOnException(v8::internal::BreakException, caught);
  debug->ChangeBreakOnException(v8::internal::BreakUncaughtException, uncaught);
115 116 117 118
}


// Prepare to step to next break location.
119
static void PrepareStep(i::StepAction step_action) {
120
  v8::internal::Debug* debug = CcTest::i_isolate()->debug();
121
  debug->PrepareStep(step_action);
122 123 124 125
}

// This function is in namespace v8::internal to be friend with class
// v8::internal::Debug.
126 127
namespace v8 {
namespace internal {
128 129 130

// Collect the currently debugged functions.
Handle<FixedArray> GetDebuggedFunctions() {
131
  Debug* debug = CcTest::i_isolate()->debug();
132 133

  v8::internal::DebugInfoListNode* node = debug->debug_info_list_;
134 135 136 137 138 139 140 141 142 143

  // Find the number of debugged functions.
  int count = 0;
  while (node) {
    count++;
    node = node->next();
  }

  // Allocate array for the debugged functions
  Handle<FixedArray> debugged_functions =
144
      CcTest::i_isolate()->factory()->NewFixedArray(count);
145 146 147 148 149 150 151 152 153 154 155 156

  // Run through the debug info objects and collect all functions.
  count = 0;
  while (node) {
    debugged_functions->set(count++, *node->debug_info());
    node = node->next();
  }

  return debugged_functions;
}


157
// Check that the debugger has been fully unloaded.
158
void CheckDebuggerUnloaded() {
159 160
  // Check that the debugger context is cleared and that there is no debug
  // information stored for the debugger.
161
  CHECK(!CcTest::i_isolate()->debug()->debug_info_list_);
162 163

  // Collect garbage to ensure weak handles are cleared.
164
  CcTest::CollectAllGarbage();
165
  CcTest::CollectAllGarbage();
166

167
  // Iterate the heap and check that there are no debugger related objects left.
168
  HeapObjectIterator iterator(CcTest::heap());
169 170
  for (HeapObject obj = iterator.Next(); !obj.is_null();
       obj = iterator.Next()) {
171
    CHECK(!obj.IsDebugInfo());
172 173 174 175
  }
}


176 177
}  // namespace internal
}  // namespace v8
178

179 180

// Check that the debugger has been fully unloaded.
181
static void CheckDebuggerUnloaded() { v8::internal::CheckDebuggerUnloaded(); }
182

183 184 185 186 187
// --- D e b u g   E v e n t   H a n d l e r s
// ---
// --- The different tests uses a number of debug event handlers.
// ---

188
// Debug event handler which counts a number of events.
189
int break_point_hit_count = 0;
190
int break_point_hit_count_deoptimize = 0;
191 192
class DebugEventCounter : public v8::debug::DebugDelegate {
 public:
193 194 195
  void BreakProgramRequested(
      v8::Local<v8::Context>,
      const std::vector<v8::debug::BreakpointId>&) override {
196
    break_point_hit_count++;
197 198 199
    // Perform a full deoptimization when the specified number of
    // breaks have been hit.
    if (break_point_hit_count == break_point_hit_count_deoptimize) {
200
      i::Deoptimizer::DeoptimizeAll(CcTest::i_isolate());
201
    }
202
    if (step_action_ != StepNone) PrepareStep(step_action_);
203
  }
204

205 206
  void set_step_action(i::StepAction step_action) {
    step_action_ = step_action;
207
  }
208

209 210
 private:
  i::StepAction step_action_ = StepNone;
211
};
212

213
// Debug event handler which performs a garbage collection.
214 215
class DebugEventBreakPointCollectGarbage : public v8::debug::DebugDelegate {
 public:
216 217 218
  void BreakProgramRequested(
      v8::Local<v8::Context>,
      const std::vector<v8::debug::BreakpointId>&) override {
219 220 221
    // Perform a garbage collection when break point is hit and continue. Based
    // on the number of break points hit either scavenge or mark compact
    // collector is used.
222 223 224
    break_point_hit_count++;
    if (break_point_hit_count % 2 == 0) {
      // Scavenge.
225
      CcTest::CollectGarbage(v8::internal::NEW_SPACE);
226
    } else {
227
      // Mark sweep compact.
228
      CcTest::CollectAllGarbage();
229 230
    }
  }
231
};
232 233 234

// Debug event handler which re-issues a debug break and calls the garbage
// collector to have the heap verified.
235 236
class DebugEventBreak : public v8::debug::DebugDelegate {
 public:
237 238 239
  void BreakProgramRequested(
      v8::Local<v8::Context>,
      const std::vector<v8::debug::BreakpointId>&) override {
240 241 242 243 244
    // Count the number of breaks.
    break_point_hit_count++;

    // Run the garbage collector to enforce heap verification if option
    // --verify-heap is set.
245
    CcTest::CollectGarbage(v8::internal::NEW_SPACE);
246 247

    // Set the break flag again to come back here as soon as possible.
248
    v8::debug::SetBreakOnNextFunctionCall(CcTest::isolate());
249
  }
250
};
251

252 253 254
static void BreakRightNow(v8::Isolate* isolate, void*) {
  v8::debug::BreakRightNow(isolate);
}
255

256 257 258
// Debug event handler which re-issues a debug break until a limit has been
// reached.
int max_break_point_hit_count = 0;
259
bool terminate_after_max_break_point_hit = false;
260 261
class DebugEventBreakMax : public v8::debug::DebugDelegate {
 public:
262 263 264
  void BreakProgramRequested(
      v8::Local<v8::Context>,
      const std::vector<v8::debug::BreakpointId>&) override {
265 266
    v8::Isolate* v8_isolate = CcTest::isolate();
    v8::internal::Isolate* isolate = CcTest::i_isolate();
267 268 269
    if (break_point_hit_count < max_break_point_hit_count) {
      // Count the number of breaks.
      break_point_hit_count++;
270

271
      // Set the break flag again to come back here as soon as possible.
272
      v8_isolate->RequestInterrupt(BreakRightNow, nullptr);
273

274 275
    } else if (terminate_after_max_break_point_hit) {
      // Terminate execution after the last break if requested.
276
      v8_isolate->TerminateExecution();
277
    }
278 279 280 281

    // Perform a full deoptimization when the specified number of
    // breaks have been hit.
    if (break_point_hit_count == break_point_hit_count_deoptimize) {
282
      i::Deoptimizer::DeoptimizeAll(isolate);
283
    }
284
  }
285
};
286 287 288 289 290 291

// --- T h e   A c t u a l   T e s t s

// Test that the debug info in the VM is in sync with the functions being
// debugged.
TEST(DebugInfo) {
292
  LocalContext env;
293
  v8::HandleScope scope(env->GetIsolate());
294 295 296 297 298 299 300
  // Create a couple of functions for the test.
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){}", "foo");
  v8::Local<v8::Function> bar =
      CompileFunction(&env, "function bar(){}", "bar");
  // Initially no functions are debugged.
  CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length());
301 302
  CHECK(!HasBreakInfo(foo));
  CHECK(!HasBreakInfo(bar));
303
  EnableDebugger(env->GetIsolate());
304
  // One function (foo) is debugged.
305
  i::Handle<i::BreakPoint> bp1 = SetBreakPoint(foo, 0);
306
  CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length());
307 308
  CHECK(HasBreakInfo(foo));
  CHECK(!HasBreakInfo(bar));
309
  // Two functions are debugged.
310
  i::Handle<i::BreakPoint> bp2 = SetBreakPoint(bar, 0);
311
  CHECK_EQ(2, v8::internal::GetDebuggedFunctions()->length());
312 313
  CHECK(HasBreakInfo(foo));
  CHECK(HasBreakInfo(bar));
314 315 316
  // One function (bar) is debugged.
  ClearBreakPoint(bp1);
  CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length());
317 318
  CHECK(!HasBreakInfo(foo));
  CHECK(HasBreakInfo(bar));
319 320
  // No functions are debugged.
  ClearBreakPoint(bp2);
321
  DisableDebugger(env->GetIsolate());
322
  CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length());
323 324
  CHECK(!HasBreakInfo(foo));
  CHECK(!HasBreakInfo(bar));
325 326 327 328 329 330
}


// Test that a break point can be set at an IC store location.
TEST(BreakPointICStore) {
  break_point_hit_count = 0;
331
  LocalContext env;
332
  v8::HandleScope scope(env->GetIsolate());
333

334 335
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
336 337
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){bar=0;}", "foo");
338 339

  // Run without breakpoints.
340
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
341 342 343
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint
344
  i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0);
345
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
346
  CHECK_EQ(1, break_point_hit_count);
347
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
348 349 350 351
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
352
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
353 354
  CHECK_EQ(2, break_point_hit_count);

355
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
356
  CheckDebuggerUnloaded();
357 358
}

359 360 361
// Test that a break point can be set at an IC store location.
TEST(BreakPointCondition) {
  break_point_hit_count = 0;
362
  LocalContext env;
363 364
  v8::HandleScope scope(env->GetIsolate());

365 366
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  CompileRun("var a = false");
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo() { return 1 }", "foo");
  // Run without breakpoints.
  CompileRun("foo()");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint
  i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0, "a == true");
  CompileRun("foo()");
  CHECK_EQ(0, break_point_hit_count);

  CompileRun("a = true");
  CompileRun("foo()");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("foo()");
  CHECK_EQ(1, break_point_hit_count);

388
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
389 390
  CheckDebuggerUnloaded();
}
391 392 393 394

// Test that a break point can be set at an IC load location.
TEST(BreakPointICLoad) {
  break_point_hit_count = 0;
395
  LocalContext env;
396
  v8::HandleScope scope(env->GetIsolate());
397 398
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
399 400 401 402

  CompileRunChecked(env->GetIsolate(), "bar=1");
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){var x=bar;}", "foo");
403 404

  // Run without breakpoints.
405
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
406 407
  CHECK_EQ(0, break_point_hit_count);

408
  // Run with breakpoint.
409
  i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0);
410
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
411
  CHECK_EQ(1, break_point_hit_count);
412
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
413 414 415 416
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
417
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
418 419
  CHECK_EQ(2, break_point_hit_count);

420
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
421
  CheckDebuggerUnloaded();
422 423 424 425 426 427
}


// Test that a break point can be set at an IC call location.
TEST(BreakPointICCall) {
  break_point_hit_count = 0;
428
  LocalContext env;
429
  v8::HandleScope scope(env->GetIsolate());
430 431
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
432 433 434
  CompileRunChecked(env->GetIsolate(), "function bar(){}");
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){bar();}", "foo");
435 436

  // Run without breakpoints.
437
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
438 439
  CHECK_EQ(0, break_point_hit_count);

440
  // Run with breakpoint
441
  i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0);
442
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
443
  CHECK_EQ(1, break_point_hit_count);
444
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
445 446 447 448
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
449
  foo->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
450 451
  CHECK_EQ(2, break_point_hit_count);

452
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
453
  CheckDebuggerUnloaded();
454 455 456
}


457 458 459
// Test that a break point can be set at an IC call location and survive a GC.
TEST(BreakPointICCallWithGC) {
  break_point_hit_count = 0;
460
  LocalContext env;
461
  v8::HandleScope scope(env->GetIsolate());
462 463
  DebugEventBreakPointCollectGarbage delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
464 465 466
  CompileRunChecked(env->GetIsolate(), "function bar(){return 1;}");
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){return bar();}", "foo");
467
  v8::Local<v8::Context> context = env.local();
468 469

  // Run without breakpoints.
470
  CHECK_EQ(1, foo->Call(context, env->Global(), 0, nullptr)
471 472 473
                  .ToLocalChecked()
                  ->Int32Value(context)
                  .FromJust());
474 475 476
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
477
  i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0);
478
  CHECK_EQ(1, foo->Call(context, env->Global(), 0, nullptr)
479 480 481
                  .ToLocalChecked()
                  ->Int32Value(context)
                  .FromJust());
482
  CHECK_EQ(1, break_point_hit_count);
483
  CHECK_EQ(1, foo->Call(context, env->Global(), 0, nullptr)
484 485 486
                  .ToLocalChecked()
                  ->Int32Value(context)
                  .FromJust());
487 488 489 490
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
491
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
492 493
  CHECK_EQ(2, break_point_hit_count);

494
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
495
  CheckDebuggerUnloaded();
496 497 498 499 500 501
}


// Test that a break point can be set at an IC call location and survive a GC.
TEST(BreakPointConstructCallWithGC) {
  break_point_hit_count = 0;
502
  LocalContext env;
503
  v8::HandleScope scope(env->GetIsolate());
504 505
  DebugEventBreakPointCollectGarbage delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
506 507 508
  CompileRunChecked(env->GetIsolate(), "function bar(){ this.x = 1;}");
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){return new bar(1).x;}", "foo");
509
  v8::Local<v8::Context> context = env.local();
510 511

  // Run without breakpoints.
512
  CHECK_EQ(1, foo->Call(context, env->Global(), 0, nullptr)
513 514 515
                  .ToLocalChecked()
                  ->Int32Value(context)
                  .FromJust());
516 517 518
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
519
  i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0);
520
  CHECK_EQ(1, foo->Call(context, env->Global(), 0, nullptr)
521 522 523
                  .ToLocalChecked()
                  ->Int32Value(context)
                  .FromJust());
524
  CHECK_EQ(1, break_point_hit_count);
525
  CHECK_EQ(1, foo->Call(context, env->Global(), 0, nullptr)
526 527 528
                  .ToLocalChecked()
                  ->Int32Value(context)
                  .FromJust());
529 530 531 532
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
533
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
534 535
  CHECK_EQ(2, break_point_hit_count);

536
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
537
  CheckDebuggerUnloaded();
538 539 540
}


541
TEST(BreakPointBuiltin) {
542
  LocalContext env;
543 544
  v8::HandleScope scope(env->GetIsolate());

545 546
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
547

548 549 550
  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

551
  // === Test simple builtin ===
552
  break_point_hit_count = 0;
553
  builtin = CompileRun("String.prototype.repeat").As<v8::Function>();
554

555
  // Run with breakpoint.
556 557
  bp = SetBreakPoint(builtin, 0);
  ExpectString("'b'.repeat(10)", "bbbbbbbbbb");
558 559
  CHECK_EQ(1, break_point_hit_count);

560 561 562
  ExpectString("'b'.repeat(10)", "bbbbbbbbbb");
  CHECK_EQ(2, break_point_hit_count);

563 564
  // Run without breakpoints.
  ClearBreakPoint(bp);
565 566 567
  ExpectString("'b'.repeat(10)", "bbbbbbbbbb");
  CHECK_EQ(2, break_point_hit_count);

568
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
569 570 571 572
  CheckDebuggerUnloaded();
}

TEST(BreakPointJSBuiltin) {
573
  LocalContext env;
574 575
  v8::HandleScope scope(env->GetIsolate());

576 577
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
578 579 580 581

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

582 583 584 585 586 587 588
  // === Test JS builtin ===
  break_point_hit_count = 0;
  builtin = CompileRun("Array.prototype.sort").As<v8::Function>();

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  CompileRun("[1,2,3].sort()");
589 590
  CHECK_EQ(1, break_point_hit_count);

591 592 593 594 595 596 597 598
  CompileRun("[1,2,3].sort()");
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("[1,2,3].sort()");
  CHECK_EQ(2, break_point_hit_count);

599
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
600 601 602 603
  CheckDebuggerUnloaded();
}

TEST(BreakPointBoundBuiltin) {
604
  LocalContext env;
605 606
  v8::HandleScope scope(env->GetIsolate());

607 608
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
609 610 611 612

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

613 614 615 616 617 618
  // === Test bound function from a builtin ===
  break_point_hit_count = 0;
  builtin = CompileRun(
                "var boundrepeat = String.prototype.repeat.bind('a');"
                "String.prototype.repeat")
                .As<v8::Function>();
619
  ExpectString("boundrepeat(10)", "aaaaaaaaaa");
620 621 622 623
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
624
  ExpectString("boundrepeat(10)", "aaaaaaaaaa");
625 626 627 628
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
629
  ExpectString("boundrepeat(10)", "aaaaaaaaaa");
630 631
  CHECK_EQ(1, break_point_hit_count);

632
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
633 634 635 636
  CheckDebuggerUnloaded();
}

TEST(BreakPointConstructorBuiltin) {
637
  LocalContext env;
638 639
  v8::HandleScope scope(env->GetIsolate());

640 641
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
642 643 644 645

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

646
  // === Test Promise constructor ===
647 648
  break_point_hit_count = 0;
  builtin = CompileRun("Promise").As<v8::Function>();
649
  ExpectString("(new Promise(()=>{})).toString()", "[object Promise]");
650 651 652 653
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
654
  ExpectString("(new Promise(()=>{})).toString()", "[object Promise]");
655 656 657 658
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
659
  ExpectString("(new Promise(()=>{})).toString()", "[object Promise]");
660 661
  CHECK_EQ(1, break_point_hit_count);

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
  // === Test Object constructor ===
  break_point_hit_count = 0;
  builtin = CompileRun("Object").As<v8::Function>();
  CompileRun("new Object()");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  CompileRun("new Object()");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("new Object()");
  CHECK_EQ(1, break_point_hit_count);

  // === Test Number constructor ===
  break_point_hit_count = 0;
  builtin = CompileRun("Number").As<v8::Function>();
  CompileRun("new Number()");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  CompileRun("new Number()");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("new Number()");
  CHECK_EQ(1, break_point_hit_count);

694
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
695 696 697 698 699
  CheckDebuggerUnloaded();
}

TEST(BreakPointInlinedBuiltin) {
  i::FLAG_allow_natives_syntax = true;
700
  LocalContext env;
701 702
  v8::HandleScope scope(env->GetIsolate());

703 704
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
705 706 707 708

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

709 710 711 712 713
  // === Test inlined builtin ===
  break_point_hit_count = 0;
  builtin = CompileRun("Math.sin").As<v8::Function>();
  CompileRun("function test(x) { return 1 + Math.sin(x) }");
  CompileRun(
714
      "%PrepareFunctionForOptimization(test);"
715 716 717 718 719 720 721 722 723 724 725 726
      "test(0.5); test(0.6);"
      "%OptimizeFunctionOnNextCall(test); test(0.7);");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  CompileRun("Math.sin(0.1);");
  CHECK_EQ(1, break_point_hit_count);
  CompileRun("test(0.2);");
  CHECK_EQ(2, break_point_hit_count);

  // Re-optimize.
727 728 729
  CompileRun(
      "%PrepareFunctionForOptimization(test);"
      "%OptimizeFunctionOnNextCall(test);");
730
  ExpectBoolean("test(0.3) < 2", true);
731 732 733 734 735 736 737
  CHECK_EQ(3, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("test(0.3);");
  CHECK_EQ(3, break_point_hit_count);

738
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
739 740 741 742 743
  CheckDebuggerUnloaded();
}

TEST(BreakPointInlineBoundBuiltin) {
  i::FLAG_allow_natives_syntax = true;
744
  LocalContext env;
745 746
  v8::HandleScope scope(env->GetIsolate());

747 748
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
749 750 751 752

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

753 754
  // === Test inlined bound builtin ===
  break_point_hit_count = 0;
755 756 757 758 759

  builtin = CompileRun(
                "var boundrepeat = String.prototype.repeat.bind('a');"
                "String.prototype.repeat")
                .As<v8::Function>();
760 761
  CompileRun("function test(x) { return 'a' + boundrepeat(x) }");
  CompileRun(
762
      "%PrepareFunctionForOptimization(test);"
763 764 765 766 767 768 769 770 771 772 773 774
      "test(4); test(5);"
      "%OptimizeFunctionOnNextCall(test); test(6);");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  CompileRun("'a'.repeat(2);");
  CHECK_EQ(1, break_point_hit_count);
  CompileRun("test(7);");
  CHECK_EQ(2, break_point_hit_count);

  // Re-optimize.
775 776 777
  CompileRun(
      "%PrepareFunctionForOptimization(f);"
      "%OptimizeFunctionOnNextCall(test);");
778 779 780 781 782 783 784 785
  CompileRun("test(8);");
  CHECK_EQ(3, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("test(9);");
  CHECK_EQ(3, break_point_hit_count);

786
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
787 788 789 790 791 792
  CheckDebuggerUnloaded();
}

TEST(BreakPointInlinedConstructorBuiltin) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_experimental_inline_promise_constructor = true;
793
  LocalContext env;
794 795
  v8::HandleScope scope(env->GetIsolate());

796 797
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
798 799 800 801

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

802 803 804 805 806
  // === Test inlined constructor builtin (regular construct builtin) ===
  break_point_hit_count = 0;
  builtin = CompileRun("Promise").As<v8::Function>();
  CompileRun("function test(x) { return new Promise(()=>x); }");
  CompileRun(
807
      "%PrepareFunctionForOptimization(test);"
808 809 810 811 812 813
      "test(4); test(5);"
      "%OptimizeFunctionOnNextCall(test); test(6);");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
814
  CompileRun("new Promise(()=>{});");
815 816 817 818 819
  CHECK_EQ(1, break_point_hit_count);
  CompileRun("test(7);");
  CHECK_EQ(2, break_point_hit_count);

  // Re-optimize.
820 821 822
  CompileRun(
      "%PrepareFunctionForOptimization(f);"
      "%OptimizeFunctionOnNextCall(test);");
823 824 825 826 827 828 829 830
  CompileRun("test(8);");
  CHECK_EQ(3, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("test(9);");
  CHECK_EQ(3, break_point_hit_count);

831
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
832 833 834 835 836 837
  CheckDebuggerUnloaded();
}

TEST(BreakPointBuiltinConcurrentOpt) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_block_concurrent_recompilation = true;
838
  LocalContext env;
839 840
  v8::HandleScope scope(env->GetIsolate());

841 842
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
843 844 845 846

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

847 848 849 850 851 852
  // === Test concurrent optimization ===
  break_point_hit_count = 0;
  builtin = CompileRun("Math.sin").As<v8::Function>();
  CompileRun("function test(x) { return 1 + Math.sin(x) }");
  // Trigger concurrent compile job. It is suspended until unblock.
  CompileRun(
853
      "%PrepareFunctionForOptimization(test);"
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
      "test(0.5); test(0.6);"
      "%OptimizeFunctionOnNextCall(test, 'concurrent'); test(0.7);");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  // Have the concurrent compile job finish now.
  CompileRun(
      "%UnblockConcurrentRecompilation();"
      "%GetOptimizationStatus(test, 'sync');");
  CompileRun("test(0.2);");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("test(0.3);");
  CHECK_EQ(1, break_point_hit_count);

872
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
873 874 875 876 877
  CheckDebuggerUnloaded();
}

TEST(BreakPointBuiltinTFOperator) {
  i::FLAG_allow_natives_syntax = true;
878
  LocalContext env;
879 880
  v8::HandleScope scope(env->GetIsolate());

881 882
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
883 884 885 886

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

887 888 889 890 891
  // === Test builtin represented as operator ===
  break_point_hit_count = 0;
  builtin = CompileRun("String.prototype.indexOf").As<v8::Function>();
  CompileRun("function test(x) { return 1 + 'foo'.indexOf(x) }");
  CompileRun(
892
      "%PrepareFunctionForOptimization(f);"
893 894 895 896 897 898 899 900 901 902 903 904
      "test('a'); test('b');"
      "%OptimizeFunctionOnNextCall(test); test('c');");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0);
  CompileRun("'bar'.indexOf('x');");
  CHECK_EQ(1, break_point_hit_count);
  CompileRun("test('d');");
  CHECK_EQ(2, break_point_hit_count);

  // Re-optimize.
905 906 907
  CompileRun(
      "%PrepareFunctionForOptimization(f);"
      "%OptimizeFunctionOnNextCall(test);");
908 909 910 911 912 913 914 915
  CompileRun("test('e');");
  CHECK_EQ(3, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("test('f');");
  CHECK_EQ(3, break_point_hit_count);

916
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
917 918 919 920
  CheckDebuggerUnloaded();
}

TEST(BreakPointBuiltinNewContext) {
921
  LocalContext env;
922 923
  v8::HandleScope scope(env->GetIsolate());

924 925
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
926 927 928 929

  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
// === Test builtin from a new context ===
// This does not work with no-snapshot build.
#ifdef V8_USE_SNAPSHOT
  break_point_hit_count = 0;
  builtin = CompileRun("String.prototype.repeat").As<v8::Function>();
  CompileRun("'a'.repeat(10)");
  CHECK_EQ(0, break_point_hit_count);
  // Set breakpoint.
  bp = SetBreakPoint(builtin, 0);

  {
    // Create and use new context after breakpoint has been set.
    v8::HandleScope handle_scope(env->GetIsolate());
    v8::Local<v8::Context> new_context = v8::Context::New(env->GetIsolate());
    v8::Context::Scope context_scope(new_context);

    // Run with breakpoint.
    CompileRun("'b'.repeat(10)");
    CHECK_EQ(1, break_point_hit_count);

    CompileRun("'b'.repeat(10)");
    CHECK_EQ(2, break_point_hit_count);

    // Run without breakpoints.
    ClearBreakPoint(bp);
    CompileRun("'b'.repeat(10)");
    CHECK_EQ(2, break_point_hit_count);
  }
#endif

960
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
961 962 963
  CheckDebuggerUnloaded();
}

964 965 966 967 968
void NoOpFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(v8_num(2));
}

TEST(BreakPointApiFunction) {
969
  LocalContext env;
970 971
  v8::HandleScope scope(env->GetIsolate());

972 973
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
974 975 976 977 978 979 980

  i::Handle<i::BreakPoint> bp;

  v8::Local<v8::FunctionTemplate> function_template =
      v8::FunctionTemplate::New(env->GetIsolate(), NoOpFunctionCallback);

  v8::Local<v8::Function> function =
981
      function_template->GetFunction(env.local()).ToLocalChecked();
982

983
  env->Global()->Set(env.local(), v8_str("f"), function).ToChecked();
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000

  // === Test simple builtin ===
  break_point_hit_count = 0;

  // Run with breakpoint.
  bp = SetBreakPoint(function, 0);
  ExpectInt32("f()", 2);
  CHECK_EQ(1, break_point_hit_count);

  ExpectInt32("f()", 2);
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  ExpectInt32("f()", 2);
  CHECK_EQ(2, break_point_hit_count);

1001
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1002 1003 1004
  CheckDebuggerUnloaded();
}

1005 1006 1007 1008 1009 1010 1011 1012 1013
void GetWrapperCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  args.GetReturnValue().Set(
      args[0]
          .As<v8::Object>()
          ->Get(args.GetIsolate()->GetCurrentContext(), args[1])
          .ToLocalChecked());
}

TEST(BreakPointApiGetter) {
1014
  LocalContext env;
1015 1016
  v8::HandleScope scope(env->GetIsolate());

1017 1018
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1019 1020 1021 1022 1023 1024 1025 1026 1027

  i::Handle<i::BreakPoint> bp;

  v8::Local<v8::FunctionTemplate> function_template =
      v8::FunctionTemplate::New(env->GetIsolate(), NoOpFunctionCallback);
  v8::Local<v8::FunctionTemplate> get_template =
      v8::FunctionTemplate::New(env->GetIsolate(), GetWrapperCallback);

  v8::Local<v8::Function> function =
1028
      function_template->GetFunction(env.local()).ToLocalChecked();
1029
  v8::Local<v8::Function> get =
1030
      get_template->GetFunction(env.local()).ToLocalChecked();
1031

1032 1033
  env->Global()->Set(env.local(), v8_str("f"), function).ToChecked();
  env->Global()->Set(env.local(), v8_str("get_wrapper"), get).ToChecked();
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  CompileRun(
      "var o = {};"
      "Object.defineProperty(o, 'f', { get: f, enumerable: true });");

  // === Test API builtin as getter ===
  break_point_hit_count = 0;

  // Run with breakpoint.
  bp = SetBreakPoint(function, 0);
  CompileRun("get_wrapper(o, 'f')");
  CHECK_EQ(1, break_point_hit_count);

  CompileRun("o.f");
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("get_wrapper(o, 'f', 2)");
  CHECK_EQ(2, break_point_hit_count);

1054
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
  CheckDebuggerUnloaded();
}

void SetWrapperCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
  CHECK(args[0]
            .As<v8::Object>()
            ->Set(args.GetIsolate()->GetCurrentContext(), args[1], args[2])
            .FromJust());
}

TEST(BreakPointApiSetter) {
1066
  LocalContext env;
1067 1068
  v8::HandleScope scope(env->GetIsolate());

1069 1070
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1071 1072 1073 1074 1075 1076 1077 1078 1079

  i::Handle<i::BreakPoint> bp;

  v8::Local<v8::FunctionTemplate> function_template =
      v8::FunctionTemplate::New(env->GetIsolate(), NoOpFunctionCallback);
  v8::Local<v8::FunctionTemplate> set_template =
      v8::FunctionTemplate::New(env->GetIsolate(), SetWrapperCallback);

  v8::Local<v8::Function> function =
1080
      function_template->GetFunction(env.local()).ToLocalChecked();
1081
  v8::Local<v8::Function> set =
1082
      set_template->GetFunction(env.local()).ToLocalChecked();
1083

1084 1085
  env->Global()->Set(env.local(), v8_str("f"), function).ToChecked();
  env->Global()->Set(env.local(), v8_str("set_wrapper"), set).ToChecked();
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

  CompileRun(
      "var o = {};"
      "Object.defineProperty(o, 'f', { set: f, enumerable: true });");

  // === Test API builtin as setter ===
  break_point_hit_count = 0;

  // Run with breakpoint.
  bp = SetBreakPoint(function, 0);

  CompileRun("o.f = 3");
  CHECK_EQ(1, break_point_hit_count);

  CompileRun("set_wrapper(o, 'f', 2)");
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("o.f = 3");
  CHECK_EQ(2, break_point_hit_count);

  // === Test API builtin as setter, with condition ===
  break_point_hit_count = 0;

  // Run with breakpoint.
  bp = SetBreakPoint(function, 0, "arguments[0] == 3");
  CompileRun("set_wrapper(o, 'f', 2)");
  CHECK_EQ(0, break_point_hit_count);

  CompileRun("set_wrapper(o, 'f', 3)");
  CHECK_EQ(1, break_point_hit_count);

  CompileRun("o.f = 3");
  CHECK_EQ(2, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("set_wrapper(o, 'f', 2)");
  CHECK_EQ(2, break_point_hit_count);

1127
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1128 1129 1130 1131
  CheckDebuggerUnloaded();
}

TEST(BreakPointApiAccessor) {
1132
  LocalContext env;
1133 1134
  v8::HandleScope scope(env->GetIsolate());

1135 1136
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147

  i::Handle<i::BreakPoint> bp;

  // Create 'foo' class, with a hidden property.
  v8::Local<v8::ObjectTemplate> obj_template =
      v8::ObjectTemplate::New(env->GetIsolate());
  v8::Local<v8::FunctionTemplate> accessor_template =
      v8::FunctionTemplate::New(env->GetIsolate(), NoOpFunctionCallback);
  obj_template->SetAccessorProperty(v8_str("f"), accessor_template,
                                    accessor_template);
  v8::Local<v8::Object> obj =
1148 1149
      obj_template->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("o"), obj).ToChecked();
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

  v8::Local<v8::Function> function =
      CompileRun("Object.getOwnPropertyDescriptor(o, 'f').set")
          .As<v8::Function>();

  // === Test API accessor ===
  break_point_hit_count = 0;

  CompileRun("function get_loop() { for (var i = 0; i < 10; i++) o.f }");
  CompileRun("function set_loop() { for (var i = 0; i < 10; i++) o.f = 2 }");

  CompileRun("get_loop(); set_loop();");  // Initialize ICs.

  // Run with breakpoint.
  bp = SetBreakPoint(function, 0);

  CompileRun("o.f = 3");
  CHECK_EQ(1, break_point_hit_count);

  CompileRun("o.f");
  CHECK_EQ(2, break_point_hit_count);

  CompileRun("for (var i = 0; i < 10; i++) o.f");
  CHECK_EQ(12, break_point_hit_count);

  CompileRun("get_loop();");
  CHECK_EQ(22, break_point_hit_count);

  CompileRun("for (var i = 0; i < 10; i++) o.f = 2");
  CHECK_EQ(32, break_point_hit_count);

  CompileRun("set_loop();");
  CHECK_EQ(42, break_point_hit_count);

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
  // Test that the break point also works when we install the function
  // template on a new property (with a fresh AccessorPair instance).
  v8::Local<v8::ObjectTemplate> baz_template =
      v8::ObjectTemplate::New(env->GetIsolate());
  baz_template->SetAccessorProperty(v8_str("g"), accessor_template,
                                    accessor_template);
  v8::Local<v8::Object> baz =
      baz_template->NewInstance(env.local()).ToLocalChecked();
  env->Global()->Set(env.local(), v8_str("b"), baz).ToChecked();

  CompileRun("b.g = 4");
  CHECK_EQ(43, break_point_hit_count);

  CompileRun("b.g");
  CHECK_EQ(44, break_point_hit_count);

1200 1201 1202 1203
  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("o.f = 3");
  CompileRun("o.f");
1204
  CHECK_EQ(44, break_point_hit_count);
1205

1206
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1207 1208 1209
  CheckDebuggerUnloaded();
}

1210 1211
TEST(BreakPointInlineApiFunction) {
  i::FLAG_allow_natives_syntax = true;
1212
  LocalContext env;
1213 1214
  v8::HandleScope scope(env->GetIsolate());

1215 1216
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1217 1218 1219 1220 1221 1222 1223

  i::Handle<i::BreakPoint> bp;

  v8::Local<v8::FunctionTemplate> function_template =
      v8::FunctionTemplate::New(env->GetIsolate(), NoOpFunctionCallback);

  v8::Local<v8::Function> function =
1224
      function_template->GetFunction(env.local()).ToLocalChecked();
1225

1226
  env->Global()->Set(env.local(), v8_str("f"), function).ToChecked();
1227 1228 1229
  CompileRun(
      "function g() { return 1 +  f(); };"
      "%PrepareFunctionForOptimization(g);");
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

  // === Test simple builtin ===
  break_point_hit_count = 0;

  // Run with breakpoint.
  bp = SetBreakPoint(function, 0);
  ExpectInt32("g()", 3);
  CHECK_EQ(1, break_point_hit_count);

  ExpectInt32("g()", 3);
  CHECK_EQ(2, break_point_hit_count);

  CompileRun("%OptimizeFunctionOnNextCall(g)");
  ExpectInt32("g()", 3);
  CHECK_EQ(3, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  ExpectInt32("g()", 3);
  CHECK_EQ(3, break_point_hit_count);

1251
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1252 1253 1254
  CheckDebuggerUnloaded();
}

1255 1256 1257 1258
// Test that a break point can be set at a return store location.
TEST(BreakPointConditionBuiltin) {
  i::FLAG_allow_natives_syntax = true;
  i::FLAG_block_concurrent_recompilation = true;
1259
  LocalContext env;
1260 1261
  v8::HandleScope scope(env->GetIsolate());

1262 1263
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
  v8::Local<v8::Function> builtin;
  i::Handle<i::BreakPoint> bp;

  // === Test global variable ===
  break_point_hit_count = 0;
  builtin = CompileRun("String.prototype.repeat").As<v8::Function>();
  CompileRun("var condition = false");
  CompileRun("'a'.repeat(10)");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0, "condition == true");
  CompileRun("'b'.repeat(10)");
  CHECK_EQ(0, break_point_hit_count);

  CompileRun("condition = true");
  CompileRun("'b'.repeat(10)");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("'b'.repeat(10)");
  CHECK_EQ(1, break_point_hit_count);

1288
  // === Test arguments ===
1289 1290
  break_point_hit_count = 0;
  builtin = CompileRun("String.prototype.repeat").As<v8::Function>();
1291
  CompileRun("function f(x) { return 'a'.repeat(x * 2); }");
1292 1293 1294
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
1295 1296
  bp = SetBreakPoint(builtin, 0, "arguments[0] == 20");
  ExpectString("f(5)", "aaaaaaaaaa");
1297 1298
  CHECK_EQ(0, break_point_hit_count);

1299
  ExpectString("f(10)", "aaaaaaaaaaaaaaaaaaaa");
1300 1301 1302 1303
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
1304
  ExpectString("f(10)", "aaaaaaaaaaaaaaaaaaaa");
1305 1306
  CHECK_EQ(1, break_point_hit_count);

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
  // === Test adapted arguments ===
  break_point_hit_count = 0;
  builtin = CompileRun("String.prototype.repeat").As<v8::Function>();
  CompileRun("function f(x) { return 'a'.repeat(x * 2, x); }");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0,
                     "arguments[1] == 10 && arguments[2] == undefined");
  ExpectString("f(5)", "aaaaaaaaaa");
  CHECK_EQ(0, break_point_hit_count);

  ExpectString("f(10)", "aaaaaaaaaaaaaaaaaaaa");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  ExpectString("f(10)", "aaaaaaaaaaaaaaaaaaaa");
  CHECK_EQ(1, break_point_hit_count);

1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
  // === Test var-arg builtins ===
  break_point_hit_count = 0;
  builtin = CompileRun("String.fromCharCode").As<v8::Function>();
  CompileRun("function f() { return String.fromCharCode(1, 2, 3); }");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0, "arguments.length == 3 && arguments[1] == 2");
  CompileRun("f(1, 2, 3)");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("f(1, 2, 3)");
  CHECK_EQ(1, break_point_hit_count);

  // === Test rest arguments ===
  break_point_hit_count = 0;
  builtin = CompileRun("String.fromCharCode").As<v8::Function>();
  CompileRun("function f(...args) { return String.fromCharCode(...args); }");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0, "arguments.length == 3 && arguments[1] == 2");
  CompileRun("f(1, 2, 3)");
  CHECK_EQ(1, break_point_hit_count);

  ClearBreakPoint(bp);
  CompileRun("f(1, 3, 3)");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("f(1, 2, 3)");
  CHECK_EQ(1, break_point_hit_count);

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
  // === Test receiver ===
  break_point_hit_count = 0;
  builtin = CompileRun("String.prototype.repeat").As<v8::Function>();
  CompileRun("function f(x) { return x.repeat(10); }");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
  bp = SetBreakPoint(builtin, 0, "this == 'a'");
  ExpectString("f('b')", "bbbbbbbbbb");
  CHECK_EQ(0, break_point_hit_count);

  ExpectString("f('a')", "aaaaaaaaaa");
  CHECK_EQ(1, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  ExpectString("f('a')", "aaaaaaaaaa");
  CHECK_EQ(1, break_point_hit_count);
1381

1382
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1383 1384 1385 1386 1387 1388
  CheckDebuggerUnloaded();
}

TEST(BreakPointInlining) {
  i::FLAG_allow_natives_syntax = true;
  break_point_hit_count = 0;
1389
  LocalContext env;
1390 1391
  v8::HandleScope scope(env->GetIsolate());

1392 1393
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1394 1395 1396 1397 1398 1399

  break_point_hit_count = 0;
  v8::Local<v8::Function> inlinee =
      CompileRun("function f(x) { return x*2; } f").As<v8::Function>();
  CompileRun("function test(x) { return 1 + f(x) }");
  CompileRun(
1400
      "%PrepareFunctionForOptimization(test);"
1401 1402 1403 1404 1405
      "test(0.5); test(0.6);"
      "%OptimizeFunctionOnNextCall(test); test(0.7);");
  CHECK_EQ(0, break_point_hit_count);

  // Run with breakpoint.
1406
  i::Handle<i::BreakPoint> bp = SetBreakPoint(inlinee, 0);
1407 1408 1409 1410 1411 1412
  CompileRun("f(0.1);");
  CHECK_EQ(1, break_point_hit_count);
  CompileRun("test(0.2);");
  CHECK_EQ(2, break_point_hit_count);

  // Re-optimize.
1413 1414 1415
  CompileRun(
      "%PrepareFunctionForOptimization(test);"
      "%OptimizeFunctionOnNextCall(test);");
1416 1417 1418 1419 1420 1421 1422 1423
  CompileRun("test(0.3);");
  CHECK_EQ(3, break_point_hit_count);

  // Run without breakpoints.
  ClearBreakPoint(bp);
  CompileRun("test(0.3);");
  CHECK_EQ(3, break_point_hit_count);

1424
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1425 1426
  CheckDebuggerUnloaded();
}
1427

1428 1429
static void CallWithBreakPoints(v8::Local<v8::Context> context,
                                v8::Local<v8::Object> recv,
1430
                                v8::Local<v8::Function> f,
1431
                                int break_point_count, int call_count) {
1432 1433
  break_point_hit_count = 0;
  for (int i = 0; i < call_count; i++) {
1434
    f->Call(context, recv, 0, nullptr).ToLocalChecked();
1435 1436 1437 1438
    CHECK_EQ((i + 1) * break_point_count, break_point_hit_count);
  }
}

1439

1440 1441 1442
// Test GC during break point processing.
TEST(GCDuringBreakPointProcessing) {
  break_point_hit_count = 0;
1443
  LocalContext env;
1444
  v8::HandleScope scope(env->GetIsolate());
1445
  v8::Local<v8::Context> context = env.local();
1446

1447 1448
  DebugEventBreakPointCollectGarbage delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1449 1450 1451 1452 1453
  v8::Local<v8::Function> foo;

  // Test IC store break point with garbage collection.
  foo = CompileFunction(&env, "function foo(){bar=0;}", "foo");
  SetBreakPoint(foo, 0);
1454
  CallWithBreakPoints(context, env->Global(), foo, 1, 10);
1455 1456 1457 1458

  // Test IC load break point with garbage collection.
  foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo");
  SetBreakPoint(foo, 0);
1459
  CallWithBreakPoints(context, env->Global(), foo, 1, 10);
1460 1461 1462 1463

  // Test IC call break point with garbage collection.
  foo = CompileFunction(&env, "function bar(){};function foo(){bar();}", "foo");
  SetBreakPoint(foo, 0);
1464
  CallWithBreakPoints(context, env->Global(), foo, 1, 10);
1465 1466 1467 1468

  // Test return break point with garbage collection.
  foo = CompileFunction(&env, "function foo(){}", "foo");
  SetBreakPoint(foo, 0);
1469
  CallWithBreakPoints(context, env->Global(), foo, 1, 25);
1470

1471 1472 1473
  // Test debug break slot break point with garbage collection.
  foo = CompileFunction(&env, "function foo(){var a;}", "foo");
  SetBreakPoint(foo, 0);
1474
  CallWithBreakPoints(context, env->Global(), foo, 1, 25);
1475

1476
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1477
  CheckDebuggerUnloaded();
1478 1479 1480 1481 1482
}


// Call the function three times with different garbage collections in between
// and make sure that the break point survives.
1483 1484
static void CallAndGC(v8::Local<v8::Context> context,
                      v8::Local<v8::Object> recv, v8::Local<v8::Function> f) {
1485 1486 1487 1488
  break_point_hit_count = 0;

  for (int i = 0; i < 3; i++) {
    // Call function.
1489
    f->Call(context, recv, 0, nullptr).ToLocalChecked();
1490 1491 1492
    CHECK_EQ(1 + i * 3, break_point_hit_count);

    // Scavenge and call function.
1493
    CcTest::CollectGarbage(v8::internal::NEW_SPACE);
1494
    f->Call(context, recv, 0, nullptr).ToLocalChecked();
1495 1496 1497
    CHECK_EQ(2 + i * 3, break_point_hit_count);

    // Mark sweep (and perhaps compact) and call function.
1498
    CcTest::CollectAllGarbage();
1499
    f->Call(context, recv, 0, nullptr).ToLocalChecked();
1500 1501 1502 1503 1504
    CHECK_EQ(3 + i * 3, break_point_hit_count);
  }
}


1505 1506
// Test that a break point can be set at a return store location.
TEST(BreakPointSurviveGC) {
1507
  break_point_hit_count = 0;
1508
  LocalContext env;
1509
  v8::HandleScope scope(env->GetIsolate());
1510
  v8::Local<v8::Context> context = env.local();
1511

1512 1513
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1514 1515 1516
  v8::Local<v8::Function> foo;

  // Test IC store break point with garbage collection.
1517
  {
1518
    CompileFunction(&env, "function foo(){}", "foo");
1519 1520 1521
    foo = CompileFunction(&env, "function foo(){bar=0;}", "foo");
    SetBreakPoint(foo, 0);
  }
1522
  CallAndGC(context, env->Global(), foo);
1523 1524

  // Test IC load break point with garbage collection.
1525
  {
1526
    CompileFunction(&env, "function foo(){}", "foo");
1527 1528 1529
    foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo");
    SetBreakPoint(foo, 0);
  }
1530
  CallAndGC(context, env->Global(), foo);
1531 1532

  // Test IC call break point with garbage collection.
1533
  {
1534
    CompileFunction(&env, "function foo(){}", "foo");
1535 1536 1537 1538 1539
    foo = CompileFunction(&env,
                          "function bar(){};function foo(){bar();}",
                          "foo");
    SetBreakPoint(foo, 0);
  }
1540
  CallAndGC(context, env->Global(), foo);
1541 1542

  // Test return break point with garbage collection.
1543
  {
1544
    CompileFunction(&env, "function foo(){}", "foo");
1545 1546 1547
    foo = CompileFunction(&env, "function foo(){}", "foo");
    SetBreakPoint(foo, 0);
  }
1548
  CallAndGC(context, env->Global(), foo);
1549

1550 1551
  // Test non IC break point with garbage collection.
  {
1552
    CompileFunction(&env, "function foo(){}", "foo");
1553 1554 1555
    foo = CompileFunction(&env, "function foo(){var bar=0;}", "foo");
    SetBreakPoint(foo, 0);
  }
1556
  CallAndGC(context, env->Global(), foo);
1557

1558
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1559
  CheckDebuggerUnloaded();
1560 1561 1562 1563 1564
}

// Test that the debugger statement causes a break.
TEST(DebuggerStatement) {
  break_point_hit_count = 0;
1565
  LocalContext env;
1566
  v8::HandleScope scope(env->GetIsolate());
1567 1568 1569
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
  v8::Local<v8::Context> context = env.local();
1570 1571 1572 1573 1574
  v8::Script::Compile(context,
                      v8_str(env->GetIsolate(), "function bar(){debugger}"))
      .ToLocalChecked()
      ->Run(context)
      .ToLocalChecked();
1575
  v8::Script::Compile(
1576 1577 1578 1579
      context, v8_str(env->GetIsolate(), "function foo(){debugger;debugger;}"))
      .ToLocalChecked()
      ->Run(context)
      .ToLocalChecked();
1580
  v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1581 1582 1583
      env->Global()
          ->Get(context, v8_str(env->GetIsolate(), "foo"))
          .ToLocalChecked());
1584
  v8::Local<v8::Function> bar = v8::Local<v8::Function>::Cast(
1585 1586 1587
      env->Global()
          ->Get(context, v8_str(env->GetIsolate(), "bar"))
          .ToLocalChecked());
1588 1589

  // Run function with debugger statement
1590
  bar->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1591 1592 1593
  CHECK_EQ(1, break_point_hit_count);

  // Run function with two debugger statement
1594
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1595 1596
  CHECK_EQ(3, break_point_hit_count);

1597
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1598
  CheckDebuggerUnloaded();
1599 1600 1601
}


1602
// Test setting a breakpoint on the debugger statement.
1603 1604
TEST(DebuggerStatementBreakpoint) {
    break_point_hit_count = 0;
1605
    LocalContext env;
1606
    v8::HandleScope scope(env->GetIsolate());
1607 1608 1609
    v8::Local<v8::Context> context = env.local();
    DebugEventCounter delegate;
    v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1610 1611 1612 1613 1614
    v8::Script::Compile(context,
                        v8_str(env->GetIsolate(), "function foo(){debugger;}"))
        .ToLocalChecked()
        ->Run(context)
        .ToLocalChecked();
1615
    v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1616 1617 1618
        env->Global()
            ->Get(context, v8_str(env->GetIsolate(), "foo"))
            .ToLocalChecked());
1619

1620
    // The debugger statement triggers breakpoint hit
1621
    foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1622 1623
    CHECK_EQ(1, break_point_hit_count);

1624
    i::Handle<i::BreakPoint> bp = SetBreakPoint(foo, 0);
1625 1626

    // Set breakpoint does not duplicate hits
1627
    foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1628 1629 1630
    CHECK_EQ(2, break_point_hit_count);

    ClearBreakPoint(bp);
1631
    v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1632
    CheckDebuggerUnloaded();
1633 1634 1635
}


1636 1637 1638
// Test that the conditional breakpoints work event if code generation from
// strings is prohibited in the debugee context.
TEST(ConditionalBreakpointWithCodeGenerationDisallowed) {
1639
  LocalContext env;
1640
  v8::HandleScope scope(env->GetIsolate());
1641

1642 1643
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1644

1645
  v8::Local<v8::Context> context = env.local();
1646 1647 1648 1649 1650 1651 1652 1653
  v8::Local<v8::Function> foo = CompileFunction(&env,
    "function foo(x) {\n"
    "  var s = 'String value2';\n"
    "  return s + x;\n"
    "}",
    "foo");

  // Set conditional breakpoint with condition 'true'.
1654
  SetBreakPoint(foo, 4, "true");
1655

1656
  break_point_hit_count = 0;
1657
  env->AllowCodeGenerationFromStrings(false);
1658
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1659
  CHECK_EQ(1, break_point_hit_count);
1660

1661
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1662
  CheckDebuggerUnloaded();
1663 1664 1665
}


1666 1667
// Simple test of the stepping mechanism using only store ICs.
TEST(DebugStepLinear) {
1668
  LocalContext env;
1669
  v8::HandleScope scope(env->GetIsolate());
1670 1671 1672 1673 1674

  // Create a function for testing stepping.
  v8::Local<v8::Function> foo = CompileFunction(&env,
                                                "function foo(){a=1;b=1;c=1;}",
                                                "foo");
1675 1676 1677 1678

  // Run foo to allow it to get optimized.
  CompileRun("a=0; b=0; c=0; foo();");

1679
  // Register a debug event listener which steps and counts.
1680 1681
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1682

1683 1684
  SetBreakPoint(foo, 3);

1685
  run_step.set_step_action(StepIn);
1686
  break_point_hit_count = 0;
1687
  v8::Local<v8::Context> context = env.local();
1688
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1689 1690 1691 1692

  // With stepping all break locations are hit.
  CHECK_EQ(4, break_point_hit_count);

1693
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1694
  CheckDebuggerUnloaded();
1695 1696

  // Register a debug event listener which just counts.
1697 1698
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1699

1700
  SetBreakPoint(foo, 3);
1701
  break_point_hit_count = 0;
1702
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1703 1704 1705 1706

  // Without stepping only active break points are hit.
  CHECK_EQ(1, break_point_hit_count);

1707
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1708
  CheckDebuggerUnloaded();
1709 1710 1711
}


1712 1713
// Test of the stepping mechanism for keyed load in a loop.
TEST(DebugStepKeyedLoadLoop) {
1714
  LocalContext env;
1715
  v8::HandleScope scope(env->GetIsolate());
1716

1717
  // Register a debug event listener which steps and counts.
1718 1719
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1720

1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
  // Create a function for testing stepping of keyed load. The statement 'y=1'
  // is there to have more than one breakable statement in the loop, TODO(315).
  v8::Local<v8::Function> foo = CompileFunction(
      &env,
      "function foo(a) {\n"
      "  var x;\n"
      "  var len = a.length;\n"
      "  for (var i = 0; i < len; i++) {\n"
      "    y = 1;\n"
      "    x = a[i];\n"
      "  }\n"
1732 1733
      "}\n"
      "y=0\n",
1734 1735
      "foo");

1736
  v8::Local<v8::Context> context = env.local();
1737
  // Create array [0,1,2,3,4,5,6,7,8,9]
1738
  v8::Local<v8::Array> a = v8::Array::New(env->GetIsolate(), 10);
1739
  for (int i = 0; i < 10; i++) {
1740 1741 1742
    CHECK(a->Set(context, v8::Number::New(env->GetIsolate(), i),
                 v8::Number::New(env->GetIsolate(), i))
              .FromJust());
1743 1744 1745 1746
  }

  // Call function without any break points to ensure inlining is in place.
  const int kArgc = 1;
1747 1748
  v8::Local<v8::Value> args[kArgc] = {a};
  foo->Call(context, env->Global(), kArgc, args).ToLocalChecked();
1749

1750
  // Set up break point and step through the function.
1751
  SetBreakPoint(foo, 3);
1752
  run_step.set_step_action(StepNext);
1753
  break_point_hit_count = 0;
1754
  foo->Call(context, env->Global(), kArgc, args).ToLocalChecked();
1755 1756

  // With stepping all break locations are hit.
1757
  CHECK_EQ(44, break_point_hit_count);
1758

1759
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1760
  CheckDebuggerUnloaded();
1761 1762 1763
}


1764 1765
// Test of the stepping mechanism for keyed store in a loop.
TEST(DebugStepKeyedStoreLoop) {
1766
  LocalContext env;
1767
  v8::HandleScope scope(env->GetIsolate());
1768

1769
  // Register a debug event listener which steps and counts.
1770 1771
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1772

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
  // Create a function for testing stepping of keyed store. The statement 'y=1'
  // is there to have more than one breakable statement in the loop, TODO(315).
  v8::Local<v8::Function> foo = CompileFunction(
      &env,
      "function foo(a) {\n"
      "  var len = a.length;\n"
      "  for (var i = 0; i < len; i++) {\n"
      "    y = 1;\n"
      "    a[i] = 42;\n"
      "  }\n"
1783 1784
      "}\n"
      "y=0\n",
1785 1786
      "foo");

1787
  v8::Local<v8::Context> context = env.local();
1788
  // Create array [0,1,2,3,4,5,6,7,8,9]
1789
  v8::Local<v8::Array> a = v8::Array::New(env->GetIsolate(), 10);
1790
  for (int i = 0; i < 10; i++) {
1791 1792 1793
    CHECK(a->Set(context, v8::Number::New(env->GetIsolate(), i),
                 v8::Number::New(env->GetIsolate(), i))
              .FromJust());
1794 1795 1796 1797
  }

  // Call function without any break points to ensure inlining is in place.
  const int kArgc = 1;
1798 1799
  v8::Local<v8::Value> args[kArgc] = {a};
  foo->Call(context, env->Global(), kArgc, args).ToLocalChecked();
1800

1801
  // Set up break point and step through the function.
1802
  SetBreakPoint(foo, 3);
1803
  run_step.set_step_action(StepNext);
1804
  break_point_hit_count = 0;
1805
  foo->Call(context, env->Global(), kArgc, args).ToLocalChecked();
1806 1807

  // With stepping all break locations are hit.
1808
  CHECK_EQ(44, break_point_hit_count);
1809

1810
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1811
  CheckDebuggerUnloaded();
1812 1813 1814
}


1815 1816
// Test of the stepping mechanism for named load in a loop.
TEST(DebugStepNamedLoadLoop) {
1817
  LocalContext env;
1818
  v8::HandleScope scope(env->GetIsolate());
1819

1820
  // Register a debug event listener which steps and counts.
1821 1822
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1823

1824
  v8::Local<v8::Context> context = env.local();
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
  // Create a function for testing stepping of named load.
  v8::Local<v8::Function> foo = CompileFunction(
      &env,
      "function foo() {\n"
          "  var a = [];\n"
          "  var s = \"\";\n"
          "  for (var i = 0; i < 10; i++) {\n"
          "    var v = new V(i, i + 1);\n"
          "    v.y;\n"
          "    a.length;\n"  // Special case: array length.
          "    s.length;\n"  // Special case: string length.
          "  }\n"
          "}\n"
          "function V(x, y) {\n"
          "  this.x = x;\n"
          "  this.y = y;\n"
          "}\n",
          "foo");

  // Call function without any break points to ensure inlining is in place.
1845
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1846

1847
  // Set up break point and step through the function.
1848
  SetBreakPoint(foo, 4);
1849
  run_step.set_step_action(StepNext);
1850
  break_point_hit_count = 0;
1851
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1852 1853

  // With stepping all break locations are hit.
1854
  CHECK_EQ(65, break_point_hit_count);
1855

1856
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1857
  CheckDebuggerUnloaded();
1858 1859 1860
}


1861
static void DoDebugStepNamedStoreLoop(int expected) {
1862
  LocalContext env;
1863
  v8::HandleScope scope(env->GetIsolate());
1864

1865
  // Register a debug event listener which steps and counts.
1866 1867
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1868 1869

  // Create a function for testing stepping of named store.
1870
  v8::Local<v8::Context> context = env.local();
1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
  v8::Local<v8::Function> foo = CompileFunction(
      &env,
      "function foo() {\n"
          "  var a = {a:1};\n"
          "  for (var i = 0; i < 10; i++) {\n"
          "    a.a = 2\n"
          "  }\n"
          "}\n",
          "foo");

  // Call function without any break points to ensure inlining is in place.
1882
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1883

1884
  // Set up break point and step through the function.
1885
  SetBreakPoint(foo, 3);
1886
  run_step.set_step_action(StepNext);
1887
  break_point_hit_count = 0;
1888
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1889 1890 1891 1892

  // With stepping all expected break locations are hit.
  CHECK_EQ(expected, break_point_hit_count);

1893
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1894
  CheckDebuggerUnloaded();
1895 1896 1897 1898
}


// Test of the stepping mechanism for named load in a loop.
1899
TEST(DebugStepNamedStoreLoop) { DoDebugStepNamedStoreLoop(34); }
1900

1901 1902
// Test the stepping mechanism with different ICs.
TEST(DebugStepLinearMixedICs) {
1903
  LocalContext env;
1904
  v8::HandleScope scope(env->GetIsolate());
1905

1906
  // Register a debug event listener which steps and counts.
1907 1908
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1909

1910
  v8::Local<v8::Context> context = env.local();
1911 1912 1913 1914 1915 1916 1917 1918
  // Create a function for testing stepping.
  v8::Local<v8::Function> foo = CompileFunction(&env,
      "function bar() {};"
      "function foo() {"
      "  var x;"
      "  var index='name';"
      "  var y = {};"
      "  a=1;b=2;x=a;y[index]=3;x=y[index];bar();}", "foo");
1919 1920 1921 1922

  // Run functions to allow them to get optimized.
  CompileRun("a=0; b=0; bar(); foo();");

1923 1924
  SetBreakPoint(foo, 0);

1925
  run_step.set_step_action(StepIn);
1926
  break_point_hit_count = 0;
1927
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1928

1929
  // With stepping all break locations are hit.
1930
  CHECK_EQ(10, break_point_hit_count);
1931

1932
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1933
  CheckDebuggerUnloaded();
1934 1935

  // Register a debug event listener which just counts.
1936 1937
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
1938

1939
  SetBreakPoint(foo, 0);
1940
  break_point_hit_count = 0;
1941
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1942 1943 1944 1945

  // Without stepping only active break points are hit.
  CHECK_EQ(1, break_point_hit_count);

1946
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1947
  CheckDebuggerUnloaded();
1948 1949 1950
}


1951
TEST(DebugStepDeclarations) {
1952
  LocalContext env;
1953
  v8::HandleScope scope(env->GetIsolate());
1954 1955

  // Register a debug event listener which steps and counts.
1956 1957
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1958

1959
  v8::Local<v8::Context> context = env.local();
1960 1961
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
1962 1963 1964 1965 1966 1967
  const char* src = "function foo() { "
                    "  var a;"
                    "  var b = 1;"
                    "  var c = foo;"
                    "  var d = Math.floor;"
                    "  var e = b + d(1.2);"
1968 1969
                    "}"
                    "foo()";
1970
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
1971

1972 1973 1974
  SetBreakPoint(foo, 0);

  // Stepping through the declarations.
1975
  run_step.set_step_action(StepIn);
1976
  break_point_hit_count = 0;
1977
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
1978
  CHECK_EQ(5, break_point_hit_count);
1979 1980

  // Get rid of the debug event listener.
1981
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
1982
  CheckDebuggerUnloaded();
1983 1984 1985 1986
}


TEST(DebugStepLocals) {
1987
  LocalContext env;
1988
  v8::HandleScope scope(env->GetIsolate());
1989 1990

  // Register a debug event listener which steps and counts.
1991 1992
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
1993

1994
  v8::Local<v8::Context> context = env.local();
1995 1996
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
1997 1998 1999 2000 2001 2002
  const char* src = "function foo() { "
                    "  var a,b;"
                    "  a = 1;"
                    "  b = a + 2;"
                    "  b = 1 + 2 + 3;"
                    "  a = Math.floor(b);"
2003 2004
                    "}"
                    "foo()";
2005
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2006

2007 2008 2009
  SetBreakPoint(foo, 0);

  // Stepping through the declarations.
2010
  run_step.set_step_action(StepIn);
2011
  break_point_hit_count = 0;
2012
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2013
  CHECK_EQ(5, break_point_hit_count);
2014 2015

  // Get rid of the debug event listener.
2016
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2017
  CheckDebuggerUnloaded();
2018 2019 2020
}


2021
TEST(DebugStepIf) {
2022
  LocalContext env;
2023 2024
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2025 2026

  // Register a debug event listener which steps and counts.
2027 2028
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2029

2030
  v8::Local<v8::Context> context = env.local();
2031 2032
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2033 2034 2035 2036 2037 2038 2039 2040 2041
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  a = 1;"
                    "  if (x) {"
                    "    b = 1;"
                    "  } else {"
                    "    c = 1;"
                    "    d = 1;"
                    "  }"
2042 2043
                    "}"
                    "a=0; b=0; c=0; d=0; foo()";
2044 2045 2046 2047
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
  SetBreakPoint(foo, 0);

  // Stepping through the true part.
2048
  run_step.set_step_action(StepIn);
2049
  break_point_hit_count = 0;
2050 2051
  v8::Local<v8::Value> argv_true[argc] = {v8::True(isolate)};
  foo->Call(context, env->Global(), argc, argv_true).ToLocalChecked();
2052
  CHECK_EQ(4, break_point_hit_count);
2053 2054

  // Stepping through the false part.
2055
  run_step.set_step_action(StepIn);
2056
  break_point_hit_count = 0;
2057 2058
  v8::Local<v8::Value> argv_false[argc] = {v8::False(isolate)};
  foo->Call(context, env->Global(), argc, argv_false).ToLocalChecked();
2059
  CHECK_EQ(5, break_point_hit_count);
2060 2061

  // Get rid of the debug event listener.
2062
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2063
  CheckDebuggerUnloaded();
2064 2065 2066 2067
}


TEST(DebugStepSwitch) {
2068
  LocalContext env;
2069 2070
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2071 2072

  // Register a debug event listener which steps and counts.
2073 2074
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2075

2076
  v8::Local<v8::Context> context = env.local();
2077 2078
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  a = 1;"
                    "  switch (x) {"
                    "    case 1:"
                    "      b = 1;"
                    "    case 2:"
                    "      c = 1;"
                    "      break;"
                    "    case 3:"
                    "      d = 1;"
                    "      e = 1;"
2091
                    "      f = 1;"
2092 2093
                    "      break;"
                    "  }"
2094 2095
                    "}"
                    "a=0; b=0; c=0; d=0; e=0; f=0; foo()";
2096 2097 2098 2099
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
  SetBreakPoint(foo, 0);

  // One case with fall-through.
2100
  run_step.set_step_action(StepIn);
2101
  break_point_hit_count = 0;
2102 2103
  v8::Local<v8::Value> argv_1[argc] = {v8::Number::New(isolate, 1)};
  foo->Call(context, env->Global(), argc, argv_1).ToLocalChecked();
2104
  CHECK_EQ(6, break_point_hit_count);
2105 2106

  // Another case.
2107
  run_step.set_step_action(StepIn);
2108
  break_point_hit_count = 0;
2109 2110
  v8::Local<v8::Value> argv_2[argc] = {v8::Number::New(isolate, 2)};
  foo->Call(context, env->Global(), argc, argv_2).ToLocalChecked();
2111
  CHECK_EQ(5, break_point_hit_count);
2112 2113

  // Last case.
2114
  run_step.set_step_action(StepIn);
2115
  break_point_hit_count = 0;
2116 2117
  v8::Local<v8::Value> argv_3[argc] = {v8::Number::New(isolate, 3)};
  foo->Call(context, env->Global(), argc, argv_3).ToLocalChecked();
2118 2119 2120
  CHECK_EQ(7, break_point_hit_count);

  // Get rid of the debug event listener.
2121
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2122
  CheckDebuggerUnloaded();
2123 2124 2125 2126
}


TEST(DebugStepWhile) {
2127
  LocalContext env;
2128 2129
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2130 2131

  // Register a debug event listener which steps and counts.
2132 2133
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2134

2135
  v8::Local<v8::Context> context = env.local();
2136 2137
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2138 2139 2140 2141 2142 2143
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  var a = 0;"
                    "  while (a < x) {"
                    "    a++;"
                    "  }"
2144 2145
                    "}"
                    "foo()";
2146 2147 2148
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
  SetBreakPoint(foo, 8);  // "var a = 0;"

2149
  // Looping 0 times.  We still should break at the while-condition once.
2150
  run_step.set_step_action(StepIn);
2151
  break_point_hit_count = 0;
2152 2153
  v8::Local<v8::Value> argv_0[argc] = {v8::Number::New(isolate, 0)};
  foo->Call(context, env->Global(), argc, argv_0).ToLocalChecked();
2154 2155
  CHECK_EQ(3, break_point_hit_count);

2156
  // Looping 10 times.
2157
  run_step.set_step_action(StepIn);
2158
  break_point_hit_count = 0;
2159 2160
  v8::Local<v8::Value> argv_10[argc] = {v8::Number::New(isolate, 10)};
  foo->Call(context, env->Global(), argc, argv_10).ToLocalChecked();
2161
  CHECK_EQ(23, break_point_hit_count);
2162 2163

  // Looping 100 times.
2164
  run_step.set_step_action(StepIn);
2165
  break_point_hit_count = 0;
2166 2167
  v8::Local<v8::Value> argv_100[argc] = {v8::Number::New(isolate, 100)};
  foo->Call(context, env->Global(), argc, argv_100).ToLocalChecked();
2168
  CHECK_EQ(203, break_point_hit_count);
2169 2170

  // Get rid of the debug event listener.
2171
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2172
  CheckDebuggerUnloaded();
2173 2174 2175 2176
}


TEST(DebugStepDoWhile) {
2177
  LocalContext env;
2178 2179
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2180 2181

  // Register a debug event listener which steps and counts.
2182 2183
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2184

2185
  v8::Local<v8::Context> context = env.local();
2186 2187
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2188 2189 2190 2191 2192 2193
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  var a = 0;"
                    "  do {"
                    "    a++;"
                    "  } while (a < x)"
2194 2195
                    "}"
                    "foo()";
2196 2197 2198
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
  SetBreakPoint(foo, 8);  // "var a = 0;"

2199
  // Looping 0 times.
2200
  run_step.set_step_action(StepIn);
2201
  break_point_hit_count = 0;
2202 2203
  v8::Local<v8::Value> argv_0[argc] = {v8::Number::New(isolate, 0)};
  foo->Call(context, env->Global(), argc, argv_0).ToLocalChecked();
2204 2205
  CHECK_EQ(4, break_point_hit_count);

2206
  // Looping 10 times.
2207
  run_step.set_step_action(StepIn);
2208
  break_point_hit_count = 0;
2209 2210
  v8::Local<v8::Value> argv_10[argc] = {v8::Number::New(isolate, 10)};
  foo->Call(context, env->Global(), argc, argv_10).ToLocalChecked();
2211 2212 2213
  CHECK_EQ(22, break_point_hit_count);

  // Looping 100 times.
2214
  run_step.set_step_action(StepIn);
2215
  break_point_hit_count = 0;
2216 2217
  v8::Local<v8::Value> argv_100[argc] = {v8::Number::New(isolate, 100)};
  foo->Call(context, env->Global(), argc, argv_100).ToLocalChecked();
2218
  CHECK_EQ(202, break_point_hit_count);
2219 2220

  // Get rid of the debug event listener.
2221
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2222
  CheckDebuggerUnloaded();
2223 2224 2225 2226
}


TEST(DebugStepFor) {
2227
  LocalContext env;
2228 2229
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2230 2231

  // Register a debug event listener which steps and counts.
2232 2233
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2234

2235
  v8::Local<v8::Context> context = env.local();
2236 2237
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2238 2239 2240 2241 2242 2243
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  a = 1;"
                    "  for (i = 0; i < x; i++) {"
                    "    b = 1;"
                    "  }"
2244 2245
                    "}"
                    "a=0; b=0; i=0; foo()";
2246
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2247

2248 2249
  SetBreakPoint(foo, 8);  // "a = 1;"

2250
  // Looping 0 times.
2251
  run_step.set_step_action(StepIn);
2252
  break_point_hit_count = 0;
2253 2254
  v8::Local<v8::Value> argv_0[argc] = {v8::Number::New(isolate, 0)};
  foo->Call(context, env->Global(), argc, argv_0).ToLocalChecked();
2255 2256
  CHECK_EQ(4, break_point_hit_count);

2257
  // Looping 10 times.
2258
  run_step.set_step_action(StepIn);
2259
  break_point_hit_count = 0;
2260 2261
  v8::Local<v8::Value> argv_10[argc] = {v8::Number::New(isolate, 10)};
  foo->Call(context, env->Global(), argc, argv_10).ToLocalChecked();
2262
  CHECK_EQ(34, break_point_hit_count);
2263 2264

  // Looping 100 times.
2265
  run_step.set_step_action(StepIn);
2266
  break_point_hit_count = 0;
2267 2268
  v8::Local<v8::Value> argv_100[argc] = {v8::Number::New(isolate, 100)};
  foo->Call(context, env->Global(), argc, argv_100).ToLocalChecked();
2269
  CHECK_EQ(304, break_point_hit_count);
2270 2271

  // Get rid of the debug event listener.
2272
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2273
  CheckDebuggerUnloaded();
2274 2275 2276
}


2277
TEST(DebugStepForContinue) {
2278
  LocalContext env;
2279 2280
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2281 2282

  // Register a debug event listener which steps and counts.
2283 2284
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2285

2286
  v8::Local<v8::Context> context = env.local();
2287 2288
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  var a = 0;"
                    "  var b = 0;"
                    "  var c = 0;"
                    "  for (var i = 0; i < x; i++) {"
                    "    a++;"
                    "    if (a % 2 == 0) continue;"
                    "    b++;"
                    "    c++;"
                    "  }"
                    "  return b;"
2301 2302
                    "}"
                    "foo()";
2303
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2304
  v8::Local<v8::Value> result;
2305 2306 2307 2308 2309
  SetBreakPoint(foo, 8);  // "var a = 0;"

  // Each loop generates 4 or 5 steps depending on whether a is equal.

  // Looping 10 times.
2310
  run_step.set_step_action(StepIn);
2311
  break_point_hit_count = 0;
2312 2313 2314
  v8::Local<v8::Value> argv_10[argc] = {v8::Number::New(isolate, 10)};
  result = foo->Call(context, env->Global(), argc, argv_10).ToLocalChecked();
  CHECK_EQ(5, result->Int32Value(context).FromJust());
2315
  CHECK_EQ(62, break_point_hit_count);
2316 2317

  // Looping 100 times.
2318
  run_step.set_step_action(StepIn);
2319
  break_point_hit_count = 0;
2320 2321 2322
  v8::Local<v8::Value> argv_100[argc] = {v8::Number::New(isolate, 100)};
  result = foo->Call(context, env->Global(), argc, argv_100).ToLocalChecked();
  CHECK_EQ(50, result->Int32Value(context).FromJust());
2323
  CHECK_EQ(557, break_point_hit_count);
2324 2325

  // Get rid of the debug event listener.
2326
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2327
  CheckDebuggerUnloaded();
2328 2329 2330 2331
}


TEST(DebugStepForBreak) {
2332
  LocalContext env;
2333 2334
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2335 2336

  // Register a debug event listener which steps and counts.
2337 2338
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2339

2340
  v8::Local<v8::Context> context = env.local();
2341 2342
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
  const int argc = 1;
  const char* src = "function foo(x) { "
                    "  var a = 0;"
                    "  var b = 0;"
                    "  var c = 0;"
                    "  for (var i = 0; i < 1000; i++) {"
                    "    a++;"
                    "    if (a == x) break;"
                    "    b++;"
                    "    c++;"
                    "  }"
                    "  return b;"
2355 2356
                    "}"
                    "foo()";
2357
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2358
  v8::Local<v8::Value> result;
2359 2360 2361 2362 2363 2364
  SetBreakPoint(foo, 8);  // "var a = 0;"

  // Each loop generates 5 steps except for the last (when break is executed)
  // which only generates 4.

  // Looping 10 times.
2365
  run_step.set_step_action(StepIn);
2366
  break_point_hit_count = 0;
2367 2368 2369
  v8::Local<v8::Value> argv_10[argc] = {v8::Number::New(isolate, 10)};
  result = foo->Call(context, env->Global(), argc, argv_10).ToLocalChecked();
  CHECK_EQ(9, result->Int32Value(context).FromJust());
2370
  CHECK_EQ(64, break_point_hit_count);
2371 2372

  // Looping 100 times.
2373
  run_step.set_step_action(StepIn);
2374
  break_point_hit_count = 0;
2375 2376 2377
  v8::Local<v8::Value> argv_100[argc] = {v8::Number::New(isolate, 100)};
  result = foo->Call(context, env->Global(), argc, argv_100).ToLocalChecked();
  CHECK_EQ(99, result->Int32Value(context).FromJust());
2378
  CHECK_EQ(604, break_point_hit_count);
2379 2380

  // Get rid of the debug event listener.
2381
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2382
  CheckDebuggerUnloaded();
2383 2384 2385 2386
}


TEST(DebugStepForIn) {
2387
  LocalContext env;
2388
  v8::HandleScope scope(env->GetIsolate());
2389 2390

  // Register a debug event listener which steps and counts.
2391 2392
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2393

2394
  v8::Local<v8::Context> context = env.local();
2395 2396
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2397 2398 2399 2400 2401 2402
  v8::Local<v8::Function> foo;
  const char* src_1 = "function foo() { "
                      "  var a = [1, 2];"
                      "  for (x in a) {"
                      "    b = 0;"
                      "  }"
2403 2404
                      "}"
                      "foo()";
2405 2406 2407
  foo = CompileFunction(&env, src_1, "foo");
  SetBreakPoint(foo, 0);  // "var a = ..."

2408
  run_step.set_step_action(StepIn);
2409
  break_point_hit_count = 0;
2410
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2411
  CHECK_EQ(8, break_point_hit_count);
2412

2413 2414
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2415 2416 2417 2418 2419
  const char* src_2 = "function foo() { "
                      "  var a = {a:[1, 2, 3]};"
                      "  for (x in a.a) {"
                      "    b = 0;"
                      "  }"
2420 2421
                      "}"
                      "foo()";
2422 2423 2424
  foo = CompileFunction(&env, src_2, "foo");
  SetBreakPoint(foo, 0);  // "var a = ..."

2425
  run_step.set_step_action(StepIn);
2426
  break_point_hit_count = 0;
2427
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2428
  CHECK_EQ(10, break_point_hit_count);
2429 2430

  // Get rid of the debug event listener.
2431
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2432
  CheckDebuggerUnloaded();
2433 2434 2435 2436
}


TEST(DebugStepWith) {
2437
  LocalContext env;
2438
  v8::HandleScope scope(env->GetIsolate());
2439 2440

  // Register a debug event listener which steps and counts.
2441 2442
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2443

2444
  v8::Local<v8::Context> context = env.local();
2445 2446
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2447 2448 2449 2450
  const char* src = "function foo(x) { "
                    "  var a = {};"
                    "  with (a) {}"
                    "  with (b) {}"
2451 2452
                    "}"
                    "foo()";
2453 2454 2455 2456
  CHECK(env->Global()
            ->Set(context, v8_str(env->GetIsolate(), "b"),
                  v8::Object::New(env->GetIsolate()))
            .FromJust());
2457
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2458
  v8::Local<v8::Value> result;
2459 2460
  SetBreakPoint(foo, 8);  // "var a = {};"

2461
  run_step.set_step_action(StepIn);
2462
  break_point_hit_count = 0;
2463
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2464 2465 2466
  CHECK_EQ(4, break_point_hit_count);

  // Get rid of the debug event listener.
2467
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2468
  CheckDebuggerUnloaded();
2469 2470 2471 2472
}


TEST(DebugConditional) {
2473
  LocalContext env;
2474 2475
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2476 2477

  // Register a debug event listener which steps and counts.
2478 2479
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2480

2481
  v8::Local<v8::Context> context = env.local();
2482 2483
  // Create a function for testing stepping. Run it to allow it to get
  // optimized.
2484 2485 2486 2487 2488
  const char* src =
      "function foo(x) { "
      "  return x ? 1 : 2;"
      "}"
      "foo()";
2489 2490 2491
  v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
  SetBreakPoint(foo, 0);  // "var a;"

2492
  run_step.set_step_action(StepIn);
2493
  break_point_hit_count = 0;
2494
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2495
  CHECK_EQ(2, break_point_hit_count);
2496

2497
  run_step.set_step_action(StepIn);
2498 2499
  break_point_hit_count = 0;
  const int argc = 1;
2500 2501
  v8::Local<v8::Value> argv_true[argc] = {v8::True(isolate)};
  foo->Call(context, env->Global(), argc, argv_true).ToLocalChecked();
2502
  CHECK_EQ(2, break_point_hit_count);
2503 2504

  // Get rid of the debug event listener.
2505
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2506
  CheckDebuggerUnloaded();
2507 2508 2509 2510
}

// Test that step in does not step into native functions.
TEST(DebugStepNatives) {
2511
  LocalContext env;
2512
  v8::HandleScope scope(env->GetIsolate());
2513 2514

  // Create a function for testing stepping.
2515 2516
  v8::Local<v8::Function> foo =
      CompileFunction(&env, "function foo(){debugger;Math.sin(1);}", "foo");
2517 2518

  // Register a debug event listener which steps and counts.
2519 2520
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2521

2522 2523
  v8::Local<v8::Context> context = env.local();
  run_step.set_step_action(StepIn);
2524
  break_point_hit_count = 0;
2525
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2526 2527 2528 2529

  // With stepping all break locations are hit.
  CHECK_EQ(3, break_point_hit_count);

2530
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2531
  CheckDebuggerUnloaded();
2532 2533

  // Register a debug event listener which just counts.
2534 2535
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
2536 2537

  break_point_hit_count = 0;
2538
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2539 2540 2541 2542

  // Without stepping only active break points are hit.
  CHECK_EQ(1, break_point_hit_count);

2543
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2544
  CheckDebuggerUnloaded();
2545 2546
}

2547 2548
// Test that step in works with function.apply.
TEST(DebugStepFunctionApply) {
2549
  LocalContext env;
2550
  v8::HandleScope scope(env->GetIsolate());
2551 2552

  // Create a function for testing stepping.
2553 2554 2555 2556 2557
  v8::Local<v8::Function> foo =
      CompileFunction(&env,
                      "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
                      "function foo(){ debugger; bar.apply(this, [1,2,3]); }",
                      "foo");
2558 2559

  // Register a debug event listener which steps and counts.
2560 2561
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
2562

2563 2564
  v8::Local<v8::Context> context = env.local();
  run_step.set_step_action(StepIn);
2565
  break_point_hit_count = 0;
2566
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2567 2568

  // With stepping all break locations are hit.
2569
  CHECK_EQ(7, break_point_hit_count);
2570

2571
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2572
  CheckDebuggerUnloaded();
2573 2574

  // Register a debug event listener which just counts.
2575 2576
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
2577 2578

  break_point_hit_count = 0;
2579
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2580 2581 2582 2583

  // Without stepping only the debugger statement is hit.
  CHECK_EQ(1, break_point_hit_count);

2584
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2585
  CheckDebuggerUnloaded();
2586 2587 2588
}


2589 2590
// Test that step in works with function.call.
TEST(DebugStepFunctionCall) {
2591
  LocalContext env;
2592 2593
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2594

2595
  v8::Local<v8::Context> context = env.local();
2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
  // Create a function for testing stepping.
  v8::Local<v8::Function> foo = CompileFunction(
      &env,
      "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
      "function foo(a){ debugger;"
      "                 if (a) {"
      "                   bar.call(this, 1, 2, 3);"
      "                 } else {"
      "                   bar.call(this, 0);"
      "                 }"
      "}",
      "foo");

  // Register a debug event listener which steps and counts.
2610 2611 2612
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
  run_step.set_step_action(StepIn);
2613 2614 2615

  // Check stepping where the if condition in bar is false.
  break_point_hit_count = 0;
2616
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2617
  CHECK_EQ(6, break_point_hit_count);
2618 2619 2620 2621

  // Check stepping where the if condition in bar is true.
  break_point_hit_count = 0;
  const int argc = 1;
2622 2623
  v8::Local<v8::Value> argv[argc] = {v8::True(isolate)};
  foo->Call(context, env->Global(), argc, argv).ToLocalChecked();
2624
  CHECK_EQ(8, break_point_hit_count);
2625

2626
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2627
  CheckDebuggerUnloaded();
2628 2629

  // Register a debug event listener which just counts.
2630 2631
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
2632 2633

  break_point_hit_count = 0;
2634
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2635 2636 2637 2638

  // Without stepping only the debugger statement is hit.
  CHECK_EQ(1, break_point_hit_count);

2639
  v8::debug::SetDebugDelegate(isolate, nullptr);
2640
  CheckDebuggerUnloaded();
2641 2642 2643
}


2644 2645
// Test that step in works with Function.call.apply.
TEST(DebugStepFunctionCallApply) {
2646
  LocalContext env;
2647 2648 2649
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);

2650
  v8::Local<v8::Context> context = env.local();
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
  // Create a function for testing stepping.
  v8::Local<v8::Function> foo =
      CompileFunction(&env,
                      "function bar() { }"
                      "function foo(){ debugger;"
                      "                Function.call.apply(bar);"
                      "                Function.call.apply(Function.call, "
                      "[Function.call, bar]);"
                      "}",
                      "foo");

  // Register a debug event listener which steps and counts.
2663 2664 2665
  DebugEventCounter run_step;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &run_step);
  run_step.set_step_action(StepIn);
2666 2667

  break_point_hit_count = 0;
2668
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2669
  CHECK_EQ(6, break_point_hit_count);
2670

2671
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2672
  CheckDebuggerUnloaded();
2673 2674

  // Register a debug event listener which just counts.
2675 2676
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
2677 2678

  break_point_hit_count = 0;
2679
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2680 2681 2682 2683

  // Without stepping only the debugger statement is hit.
  CHECK_EQ(1, break_point_hit_count);

2684
  v8::debug::SetDebugDelegate(isolate, nullptr);
2685
  CheckDebuggerUnloaded();
2686 2687 2688
}


2689 2690
// Tests that breakpoint will be hit if it's set in script.
TEST(PauseInScript) {
2691
  LocalContext env;
2692
  v8::HandleScope scope(env->GetIsolate());
2693
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
2694 2695

  // Register a debug event listener which counts.
2696
  DebugEventCounter event_counter;
2697
  v8::debug::SetDebugDelegate(env->GetIsolate(), &event_counter);
2698

2699
  v8::Local<v8::Context> context = env.local();
2700 2701 2702 2703
  // Create a script that returns a function.
  const char* src = "(function (evt) {})";
  const char* script_name = "StepInHandlerTest";

2704 2705 2706 2707 2708
  v8::ScriptOrigin origin(v8_str(env->GetIsolate(), script_name),
                          v8::Integer::New(env->GetIsolate(), 0));
  v8::Local<v8::Script> script =
      v8::Script::Compile(context, v8_str(env->GetIsolate(), src), &origin)
          .ToLocalChecked();
2709 2710

  // Set breakpoint in the script.
2711
  i::Handle<i::Script> i_script(
2712
      i::Script::cast(v8::Utils::OpenHandle(*script)->shared().script()),
2713
      isolate);
2714 2715 2716 2717
  i::Handle<i::String> condition = isolate->factory()->empty_string();
  int position = 0;
  int id;
  isolate->debug()->SetBreakPointForScript(i_script, condition, &position, &id);
2718 2719
  break_point_hit_count = 0;

2720
  v8::Local<v8::Value> r = script->Run(context).ToLocalChecked();
2721 2722

  CHECK(r->IsFunction());
2723
  CHECK_EQ(1, break_point_hit_count);
2724

2725 2726
  // Get rid of the debug delegate.
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2727
  CheckDebuggerUnloaded();
2728 2729
}

2730
int message_callback_count = 0;
2731 2732

TEST(DebugBreak) {
2733
  i::FLAG_stress_compaction = false;
2734 2735 2736
#ifdef VERIFY_HEAP
  i::FLAG_verify_heap = true;
#endif
2737
  LocalContext env;
2738 2739
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2740 2741

  // Register a debug event listener which sets the break flag and counts.
2742 2743
  DebugEventBreak delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
2744

2745
  v8::Local<v8::Context> context = env.local();
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
  // Create a function for testing stepping.
  const char* src = "function f0() {}"
                    "function f1(x1) {}"
                    "function f2(x1,x2) {}"
                    "function f3(x1,x2,x3) {}";
  v8::Local<v8::Function> f0 = CompileFunction(&env, src, "f0");
  v8::Local<v8::Function> f1 = CompileFunction(&env, src, "f1");
  v8::Local<v8::Function> f2 = CompileFunction(&env, src, "f2");
  v8::Local<v8::Function> f3 = CompileFunction(&env, src, "f3");

  // Call the function to make sure it is compiled.
2757 2758 2759
  v8::Local<v8::Value> argv[] = {
      v8::Number::New(isolate, 1), v8::Number::New(isolate, 1),
      v8::Number::New(isolate, 1), v8::Number::New(isolate, 1)};
2760 2761

  // Call all functions to make sure that they are compiled.
2762 2763 2764 2765
  f0->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
  f1->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
  f2->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
  f3->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2766 2767

  // Set the debug break flag.
2768
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
2769 2770 2771

  // Call all functions with different argument count.
  break_point_hit_count = 0;
2772
  for (unsigned int i = 0; i < arraysize(argv); i++) {
2773 2774 2775 2776
    f0->Call(context, env->Global(), i, argv).ToLocalChecked();
    f1->Call(context, env->Global(), i, argv).ToLocalChecked();
    f2->Call(context, env->Global(), i, argv).ToLocalChecked();
    f3->Call(context, env->Global(), i, argv).ToLocalChecked();
2777 2778 2779
  }

  // One break for each function called.
2780
  CHECK_EQ(4 * arraysize(argv), break_point_hit_count);
2781 2782

  // Get rid of the debug event listener.
2783
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2784
  CheckDebuggerUnloaded();
2785 2786
}

2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
class DebugScopingListener : public v8::debug::DebugDelegate {
 public:
  void BreakProgramRequested(
      v8::Local<v8::Context>,
      const std::vector<v8::debug::BreakpointId>&) override {
    auto stack_traces =
        v8::debug::StackTraceIterator::Create(CcTest::isolate());
    v8::debug::Location location = stack_traces->GetSourceLocation();
    CHECK_EQ(26, location.GetColumnNumber());
    CHECK_EQ(0, location.GetLineNumber());

    auto scopes = stack_traces->GetScopeIterator();
    CHECK_EQ(v8::debug::ScopeIterator::ScopeTypeWith, scopes->GetType());
    CHECK_EQ(20, scopes->GetStartLocation().GetColumnNumber());
    CHECK_EQ(31, scopes->GetEndLocation().GetColumnNumber());

    scopes->Advance();
    CHECK_EQ(v8::debug::ScopeIterator::ScopeTypeLocal, scopes->GetType());
    CHECK_EQ(0, scopes->GetStartLocation().GetColumnNumber());
    CHECK_EQ(68, scopes->GetEndLocation().GetColumnNumber());

    scopes->Advance();
    CHECK_EQ(v8::debug::ScopeIterator::ScopeTypeGlobal, scopes->GetType());

    scopes->Advance();
    CHECK(scopes->Done());
  }
};
2815 2816 2817 2818 2819 2820

TEST(DebugBreakInWrappedScript) {
  i::FLAG_stress_compaction = false;
#ifdef VERIFY_HEAP
  i::FLAG_verify_heap = true;
#endif
2821
  LocalContext env;
2822 2823 2824 2825
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);

  // Register a debug event listener which sets the break flag and counts.
2826 2827
  DebugScopingListener delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840

  static const char* source =
      //   0         1         2         3         4         5         6 7
      "try { with({o : []}){ o[0](); } } catch (e) { return e.toString(); }";
  static const char* expect = "TypeError: o[0] is not a function";

  // For this test, we want to break on uncaught exceptions:
  ChangeBreakOnException(true, true);

  {
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
2841
            env.local(), &script_source, 0, nullptr, 0, nullptr)
2842 2843
            .ToLocalChecked();
    v8::Local<v8::Value> result =
2844
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
2845 2846
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
2847
              ->Equals(env.local(), v8_str(expect))
2848 2849 2850 2851
              .FromJust());
  }

  // Get rid of the debug event listener.
2852
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2853 2854 2855
  CheckDebuggerUnloaded();
}

2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
static void EmptyHandler(const v8::FunctionCallbackInfo<v8::Value>& args) {}

TEST(DebugScopeIteratorWithFunctionTemplate) {
  LocalContext env;
  v8::HandleScope handle_scope(env->GetIsolate());
  v8::Isolate* isolate = env->GetIsolate();
  EnableDebugger(isolate);
  v8::Local<v8::Function> func =
      v8::Function::New(env.local(), EmptyHandler).ToLocalChecked();
  std::unique_ptr<v8::debug::ScopeIterator> iterator =
      v8::debug::ScopeIterator::CreateForFunction(isolate, func);
  CHECK(iterator->Done());
  DisableDebugger(isolate);
}

2871 2872 2873 2874 2875
TEST(DebugBreakWithoutJS) {
  i::FLAG_stress_compaction = false;
#ifdef VERIFY_HEAP
  i::FLAG_verify_heap = true;
#endif
2876
  LocalContext env;
2877 2878
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
2879
  v8::Local<v8::Context> context = env.local();
2880 2881

  // Register a debug event listener which sets the break flag and counts.
2882 2883
  DebugEventBreak delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
2884 2885

  // Set the debug break flag.
2886
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898

  v8::Local<v8::String> json = v8_str("[1]");
  v8::Local<v8::Value> parsed = v8::JSON::Parse(context, json).ToLocalChecked();
  CHECK(v8::JSON::Stringify(context, parsed)
            .ToLocalChecked()
            ->Equals(context, json)
            .FromJust());
  CHECK_EQ(0, break_point_hit_count);
  CompileRun("");
  CHECK_EQ(1, break_point_hit_count);

  // Get rid of the debug event listener.
2899
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2900 2901
  CheckDebuggerUnloaded();
}
2902 2903 2904 2905

// Test to ensure that JavaScript code keeps running while the debug break
// through the stack limit flag is set but breaks are disabled.
TEST(DisableBreak) {
2906
  LocalContext env;
2907
  v8::HandleScope scope(env->GetIsolate());
2908 2909

  // Register a debug event listener which sets the break flag and counts.
2910 2911
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
2912

2913
  v8::Local<v8::Context> context = env.local();
2914 2915 2916 2917
  // Create a function for testing stepping.
  const char* src = "function f() {g()};function g(){i=0; while(i<10){i++}}";
  v8::Local<v8::Function> f = CompileFunction(&env, src, "f");

2918
  // Set, test and cancel debug break.
2919 2920
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
  v8::debug::ClearBreakOnNextFunctionCall(env->GetIsolate());
2921

2922
  // Set the debug break flag.
2923
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
2924 2925 2926

  // Call all functions with different argument count.
  break_point_hit_count = 0;
2927
  f->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2928 2929 2930
  CHECK_EQ(1, break_point_hit_count);

  {
2931
    v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
2932
    i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
2933
    v8::internal::DisableBreak disable_break(isolate->debug());
2934
    f->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2935 2936 2937
    CHECK_EQ(1, break_point_hit_count);
  }

2938
  f->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
2939 2940 2941
  CHECK_EQ(2, break_point_hit_count);

  // Get rid of the debug event listener.
2942
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2943
  CheckDebuggerUnloaded();
2944 2945
}

2946
TEST(DisableDebuggerStatement) {
2947
  LocalContext env;
2948 2949 2950
  v8::HandleScope scope(env->GetIsolate());

  // Register a debug event listener which sets the break flag and counts.
2951 2952 2953
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);

2954 2955 2956 2957 2958 2959 2960 2961
  CompileRun("debugger;");
  CHECK_EQ(1, break_point_hit_count);

  // Check that we ignore debugger statement when breakpoints aren't active.
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
  isolate->debug()->set_break_points_active(false);
  CompileRun("debugger;");
  CHECK_EQ(1, break_point_hit_count);
2962 2963

  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
2964 2965
}

2966 2967 2968 2969 2970 2971 2972 2973
static const char* kSimpleExtensionSource =
  "(function Foo() {"
  "  return 4;"
  "})() ";

// http://crbug.com/28933
// Test that debug break is disabled when bootstrapper is active.
TEST(NoBreakWhenBootstrapping) {
2974
  v8::Isolate* isolate = CcTest::isolate();
2975
  v8::HandleScope scope(isolate);
2976 2977

  // Register a debug event listener which sets the break flag and counts.
2978 2979
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
2980 2981

  // Set the debug break flag.
2982
  v8::debug::SetBreakOnNextFunctionCall(isolate);
2983 2984 2985 2986
  break_point_hit_count = 0;
  {
    // Create a context with an extension to make sure that some JavaScript
    // code is executed during bootstrapping.
2987 2988
    v8::RegisterExtension(v8::base::make_unique<v8::Extension>(
        "simpletest", kSimpleExtensionSource));
2989 2990
    const char* extension_names[] = { "simpletest" };
    v8::ExtensionConfiguration extensions(1, extension_names);
2991 2992
    v8::HandleScope handle_scope(isolate);
    v8::Context::New(isolate, &extensions);
2993
  }
2994
  // Check that no DebugBreak events occurred during the context creation.
2995
  CHECK_EQ(0, break_point_hit_count);
2996

2997
  // Get rid of the debug event listener.
2998
  v8::debug::SetDebugDelegate(isolate, nullptr);
2999
  CheckDebuggerUnloaded();
3000
}
3001

3002 3003 3004
TEST(SetDebugEventListenerOnUninitializedVM) {
  v8::HandleScope scope(CcTest::isolate());
  EnableDebugger(CcTest::isolate());
3005 3006
}

3007 3008 3009 3010 3011 3012 3013
// Test that clearing the debug event listener actually clears all break points
// and related information.
TEST(DebuggerUnload) {
  LocalContext env;
  v8::HandleScope handle_scope(env->GetIsolate());
  // Check debugger is unloaded before it is used.
  CheckDebuggerUnloaded();
3014

3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026
  // Set a debug event listener.
  break_point_hit_count = 0;
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
  v8::Local<v8::Context> context = env.local();
  {
    v8::HandleScope scope(env->GetIsolate());
    // Create a couple of functions for the test.
    v8::Local<v8::Function> foo =
        CompileFunction(&env, "function foo(){x=1}", "foo");
    v8::Local<v8::Function> bar =
        CompileFunction(&env, "function bar(){y=2}", "bar");
3027

3028 3029 3030 3031 3032
    // Set some break points.
    SetBreakPoint(foo, 0);
    SetBreakPoint(foo, 4);
    SetBreakPoint(bar, 0);
    SetBreakPoint(bar, 4);
3033

3034 3035 3036 3037 3038 3039
    // Make sure that the break points are there.
    break_point_hit_count = 0;
    foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
    CHECK_EQ(2, break_point_hit_count);
    bar->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
    CHECK_EQ(4, break_point_hit_count);
3040
  }
3041 3042 3043 3044 3045

  // Remove the debug event listener without clearing breakpoints. Do this
  // outside a handle scope.
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
  CheckDebuggerUnloaded();
3046 3047
}

3048
int event_listener_hit_count = 0;
3049

3050 3051 3052 3053 3054 3055
// Test for issue http://code.google.com/p/v8/issues/detail?id=289.
// Make sure that DebugGetLoadedScripts doesn't return scripts
// with disposed external source.
class EmptyExternalStringResource : public v8::String::ExternalStringResource {
 public:
  EmptyExternalStringResource() { empty_[0] = 0; }
3056
  ~EmptyExternalStringResource() override = default;
3057
  size_t length() const override { return empty_.length(); }
3058
  const uint16_t* data() const override { return empty_.begin(); }
3059

3060 3061 3062
 private:
  ::v8::internal::EmbeddedVector<uint16_t, 1> empty_;
};
3063

3064 3065
TEST(DebugScriptLineEndsAreAscending) {
  LocalContext env;
3066 3067
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
3068

3069 3070 3071 3072 3073
  // Compile a test script.
  v8::Local<v8::String> script = v8_str(isolate,
                                        "function f() {\n"
                                        "  debugger;\n"
                                        "}\n");
3074

3075 3076 3077 3078
  v8::ScriptOrigin origin1 = v8::ScriptOrigin(v8_str(isolate, "name"));
  v8::Local<v8::Script> script1 =
      v8::Script::Compile(env.local(), script, &origin1).ToLocalChecked();
  USE(script1);
3079

3080 3081 3082 3083 3084
  Handle<v8::internal::FixedArray> instances;
  {
    v8::internal::Debug* debug = CcTest::i_isolate()->debug();
    instances = debug->GetLoadedScripts();
  }
3085 3086 3087 3088

  CHECK_GT(instances->length(), 0);
  for (int i = 0; i < instances->length(); i++) {
    Handle<v8::internal::Script> script = Handle<v8::internal::Script>(
3089
        v8::internal::Script::cast(instances->get(i)), CcTest::i_isolate());
3090 3091

    v8::internal::Script::InitLineEnds(script);
3092
    v8::internal::FixedArray ends =
3093
        v8::internal::FixedArray::cast(script->line_ends());
3094
    CHECK_GT(ends.length(), 0);
3095 3096

    int prev_end = -1;
3097 3098
    for (int j = 0; j < ends.length(); j++) {
      const int curr_end = v8::internal::Smi::ToInt(ends.get(j));
3099 3100 3101 3102
      CHECK_GT(curr_end, prev_end);
      prev_end = curr_end;
    }
  }
3103
}
3104

3105 3106
static v8::Local<v8::Context> expected_context;
static v8::Local<v8::Value> expected_context_data;
3107

3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
class ContextCheckEventListener : public v8::debug::DebugDelegate {
 public:
  void BreakProgramRequested(v8::Local<v8::Context> paused_context,
                             const std::vector<v8::debug::BreakpointId>&
                                 inspector_break_points_hit) override {
    CheckContext();
  }
  void ScriptCompiled(v8::Local<v8::debug::Script> script, bool is_live_edited,
                      bool has_compile_error) override {
    CheckContext();
  }
  void ExceptionThrown(v8::Local<v8::Context> paused_context,
                       v8::Local<v8::Value> exception,
3121 3122
                       v8::Local<v8::Value> promise, bool is_uncaught,
                       v8::debug::ExceptionType) override {
3123 3124 3125 3126 3127 3128 3129 3130
    CheckContext();
  }
  bool IsFunctionBlackboxed(v8::Local<v8::debug::Script> script,
                            const v8::debug::Location& start,
                            const v8::debug::Location& end) override {
    CheckContext();
    return false;
  }
3131

3132 3133 3134 3135 3136 3137 3138 3139
 private:
  void CheckContext() {
    v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
    CHECK(context == expected_context);
    CHECK(context->GetEmbedderData(0)->StrictEquals(expected_context_data));
    event_listener_hit_count++;
  }
};
3140 3141

// Test which creates two contexts and sets different embedder data on each.
3142 3143
// Checks that this data is set correctly and that when the debug event
// listener is called the expected context is the one active.
3144
TEST(ContextData) {
3145
  v8::Isolate* isolate = CcTest::isolate();
3146
  v8::HandleScope scope(isolate);
3147 3148

  // Create two contexts.
3149 3150 3151 3152 3153
  v8::Local<v8::Context> context_1;
  v8::Local<v8::Context> context_2;
  v8::Local<v8::ObjectTemplate> global_template =
      v8::Local<v8::ObjectTemplate>();
  v8::Local<v8::Value> global_object = v8::Local<v8::Value>();
3154 3155 3156 3157
  context_1 =
      v8::Context::New(isolate, nullptr, global_template, global_object);
  context_2 =
      v8::Context::New(isolate, nullptr, global_template, global_object);
3158

3159 3160
  ContextCheckEventListener delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
3161

3162
  // Default data value is undefined.
3163 3164
  CHECK_EQ(0, context_1->GetNumberOfEmbedderDataFields());
  CHECK_EQ(0, context_2->GetNumberOfEmbedderDataFields());
3165 3166

  // Set and check different data values.
3167 3168
  v8::Local<v8::String> data_1 = v8_str(isolate, "1");
  v8::Local<v8::String> data_2 = v8_str(isolate, "2");
3169 3170 3171 3172
  context_1->SetEmbedderData(0, data_1);
  context_2->SetEmbedderData(0, data_2);
  CHECK(context_1->GetEmbedderData(0)->StrictEquals(data_1));
  CHECK(context_2->GetEmbedderData(0)->StrictEquals(data_2));
3173 3174

  // Simple test function which causes a break.
3175
  const char* source = "function f() { debugger; }";
3176 3177 3178 3179

  // Enter and run function in the first context.
  {
    v8::Context::Scope context_scope(context_1);
3180
    expected_context = context_1;
3181
    expected_context_data = data_1;
3182
    v8::Local<v8::Function> f = CompileFunction(isolate, source, "f");
3183
    f->Call(context_1, context_1->Global(), 0, nullptr).ToLocalChecked();
3184 3185 3186 3187 3188
  }

  // Enter and run function in the second context.
  {
    v8::Context::Scope context_scope(context_2);
3189
    expected_context = context_2;
3190 3191 3192 3193
    expected_context_data = data_2;
    v8::Local<v8::Function> f = CompileFunction(isolate, source, "f");
    f->Call(context_2, context_2->Global(), 0, nullptr).ToLocalChecked();
  }
3194

3195 3196
  // Two times compile event and two times break event.
  CHECK_GT(event_listener_hit_count, 3);
3197

3198 3199
  v8::debug::SetDebugDelegate(isolate, nullptr);
  CheckDebuggerUnloaded();
3200 3201
}

3202 3203 3204 3205 3206 3207
// Test which creates a context and sets embedder data on it. Checks that this
// data is set correctly and that when the debug event listener is called for
// break event in an eval statement the expected context is the one returned by
// Message.GetEventContext.
TEST(EvalContextData) {
  v8::HandleScope scope(CcTest::isolate());
3208

3209 3210 3211
  v8::Local<v8::Context> context_1;
  v8::Local<v8::ObjectTemplate> global_template =
      v8::Local<v8::ObjectTemplate>();
3212
  context_1 = v8::Context::New(CcTest::isolate(), nullptr, global_template);
3213

3214 3215
  ContextCheckEventListener delegate;
  v8::debug::SetDebugDelegate(CcTest::isolate(), &delegate);
3216

3217 3218
  // Contexts initially do not have embedder data fields.
  CHECK_EQ(0, context_1->GetNumberOfEmbedderDataFields());
3219 3220

  // Set and check a data value.
3221
  v8::Local<v8::String> data_1 = v8_str(CcTest::isolate(), "1");
3222 3223
  context_1->SetEmbedderData(0, data_1);
  CHECK(context_1->GetEmbedderData(0)->StrictEquals(data_1));
3224 3225 3226 3227 3228 3229 3230

  // Simple test function with eval that causes a break.
  const char* source = "function f() { eval('debugger;'); }";

  // Enter and run function in the context.
  {
    v8::Context::Scope context_scope(context_1);
3231
    expected_context = context_1;
3232
    expected_context_data = data_1;
3233
    v8::Local<v8::Function> f = CompileFunction(CcTest::isolate(), source, "f");
3234
    f->Call(context_1, context_1->Global(), 0, nullptr).ToLocalChecked();
3235
  }
3236

3237
  v8::debug::SetDebugDelegate(CcTest::isolate(), nullptr);
3238 3239

  // One time compile event and one time break event.
3240
  CHECK_GT(event_listener_hit_count, 2);
3241
  CheckDebuggerUnloaded();
3242 3243
}

3244 3245 3246 3247 3248 3249 3250 3251 3252 3253
// Debug event listener which counts script compiled events.
class ScriptCompiledDelegate : public v8::debug::DebugDelegate {
 public:
  void ScriptCompiled(v8::Local<v8::debug::Script>, bool,
                      bool has_compile_error) override {
    if (!has_compile_error) {
      after_compile_event_count++;
    } else {
      compile_error_event_count++;
    }
3254 3255
  }

3256 3257 3258
  int after_compile_event_count = 0;
  int compile_error_event_count = 0;
};
3259 3260 3261

// Tests that after compile event is sent as many times as there are scripts
// compiled.
3262
TEST(AfterCompileEventWhenEventListenerIsReset) {
3263
  LocalContext env;
3264
  v8::HandleScope scope(env->GetIsolate());
3265
  v8::Local<v8::Context> context = env.local();
3266 3267
  const char* script = "var a=1";

3268 3269
  ScriptCompiledDelegate delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3270 3271 3272 3273
  v8::Script::Compile(context, v8_str(env->GetIsolate(), script))
      .ToLocalChecked()
      ->Run(context)
      .ToLocalChecked();
3274
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3275

3276
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3277
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
3278 3279 3280 3281
  v8::Script::Compile(context, v8_str(env->GetIsolate(), script))
      .ToLocalChecked()
      ->Run(context)
      .ToLocalChecked();
3282

3283
  // Setting listener to nullptr should cause debugger unload.
3284
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3285
  CheckDebuggerUnloaded();
3286 3287

  // Compilation cache should be disabled when debugger is active.
3288
  CHECK_EQ(2, delegate.after_compile_event_count);
3289 3290
}

3291 3292
// Tests that syntax error event is sent as many times as there are scripts
// with syntax error compiled.
3293
TEST(SyntaxErrorEventOnSyntaxException) {
3294
  LocalContext env;
3295 3296 3297 3298 3299
  v8::HandleScope scope(env->GetIsolate());

  // For this test, we want to break on uncaught exceptions:
  ChangeBreakOnException(false, true);

3300 3301 3302
  ScriptCompiledDelegate delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
  v8::Local<v8::Context> context = env.local();
3303 3304

  // Check initial state.
3305
  CHECK_EQ(0, delegate.compile_error_event_count);
3306 3307

  // Throws SyntaxError: Unexpected end of input
3308 3309
  CHECK(
      v8::Script::Compile(context, v8_str(env->GetIsolate(), "+++")).IsEmpty());
3310
  CHECK_EQ(1, delegate.compile_error_event_count);
3311

3312 3313
  CHECK(v8::Script::Compile(context, v8_str(env->GetIsolate(), "/sel\\/: \\"))
            .IsEmpty());
3314
  CHECK_EQ(2, delegate.compile_error_event_count);
3315

3316 3317 3318 3319
  v8::Local<v8::Script> script =
      v8::Script::Compile(context,
                          v8_str(env->GetIsolate(), "JSON.parse('1234:')"))
          .ToLocalChecked();
3320
  CHECK_EQ(2, delegate.compile_error_event_count);
3321
  CHECK(script->Run(context).IsEmpty());
3322
  CHECK_EQ(3, delegate.compile_error_event_count);
3323

3324 3325 3326
  v8::Script::Compile(context,
                      v8_str(env->GetIsolate(), "new RegExp('/\\/\\\\');"))
      .ToLocalChecked();
3327
  CHECK_EQ(3, delegate.compile_error_event_count);
3328

3329 3330
  v8::Script::Compile(context, v8_str(env->GetIsolate(), "throw 1;"))
      .ToLocalChecked();
3331
  CHECK_EQ(3, delegate.compile_error_event_count);
3332 3333
}

3334 3335
// Tests that break event is sent when event listener is reset.
TEST(BreakEventWhenEventListenerIsReset) {
3336
  LocalContext env;
3337
  v8::HandleScope scope(env->GetIsolate());
3338
  v8::Local<v8::Context> context = env.local();
3339 3340
  const char* script = "function f() {};";

3341 3342
  ScriptCompiledDelegate delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3343 3344 3345 3346
  v8::Script::Compile(context, v8_str(env->GetIsolate(), script))
      .ToLocalChecked()
      ->Run(context)
      .ToLocalChecked();
3347
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3348

3349
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3350
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
3351
  v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
3352 3353 3354
      env->Global()
          ->Get(context, v8_str(env->GetIsolate(), "f"))
          .ToLocalChecked());
3355
  f->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
3356

3357
  // Setting event listener to nullptr should cause debugger unload.
3358
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3359
  CheckDebuggerUnloaded();
3360 3361

  // Compilation cache should be disabled when debugger is active.
3362
  CHECK_EQ(1, delegate.after_compile_event_count);
3363
}
3364

3365 3366
// Tests that script is reported as compiled when bound to context.
TEST(AfterCompileEventOnBindToContext) {
3367
  LocalContext env;
3368
  v8::Isolate* isolate = env->GetIsolate();
3369 3370 3371
  v8::HandleScope handle_scope(isolate);
  ScriptCompiledDelegate delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
3372 3373 3374 3375 3376 3377 3378 3379 3380

  const char* source = "var a=1";
  v8::ScriptCompiler::Source script_source(
      v8::String::NewFromUtf8(isolate, source, v8::NewStringType::kNormal)
          .ToLocalChecked());

  v8::Local<v8::UnboundScript> unbound =
      v8::ScriptCompiler::CompileUnboundScript(isolate, &script_source)
          .ToLocalChecked();
3381
  CHECK_EQ(delegate.after_compile_event_count, 0);
3382 3383

  unbound->BindToCurrentContext();
3384 3385
  CHECK_EQ(delegate.after_compile_event_count, 1);
  v8::debug::SetDebugDelegate(isolate, nullptr);
3386 3387 3388 3389
}


// Test that if DebugBreak is forced it is ignored when code from
3390
// debug-delay.js is executed.
3391
TEST(NoDebugBreakInAfterCompileEventListener) {
3392
  LocalContext env;
3393
  v8::HandleScope scope(env->GetIsolate());
3394
  v8::Local<v8::Context> context = env.local();
3395 3396

  // Register a debug event listener which sets the break flag and counts.
3397 3398
  DebugEventCounter delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3399 3400

  // Set the debug break flag.
3401
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
3402 3403 3404 3405 3406 3407 3408 3409 3410

  // Create a function for testing stepping.
  const char* src = "function f() { eval('var x = 10;'); } ";
  v8::Local<v8::Function> f = CompileFunction(&env, src, "f");

  // There should be only one break event.
  CHECK_EQ(1, break_point_hit_count);

  // Set the debug break flag again.
3411
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
3412
  f->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
3413 3414 3415
  // There should be one more break event when the script is evaluated in 'f'.
  CHECK_EQ(2, break_point_hit_count);

3416
  // Get rid of the debug event listener.
3417
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3418
  CheckDebuggerUnloaded();
3419
}
3420 3421


3422 3423
// Test that the debug break flag works with function.apply.
TEST(DebugBreakFunctionApply) {
3424
  LocalContext env;
3425
  v8::HandleScope scope(env->GetIsolate());
3426
  v8::Local<v8::Context> context = env.local();
3427 3428 3429 3430 3431 3432 3433 3434 3435 3436

  // Create a function for testing breaking in apply.
  v8::Local<v8::Function> foo = CompileFunction(
      &env,
      "function baz(x) { }"
      "function bar(x) { baz(); }"
      "function foo(){ bar.apply(this, [1]); }",
      "foo");

  // Register a debug event listener which steps and counts.
3437 3438
  DebugEventBreakMax delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3439 3440

  // Set the debug break flag before calling the code using function.apply.
3441
  v8::debug::SetBreakOnNextFunctionCall(env->GetIsolate());
3442 3443 3444 3445 3446

  // Limit the number of debug breaks. This is a regression test for issue 493
  // where this test would enter an infinite loop.
  break_point_hit_count = 0;
  max_break_point_hit_count = 10000;  // 10000 => infinite loop.
3447
  foo->Call(context, env->Global(), 0, nullptr).ToLocalChecked();
3448 3449

  // When keeping the debug break several break will happen.
3450
  CHECK_GT(break_point_hit_count, 1);
3451

3452
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3453
  CheckDebuggerUnloaded();
3454
}
3455

3456
// Test that setting the terminate execution flag during debug break processing.
3457 3458 3459
static void TestDebugBreakInLoop(const char* loop_head,
                                 const char** loop_bodies,
                                 const char* loop_tail) {
3460 3461
  // Receive 10 breaks for each test and then terminate JavaScript execution.
  static const int kBreaksPerTest = 10;
3462

3463
  for (int i = 0; loop_bodies[i] != nullptr; i++) {
3464 3465
    // Perform a lazy deoptimization after various numbers of breaks
    // have been hit.
3466

3467
    i::EmbeddedVector<char, 1024> buffer;
3468 3469 3470
    SNPrintF(buffer, "function f() {%s%s%s}", loop_head, loop_bodies[i],
             loop_tail);

3471
    i::PrintF("%s\n", buffer.begin());
3472 3473

    for (int j = 0; j < 3; j++) {
3474
      break_point_hit_count_deoptimize = j;
3475
      if (j == 2) {
3476 3477
        break_point_hit_count_deoptimize = kBreaksPerTest;
      }
3478

3479 3480 3481
      break_point_hit_count = 0;
      max_break_point_hit_count = kBreaksPerTest;
      terminate_after_max_break_point_hit = true;
3482

3483
      // Function with infinite loop.
3484
      CompileRun(buffer.begin());
3485

3486
      // Set the debug break to enter the debugger as soon as possible.
3487
      v8::debug::SetBreakOnNextFunctionCall(CcTest::isolate());
3488

3489 3490 3491
      // Call function with infinite loop.
      CompileRun("f();");
      CHECK_EQ(kBreaksPerTest, break_point_hit_count);
3492

3493
      CHECK(!CcTest::isolate()->IsExecutionTerminating());
3494
    }
3495 3496 3497
  }
}

3498 3499 3500 3501 3502 3503
static const char* loop_bodies_1[] = {"",
                                      "g()",
                                      "if (a == 0) { g() }",
                                      "if (a == 1) { g() }",
                                      "if (a == 0) { g() } else { h() }",
                                      "if (a == 0) { continue }",
3504
                                      nullptr};
3505 3506 3507 3508 3509 3510 3511

static const char* loop_bodies_2[] = {
    "if (a == 1) { continue }",
    "switch (a) { case 1: g(); }",
    "switch (a) { case 1: continue; }",
    "switch (a) { case 1: g(); break; default: h() }",
    "switch (a) { case 1: continue; break; default: h() }",
3512
    nullptr};
3513 3514 3515

void DebugBreakLoop(const char* loop_header, const char** loop_bodies,
                    const char* loop_footer) {
3516
  LocalContext env;
3517
  v8::HandleScope scope(env->GetIsolate());
3518 3519

  // Register a debug event listener which sets the break flag and counts.
3520 3521
  DebugEventBreakMax delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3522

3523 3524 3525 3526
  CompileRun(
      "var a = 1;\n"
      "function g() { }\n"
      "function h() { }");
3527

3528
  TestDebugBreakInLoop(loop_header, loop_bodies, loop_footer);
3529 3530

  // Get rid of the debug event listener.
3531
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3532
  CheckDebuggerUnloaded();
3533 3534 3535
}


3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590
TEST(DebugBreakInWhileTrue1) {
  DebugBreakLoop("while (true) {", loop_bodies_1, "}");
}


TEST(DebugBreakInWhileTrue2) {
  DebugBreakLoop("while (true) {", loop_bodies_2, "}");
}


TEST(DebugBreakInWhileCondition1) {
  DebugBreakLoop("while (a == 1) {", loop_bodies_1, "}");
}


TEST(DebugBreakInWhileCondition2) {
  DebugBreakLoop("while (a == 1) {", loop_bodies_2, "}");
}


TEST(DebugBreakInDoWhileTrue1) {
  DebugBreakLoop("do {", loop_bodies_1, "} while (true)");
}


TEST(DebugBreakInDoWhileTrue2) {
  DebugBreakLoop("do {", loop_bodies_2, "} while (true)");
}


TEST(DebugBreakInDoWhileCondition1) {
  DebugBreakLoop("do {", loop_bodies_1, "} while (a == 1)");
}


TEST(DebugBreakInDoWhileCondition2) {
  DebugBreakLoop("do {", loop_bodies_2, "} while (a == 1)");
}


TEST(DebugBreakInFor1) { DebugBreakLoop("for (;;) {", loop_bodies_1, "}"); }


TEST(DebugBreakInFor2) { DebugBreakLoop("for (;;) {", loop_bodies_2, "}"); }


TEST(DebugBreakInForCondition1) {
  DebugBreakLoop("for (;a == 1;) {", loop_bodies_1, "}");
}


TEST(DebugBreakInForCondition2) {
  DebugBreakLoop("for (;a == 1;) {", loop_bodies_2, "}");
}

3591 3592 3593 3594 3595 3596
class DebugBreakInlineListener : public v8::debug::DebugDelegate {
 public:
  void BreakProgramRequested(v8::Local<v8::Context> paused_context,
                             const std::vector<v8::debug::BreakpointId>&
                                 inspector_break_points_hit) override {
    int expected_frame_count = 4;
3597
    int expected_line_number[] = {1, 4, 7, 13};
3598 3599 3600 3601 3602 3603 3604 3605

    int frame_count = 0;
    auto iterator = v8::debug::StackTraceIterator::Create(CcTest::isolate());
    for (; !iterator->Done(); iterator->Advance(), ++frame_count) {
      v8::debug::Location loc = iterator->GetSourceLocation();
      CHECK_EQ(expected_line_number[frame_count], loc.GetLineNumber());
    }
    CHECK_EQ(frame_count, expected_frame_count);
3606
  }
3607
};
3608 3609 3610

TEST(DebugBreakInline) {
  i::FLAG_allow_natives_syntax = true;
3611
  LocalContext env;
3612
  v8::HandleScope scope(env->GetIsolate());
3613
  v8::Local<v8::Context> context = env.local();
3614
  const char* source =
3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627
      "function debug(b) {                 \n"
      "  if (b) debugger;                  \n"
      "}                                   \n"
      "function f(b) {                     \n"
      "  debug(b)                          \n"
      "};                                  \n"
      "function g(b) {                     \n"
      "  f(b);                             \n"
      "};                                  \n"
      "%PrepareFunctionForOptimization(g); \n"
      "g(false);                           \n"
      "g(false);                           \n"
      "%OptimizeFunctionOnNextCall(g);     \n"
3628
      "g(true);";
3629 3630 3631
  DebugBreakInlineListener delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
  v8::Local<v8::Script> inline_script =
3632 3633 3634
      v8::Script::Compile(context, v8_str(env->GetIsolate(), source))
          .ToLocalChecked();
  inline_script->Run(context).ToLocalChecked();
3635
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3636 3637
}

3638
static void RunScriptInANewCFrame(const char* source) {
3639
  v8::TryCatch try_catch(CcTest::isolate());
3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653
  CompileRun(source);
  CHECK(try_catch.HasCaught());
}


TEST(Regress131642) {
  // Bug description:
  // When doing StepNext through the first script, the debugger is not reset
  // after exiting through exception.  A flawed implementation enabling the
  // debugger to step into Array.prototype.forEach breaks inside the callback
  // for forEach in the second script under the assumption that we are in a
  // recursive call.  In an attempt to step out, we crawl the stack using the
  // recorded frame pointer from the first script and fail when not finding it
  // on the stack.
3654
  LocalContext env;
3655
  v8::HandleScope scope(env->GetIsolate());
3656 3657 3658
  DebugEventCounter delegate;
  delegate.set_step_action(StepNext);
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669

  // We step through the first script.  It exits through an exception.  We run
  // this inside a new frame to record a different FP than the second script
  // would expect.
  const char* script_1 = "debugger; throw new Error();";
  RunScriptInANewCFrame(script_1);

  // The second script uses forEach.
  const char* script_2 = "[0].forEach(function() { });";
  CompileRun(script_2);

3670
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
3671 3672
}

3673 3674 3675 3676 3677 3678 3679 3680
class DebugBreakStackTraceListener : public v8::debug::DebugDelegate {
 public:
  void BreakProgramRequested(v8::Local<v8::Context> paused_context,
                             const std::vector<v8::debug::BreakpointId>&
                                 inspector_break_points_hit) override {
    v8::StackTrace::CurrentStackTrace(CcTest::isolate(), 10);
  }
};
3681 3682

static void AddDebugBreak(const v8::FunctionCallbackInfo<v8::Value>& args) {
3683
  v8::debug::SetBreakOnNextFunctionCall(args.GetIsolate());
3684 3685 3686
}

TEST(DebugBreakStackTrace) {
3687
  LocalContext env;
3688
  v8::HandleScope scope(env->GetIsolate());
3689 3690 3691
  DebugBreakStackTraceListener delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
  v8::Local<v8::Context> context = env.local();
3692
  v8::Local<v8::FunctionTemplate> add_debug_break_template =
3693
      v8::FunctionTemplate::New(env->GetIsolate(), AddDebugBreak);
3694 3695 3696 3697 3698
  v8::Local<v8::Function> add_debug_break =
      add_debug_break_template->GetFunction(context).ToLocalChecked();
  CHECK(env->Global()
            ->Set(context, v8_str("add_debug_break"), add_debug_break)
            .FromJust());
3699 3700 3701 3702 3703 3704 3705 3706 3707

  CompileRun("(function loop() {"
             "  for (var j = 0; j < 1000; j++) {"
             "    for (var i = 0; i < 1000; i++) {"
             "      if (i == 999) add_debug_break();"
             "    }"
             "  }"
             "})()");
}
3708 3709


3710 3711
v8::base::Semaphore terminate_requested_semaphore(0);
v8::base::Semaphore terminate_fired_semaphore(0);
3712

3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724
class DebugBreakTriggerTerminate : public v8::debug::DebugDelegate {
 public:
  void BreakProgramRequested(v8::Local<v8::Context> paused_context,
                             const std::vector<v8::debug::BreakpointId>&
                                 inspector_break_points_hit) override {
    if (terminate_already_fired_) return;
    terminate_requested_semaphore.Signal();
    // Wait for at most 2 seconds for the terminate request.
    CHECK(
        terminate_fired_semaphore.WaitFor(v8::base::TimeDelta::FromSeconds(2)));
    terminate_already_fired_ = true;
  }
3725

3726 3727 3728
 private:
  bool terminate_already_fired_ = false;
};
3729

3730
class TerminationThread : public v8::base::Thread {
3731
 public:
3732 3733
  explicit TerminationThread(v8::Isolate* isolate)
      : Thread(Options("terminator")), isolate_(isolate) {}
3734

3735
  void Run() override {
3736
    terminate_requested_semaphore.Wait();
3737
    isolate_->TerminateExecution();
3738 3739 3740 3741 3742 3743 3744 3745 3746
    terminate_fired_semaphore.Signal();
  }

 private:
  v8::Isolate* isolate_;
};


TEST(DebugBreakOffThreadTerminate) {
3747
  LocalContext env;
3748 3749
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
3750 3751
  DebugBreakTriggerTerminate delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
3752 3753
  TerminationThread terminator(isolate);
  terminator.Start();
3754
  v8::TryCatch try_catch(env->GetIsolate());
3755
  env->GetIsolate()->RequestInterrupt(BreakRightNow, nullptr);
3756
  CompileRun("while (true);");
3757
  CHECK(try_catch.HasTerminated());
3758
}
3759

3760 3761 3762 3763 3764 3765 3766 3767 3768 3769
class ArchiveRestoreThread : public v8::base::Thread,
                             public v8::debug::DebugDelegate {
 public:
  ArchiveRestoreThread(v8::Isolate* isolate, int spawn_count)
      : Thread(Options("ArchiveRestoreThread")),
        isolate_(isolate),
        debug_(reinterpret_cast<i::Isolate*>(isolate_)->debug()),
        spawn_count_(spawn_count),
        break_count_(0) {}

3770
  void Run() override {
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800
    v8::Locker locker(isolate_);
    isolate_->Enter();

    v8::HandleScope scope(isolate_);
    v8::Local<v8::Context> context = v8::Context::New(isolate_);
    v8::Context::Scope context_scope(context);

    v8::Local<v8::Function> test = CompileFunction(isolate_,
                                                   "function test(n) {\n"
                                                   "  debugger;\n"
                                                   "  return n + 1;\n"
                                                   "}\n",
                                                   "test");

    debug_->SetDebugDelegate(this);
    v8::internal::DisableBreak enable_break(debug_, false);

    v8::Local<v8::Value> args[1] = {v8::Integer::New(isolate_, spawn_count_)};

    int result = test->Call(context, context->Global(), 1, args)
                     .ToLocalChecked()
                     ->Int32Value(context)
                     .FromJust();

    // Verify that test(spawn_count_) returned spawn_count_ + 1.
    CHECK_EQ(spawn_count_ + 1, result);

    isolate_->Exit();
  }

3801 3802 3803
  void BreakProgramRequested(
      v8::Local<v8::Context> context,
      const std::vector<v8::debug::BreakpointId>&) override {
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
    auto stack_traces = v8::debug::StackTraceIterator::Create(isolate_);
    if (!stack_traces->Done()) {
      v8::debug::Location location = stack_traces->GetSourceLocation();

      i::PrintF("ArchiveRestoreThread #%d hit breakpoint at line %d\n",
                spawn_count_, location.GetLineNumber());

      switch (location.GetLineNumber()) {
        case 1:  // debugger;
          CHECK_EQ(break_count_, 0);

          // Attempt to stop on the next line after the first debugger
          // statement. If debug->{Archive,Restore}Debug() improperly reset
          // thread-local debug information, the debugger will fail to stop
          // before the test function returns.
          debug_->PrepareStep(StepNext);

          // Spawning threads while handling the current breakpoint verifies
          // that the parent thread correctly archived and restored the
          // state necessary to stop on the next line. If not, then control
          // will simply continue past the `return n + 1` statement.
          MaybeSpawnChildThread();

          break;

        case 2:  // return n + 1;
          CHECK_EQ(break_count_, 1);
          break;

        default:
          CHECK(false);
      }
    }

    ++break_count_;
  }

  void MaybeSpawnChildThread() {
    if (spawn_count_ > 1) {
      v8::Unlocker unlocker(isolate_);

      // Spawn a thread that spawns a thread that spawns a thread (and so
      // on) so that the ThreadManager is forced to archive and restore
      // the current thread.
      ArchiveRestoreThread child(isolate_, spawn_count_ - 1);
      child.Start();
      child.Join();

      // The child thread sets itself as the debug delegate, so we need to
      // usurp it after the child finishes, or else future breakpoints
      // will be delegated to a destroyed ArchiveRestoreThread object.
      debug_->SetDebugDelegate(this);

      // This is the most important check in this test, since
      // child.GetBreakCount() will return 1 if the debugger fails to stop
      // on the `return n + 1` line after the grandchild thread returns.
      CHECK_EQ(child.GetBreakCount(), 2);
    }
  }

  int GetBreakCount() { return break_count_; }

 private:
  v8::Isolate* isolate_;
  v8::internal::Debug* debug_;
  const int spawn_count_;
  int break_count_;
};

TEST(DebugArchiveRestore) {
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
  v8::Isolate* isolate = v8::Isolate::New(create_params);

  ArchiveRestoreThread thread(isolate, 5);
  // Instead of calling thread.Start() and thread.Join() here, we call
  // thread.Run() directly, to make sure we exercise archive/restore
  // logic on the *current* thread as well as other threads.
  thread.Run();
  CHECK_EQ(thread.GetBreakCount(), 2);

  isolate->Dispose();
}

3888 3889 3890 3891
class DebugEventExpectNoException : public v8::debug::DebugDelegate {
 public:
  void ExceptionThrown(v8::Local<v8::Context> paused_context,
                       v8::Local<v8::Value> exception,
3892 3893
                       v8::Local<v8::Value> promise, bool is_uncaught,
                       v8::debug::ExceptionType) override {
3894 3895 3896
    CHECK(false);
  }
};
3897 3898 3899

static void TryCatchWrappedThrowCallback(
    const v8::FunctionCallbackInfo<v8::Value>& args) {
3900
  v8::TryCatch try_catch(args.GetIsolate());
3901 3902 3903 3904 3905
  CompileRun("throw 'rejection';");
  CHECK(try_catch.HasCaught());
}

TEST(DebugPromiseInterceptedByTryCatch) {
3906
  LocalContext env;
3907 3908
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
3909 3910 3911
  DebugEventExpectNoException delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
  v8::Local<v8::Context> context = env.local();
3912 3913
  ChangeBreakOnException(false, true);

3914
  v8::Local<v8::FunctionTemplate> fun =
3915
      v8::FunctionTemplate::New(isolate, TryCatchWrappedThrowCallback);
3916 3917 3918 3919
  CHECK(env->Global()
            ->Set(context, v8_str("fun"),
                  fun->GetFunction(context).ToLocalChecked())
            .FromJust());
3920 3921 3922 3923

  CompileRun("var p = new Promise(function(res, rej) { fun(); res(); });");
  CompileRun(
      "var r;"
3924 3925
      "p.then(function() { r = 'resolved'; },"
      "       function() { r = 'rejected'; });");
3926
  CHECK(CompileRun("r")->Equals(context, v8_str("resolved")).FromJust());
3927 3928
}

3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941
class NoInterruptsOnDebugEvent : public v8::debug::DebugDelegate {
 public:
  void ScriptCompiled(v8::Local<v8::debug::Script> script, bool is_live_edited,
                      bool has_compile_error) override {
    ++after_compile_handler_depth_;
    // Do not allow nested AfterCompile events.
    CHECK_LE(after_compile_handler_depth_, 1);
    v8::Isolate* isolate = CcTest::isolate();
    v8::Isolate::AllowJavascriptExecutionScope allow_script(isolate);
    isolate->RequestInterrupt(&HandleInterrupt, this);
    CompileRun("function foo() {}; foo();");
    --after_compile_handler_depth_;
  }
3942

3943 3944 3945 3946 3947
 private:
  static void HandleInterrupt(v8::Isolate* isolate, void* data) {
    NoInterruptsOnDebugEvent* d = static_cast<NoInterruptsOnDebugEvent*>(data);
    CHECK_EQ(0, d->after_compile_handler_depth_);
  }
3948

3949 3950
  int after_compile_handler_depth_ = 0;
};
3951 3952

TEST(NoInterruptsInDebugListener) {
3953 3954 3955 3956
  LocalContext env;
  v8::HandleScope handle_scope(env->GetIsolate());
  NoInterruptsOnDebugEvent delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
3957 3958
  CompileRun("void(0);");
}
3959 3960

TEST(BreakLocationIterator) {
3961
  LocalContext env;
3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
  v8::Isolate* isolate = env->GetIsolate();
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  v8::HandleScope scope(isolate);

  v8::Local<v8::Value> result = CompileRun(
      "function f() {\n"
      "  debugger;   \n"
      "  f();        \n"
      "  debugger;   \n"
      "}             \n"
      "f");
  Handle<i::Object> function_obj = v8::Utils::OpenHandle(*result);
  Handle<i::JSFunction> function = Handle<i::JSFunction>::cast(function_obj);
3975
  Handle<i::SharedFunctionInfo> shared(function->shared(), i_isolate);
3976 3977

  EnableDebugger(isolate);
3978
  CHECK(i_isolate->debug()->EnsureBreakInfo(shared));
3979
  i_isolate->debug()->PrepareFunctionForDebugExecution(shared);
3980

3981
  Handle<i::DebugInfo> debug_info(shared->GetDebugInfo(), i_isolate);
3982 3983

  {
3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
    i::BreakIterator iterator(debug_info);
    CHECK(iterator.GetBreakLocation().IsDebuggerStatement());
    CHECK_EQ(17, iterator.GetBreakLocation().position());
    iterator.Next();
    CHECK(iterator.GetBreakLocation().IsDebugBreakSlot());
    CHECK_EQ(32, iterator.GetBreakLocation().position());
    iterator.Next();
    CHECK(iterator.GetBreakLocation().IsCall());
    CHECK_EQ(32, iterator.GetBreakLocation().position());
    iterator.Next();
    CHECK(iterator.GetBreakLocation().IsDebuggerStatement());
    CHECK_EQ(47, iterator.GetBreakLocation().position());
    iterator.Next();
    CHECK(iterator.GetBreakLocation().IsReturn());
    CHECK_EQ(60, iterator.GetBreakLocation().position());
    iterator.Next();
    CHECK(iterator.Done());
4001 4002
  }

4003 4004
  DisableDebugger(isolate);
}
4005

4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017
class DebugStepOverFunctionWithCaughtExceptionListener
    : public v8::debug::DebugDelegate {
 public:
  void BreakProgramRequested(v8::Local<v8::Context> paused_context,
                             const std::vector<v8::debug::BreakpointId>&
                                 inspector_break_points_hit) override {
    ++break_point_hit_count;
    if (break_point_hit_count >= 3) return;
    PrepareStep(StepNext);
  }
  int break_point_hit_count = 0;
};
4018 4019 4020 4021

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

4022
  LocalContext env;
4023 4024
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
4025 4026
  DebugStepOverFunctionWithCaughtExceptionListener delegate;
  v8::debug::SetDebugDelegate(isolate, &delegate);
4027 4028 4029 4030 4031 4032 4033 4034 4035

  CompileRun(
      "function foo() {\n"
      "  try { throw new Error(); } catch (e) {}\n"
      "}\n"
      "debugger;\n"
      "foo();\n"
      "foo();\n");

4036 4037
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
  CHECK_EQ(3, delegate.break_point_hit_count);
4038
}
4039

4040 4041 4042 4043 4044
bool near_heap_limit_callback_called = false;
size_t NearHeapLimitCallback(void* data, size_t current_heap_limit,
                             size_t initial_heap_limit) {
  near_heap_limit_callback_called = true;
  return initial_heap_limit + 10u * i::MB;
4045 4046 4047 4048 4049
}

UNINITIALIZED_TEST(DebugSetOutOfMemoryListener) {
  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
4050
  create_params.constraints.set_max_old_generation_size_in_bytes(10 * i::MB);
4051 4052 4053 4054 4055 4056
  v8::Isolate* isolate = v8::Isolate::New(create_params);
  i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
  {
    v8::Isolate::Scope i_scope(isolate);
    v8::HandleScope scope(isolate);
    LocalContext context(isolate);
4057 4058
    isolate->AddNearHeapLimitCallback(NearHeapLimitCallback, nullptr);
    CHECK(!near_heap_limit_callback_called);
4059 4060
    // The following allocation fails unless the out-of-memory callback
    // increases the heap limit.
4061
    int length = 10 * i::MB / i::kTaggedSize;
4062
    i_isolate->factory()->NewFixedArray(length, i::AllocationType::kOld);
4063 4064
    CHECK(near_heap_limit_callback_called);
    isolate->RemoveNearHeapLimitCallback(NearHeapLimitCallback, 0);
4065 4066 4067
  }
  isolate->Dispose();
}
4068 4069 4070 4071 4072 4073

TEST(DebugCoverage) {
  i::FLAG_always_opt = false;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
4074 4075
  v8::debug::Coverage::SelectMode(isolate,
                                  v8::debug::CoverageMode::kPreciseCount);
4076 4077 4078 4079 4080 4081
  v8::Local<v8::String> source = v8_str(
      "function f() {\n"
      "}\n"
      "f();\n"
      "f();");
  CompileRun(source);
4082
  v8::debug::Coverage coverage = v8::debug::Coverage::CollectPrecise(isolate);
4083
  CHECK_EQ(1u, coverage.ScriptCount());
4084 4085
  v8::debug::Coverage::ScriptData script_data = coverage.GetScriptData(0);
  v8::Local<v8::debug::Script> script = script_data.GetScript();
4086 4087 4088 4089 4090
  CHECK(script->Source()
            .ToLocalChecked()
            ->Equals(env.local(), source)
            .FromMaybe(false));

4091 4092 4093
  CHECK_EQ(2u, script_data.FunctionCount());
  v8::debug::Coverage::FunctionData function_data =
      script_data.GetFunctionData(0);
4094 4095 4096 4097 4098 4099 4100 4101
  v8::debug::Location start =
      script->GetSourceLocation(function_data.StartOffset());
  v8::debug::Location end =
      script->GetSourceLocation(function_data.EndOffset());
  CHECK_EQ(0, start.GetLineNumber());
  CHECK_EQ(0, start.GetColumnNumber());
  CHECK_EQ(3, end.GetLineNumber());
  CHECK_EQ(4, end.GetColumnNumber());
4102 4103 4104
  CHECK_EQ(1, function_data.Count());

  function_data = script_data.GetFunctionData(1);
4105 4106 4107 4108 4109 4110
  start = script->GetSourceLocation(function_data.StartOffset());
  end = script->GetSourceLocation(function_data.EndOffset());
  CHECK_EQ(0, start.GetLineNumber());
  CHECK_EQ(0, start.GetColumnNumber());
  CHECK_EQ(1, end.GetLineNumber());
  CHECK_EQ(1, end.GetColumnNumber());
4111
  CHECK_EQ(2, function_data.Count());
4112
}
4113

4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
namespace {
v8::debug::Coverage::ScriptData GetScriptDataAndDeleteCoverage(
    v8::Isolate* isolate) {
  v8::debug::Coverage coverage = v8::debug::Coverage::CollectPrecise(isolate);
  CHECK_EQ(1u, coverage.ScriptCount());
  return coverage.GetScriptData(0);
}
}  // namespace

TEST(DebugCoverageWithCoverageOutOfScope) {
  i::FLAG_always_opt = false;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
4128 4129
  v8::debug::Coverage::SelectMode(isolate,
                                  v8::debug::CoverageMode::kPreciseCount);
4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
  v8::Local<v8::String> source = v8_str(
      "function f() {\n"
      "}\n"
      "f();\n"
      "f();");
  CompileRun(source);
  v8::debug::Coverage::ScriptData script_data =
      GetScriptDataAndDeleteCoverage(isolate);
  v8::Local<v8::debug::Script> script = script_data.GetScript();
  CHECK(script->Source()
            .ToLocalChecked()
            ->Equals(env.local(), source)
            .FromMaybe(false));

  CHECK_EQ(2u, script_data.FunctionCount());
  v8::debug::Coverage::FunctionData function_data =
      script_data.GetFunctionData(0);

  CHECK_EQ(0, function_data.StartOffset());
  CHECK_EQ(26, function_data.EndOffset());

  v8::debug::Location start =
      script->GetSourceLocation(function_data.StartOffset());
  v8::debug::Location end =
      script->GetSourceLocation(function_data.EndOffset());
  CHECK_EQ(0, start.GetLineNumber());
  CHECK_EQ(0, start.GetColumnNumber());
  CHECK_EQ(3, end.GetLineNumber());
  CHECK_EQ(4, end.GetColumnNumber());
  CHECK_EQ(1, function_data.Count());

  function_data = script_data.GetFunctionData(1);
  start = script->GetSourceLocation(function_data.StartOffset());
  end = script->GetSourceLocation(function_data.EndOffset());

  CHECK_EQ(0, function_data.StartOffset());
  CHECK_EQ(16, function_data.EndOffset());

  CHECK_EQ(0, start.GetLineNumber());
  CHECK_EQ(0, start.GetColumnNumber());
  CHECK_EQ(1, end.GetLineNumber());
  CHECK_EQ(1, end.GetColumnNumber());
  CHECK_EQ(2, function_data.Count());
}

namespace {
v8::debug::Coverage::FunctionData GetFunctionDataAndDeleteCoverage(
    v8::Isolate* isolate) {
  v8::debug::Coverage coverage = v8::debug::Coverage::CollectPrecise(isolate);
  CHECK_EQ(1u, coverage.ScriptCount());

  v8::debug::Coverage::ScriptData script_data = coverage.GetScriptData(0);

  CHECK_EQ(2u, script_data.FunctionCount());
  v8::debug::Coverage::FunctionData function_data =
      script_data.GetFunctionData(0);
  CHECK_EQ(1, function_data.Count());
  CHECK_EQ(0, function_data.StartOffset());
  CHECK_EQ(26, function_data.EndOffset());
  return function_data;
}
}  // namespace

TEST(DebugCoverageWithScriptDataOutOfScope) {
  i::FLAG_always_opt = false;
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
4198 4199
  v8::debug::Coverage::SelectMode(isolate,
                                  v8::debug::CoverageMode::kPreciseCount);
4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213
  v8::Local<v8::String> source = v8_str(
      "function f() {\n"
      "}\n"
      "f();\n"
      "f();");
  CompileRun(source);

  v8::debug::Coverage::FunctionData function_data =
      GetFunctionDataAndDeleteCoverage(isolate);
  CHECK_EQ(1, function_data.Count());
  CHECK_EQ(0, function_data.StartOffset());
  CHECK_EQ(26, function_data.EndOffset());
}

4214 4215
TEST(BuiltinsExceptionPrediction) {
  v8::Isolate* isolate = CcTest::isolate();
4216
  i::Isolate* iisolate = CcTest::i_isolate();
4217 4218 4219
  v8::HandleScope handle_scope(isolate);
  v8::Context::New(isolate);

4220
  i::Builtins* builtins = iisolate->builtins();
4221 4222
  bool fail = false;
  for (int i = 0; i < i::Builtins::builtin_count; i++) {
4223
    i::Code builtin = builtins->builtin(i);
4224 4225
    if (builtin.kind() != i::Code::BUILTIN) continue;
    auto prediction = builtin.GetBuiltinCatchPrediction();
4226
    USE(prediction);
4227 4228 4229
  }
  CHECK(!fail);
}
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244

TEST(DebugGetPossibleBreakpointsReturnLocations) {
  LocalContext env;
  v8::Isolate* isolate = env->GetIsolate();
  v8::HandleScope scope(isolate);
  v8::Local<v8::String> source = v8_str(
      "function fib(x) {\n"
      "  if (x < 0) return;\n"
      "  if (x === 0) return 1;\n"
      "  if (x === 1) return fib(0);\n"
      "  return x > 2 ? fib(x - 1) + fib(x - 2) : fib(1) + fib(0);\n"
      "}");
  CompileRun(source);
  v8::PersistentValueVector<v8::debug::Script> scripts(isolate);
  v8::debug::GetLoadedScripts(isolate, scripts);
4245
  CHECK_EQ(scripts.Size(), 1);
4246 4247 4248 4249 4250 4251 4252 4253 4254
  std::vector<v8::debug::BreakLocation> locations;
  CHECK(scripts.Get(0)->GetPossibleBreakpoints(
      v8::debug::Location(0, 17), v8::debug::Location(), true, &locations));
  int returns_count = 0;
  for (size_t i = 0; i < locations.size(); ++i) {
    if (locations[i].type() == v8::debug::kReturnBreakLocation) {
      ++returns_count;
    }
  }
4255 4256
  // With Ignition we generate one return location per return statement,
  // each has line = 5, column = 0 as statement position.
4257
  CHECK_EQ(returns_count, 4);
4258
}
4259 4260 4261

TEST(DebugEvaluateNoSideEffect) {
  LocalContext env;
4262 4263
  v8::HandleScope scope(env->GetIsolate());
  EnableDebugger(env->GetIsolate());
4264
  i::Isolate* isolate = CcTest::i_isolate();
4265
  std::vector<i::Handle<i::JSFunction>> all_functions;
4266
  {
4267
    i::HeapObjectIterator iterator(isolate->heap());
4268 4269
    for (i::HeapObject obj = iterator.Next(); !obj.is_null();
         obj = iterator.Next()) {
4270
      if (!obj.IsJSFunction()) continue;
4271
      i::JSFunction fun = i::JSFunction::cast(obj);
4272
      all_functions.emplace_back(fun, isolate);
4273 4274 4275 4276 4277
    }
  }

  // Perform side effect check on all built-in functions. The side effect check
  // itself contains additional sanity checks.
4278
  for (i::Handle<i::JSFunction> fun : all_functions) {
4279
    bool failed = false;
4280
    isolate->debug()->StartSideEffectCheckMode();
4281 4282
    failed = !isolate->debug()->PerformSideEffectCheck(
        fun, v8::Utils::OpenHandle(*env->Global()));
4283
    isolate->debug()->StopSideEffectCheckMode();
4284 4285
    if (failed) isolate->clear_pending_exception();
  }
4286
  DisableDebugger(env->GetIsolate());
4287
}
4288 4289 4290 4291 4292 4293 4294 4295

namespace {
i::MaybeHandle<i::Script> FindScript(
    i::Isolate* isolate, const std::vector<i::Handle<i::Script>>& scripts,
    const char* name) {
  Handle<i::String> i_name =
      isolate->factory()->NewStringFromAsciiChecked(name);
  for (const auto& script : scripts) {
4296
    if (!script->name().IsString()) continue;
4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315
    if (i_name->Equals(i::String::cast(script->name()))) return script;
  }
  return i::MaybeHandle<i::Script>();
}
}  // anonymous namespace

UNINITIALIZED_TEST(LoadedAtStartupScripts) {
  i::FLAG_expose_gc = true;

  v8::Isolate::CreateParams create_params;
  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 i_scope(isolate);
    v8::HandleScope scope(isolate);
    LocalContext context(isolate);

    std::vector<i::Handle<i::Script>> scripts;
4316 4317
    CompileWithOrigin(v8_str("function foo(){}"), v8_str("normal.js"),
                      v8_bool(false));
4318 4319 4320 4321
    std::unordered_map<int, int> count_by_type;
    {
      i::DisallowHeapAllocation no_gc;
      i::Script::Iterator iterator(i_isolate);
4322 4323
      for (i::Script script = iterator.Next(); !script.is_null();
           script = iterator.Next()) {
4324 4325
        if (script.type() == i::Script::TYPE_NATIVE &&
            script.name().IsUndefined(i_isolate)) {
4326 4327
          continue;
        }
4328
        ++count_by_type[script.type()];
4329 4330 4331
        scripts.emplace_back(script, i_isolate);
      }
    }
4332
    CHECK_EQ(count_by_type[i::Script::TYPE_NATIVE], 0);
4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
    CHECK_EQ(count_by_type[i::Script::TYPE_EXTENSION], 2);
    CHECK_EQ(count_by_type[i::Script::TYPE_NORMAL], 1);
    CHECK_EQ(count_by_type[i::Script::TYPE_WASM], 0);
    CHECK_EQ(count_by_type[i::Script::TYPE_INSPECTOR], 0);

    i::Handle<i::Script> gc_script =
        FindScript(i_isolate, scripts, "v8/gc").ToHandleChecked();
    CHECK_EQ(gc_script->type(), i::Script::TYPE_EXTENSION);

    i::Handle<i::Script> normal_script =
        FindScript(i_isolate, scripts, "normal.js").ToHandleChecked();
    CHECK_EQ(normal_script->type(), i::Script::TYPE_NORMAL);
  }
  isolate->Dispose();
}

TEST(SourceInfo) {
  LocalContext env;
  v8::HandleScope scope(env->GetIsolate());
  const char* source =
      "//\n"
      "function a() { b(); };\n"
      "function    b() {\n"
      "  c(true);\n"
      "};\n"
      "  function c(x) {\n"
      "    if (x) {\n"
      "      return 1;\n"
      "    } else {\n"
      "      return 1;\n"
      "    }\n"
      "  };\n"
      "function d(x) {\n"
      "  x = 1 ;\n"
      "  x = 2 ;\n"
      "  x = 3 ;\n"
      "  x = 4 ;\n"
      "  x = 5 ;\n"
      "  x = 6 ;\n"
      "  x = 7 ;\n"
      "  x = 8 ;\n"
      "  x = 9 ;\n"
      "  x = 10;\n"
      "  x = 11;\n"
      "  x = 12;\n"
      "  x = 13;\n"
      "  x = 14;\n"
      "  x = 15;\n"
      "}\n";
  v8::Local<v8::Script> v8_script =
      v8::Script::Compile(env.local(), v8_str(source)).ToLocalChecked();
  i::Handle<i::Script> i_script(
4385
      i::Script::cast(v8::Utils::OpenHandle(*v8_script)->shared().script()),
4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
      CcTest::i_isolate());
  v8::Local<v8::debug::Script> script =
      v8::ToApiHandle<v8::debug::Script>(i_script);

  // Test that when running through source positions the position, line and
  // column progresses as expected.
  v8::debug::Location prev_location = script->GetSourceLocation(0);
  CHECK_EQ(prev_location.GetLineNumber(), 0);
  CHECK_EQ(prev_location.GetColumnNumber(), 0);
  for (int offset = 1; offset < 100; ++offset) {
    v8::debug::Location location = script->GetSourceLocation(offset);
    if (prev_location.GetLineNumber() == location.GetLineNumber()) {
      CHECK_EQ(location.GetColumnNumber(), prev_location.GetColumnNumber() + 1);
    } else {
      CHECK_EQ(location.GetLineNumber(), prev_location.GetLineNumber() + 1);
      CHECK_EQ(location.GetColumnNumber(), 0);
    }
    prev_location = location;
  }

  // Every line of d() is the same length.  Verify we can loop through all
  // positions and find the right line # for each.
  // The position of the first line of d(), i.e. "x = 1 ;".
  const int start_line_d = 13;
  const int start_code_d =
      static_cast<int>(strstr(source, "  x = 1 ;") - source);
  const int num_lines_d = 15;
  const int line_length_d = 10;
  int p = start_code_d;
  for (int line = 0; line < num_lines_d; ++line) {
    for (int column = 0; column < line_length_d; ++column) {
      v8::debug::Location location = script->GetSourceLocation(p);
      CHECK_EQ(location.GetLineNumber(), start_line_d + line);
      CHECK_EQ(location.GetColumnNumber(), column);
      ++p;
    }
  }

  // Test first positon.
  CHECK_EQ(script->GetSourceLocation(0).GetLineNumber(), 0);
  CHECK_EQ(script->GetSourceLocation(0).GetColumnNumber(), 0);

  // Test second positon.
  CHECK_EQ(script->GetSourceLocation(1).GetLineNumber(), 0);
  CHECK_EQ(script->GetSourceLocation(1).GetColumnNumber(), 1);

  // Test first positin in function a().
  const int start_a =
      static_cast<int>(strstr(source, "function a") - source) + 10;
  CHECK_EQ(script->GetSourceLocation(start_a).GetLineNumber(), 1);
  CHECK_EQ(script->GetSourceLocation(start_a).GetColumnNumber(), 10);

  // Test first positin in function b().
  const int start_b =
      static_cast<int>(strstr(source, "function    b") - source) + 13;
  CHECK_EQ(script->GetSourceLocation(start_b).GetLineNumber(), 2);
  CHECK_EQ(script->GetSourceLocation(start_b).GetColumnNumber(), 13);

  // Test first positin in function c().
  const int start_c =
      static_cast<int>(strstr(source, "function c") - source) + 10;
  CHECK_EQ(script->GetSourceLocation(start_c).GetLineNumber(), 5);
  CHECK_EQ(script->GetSourceLocation(start_c).GetColumnNumber(), 12);

  // Test first positin in function d().
  const int start_d =
      static_cast<int>(strstr(source, "function d") - source) + 10;
  CHECK_EQ(script->GetSourceLocation(start_d).GetLineNumber(), 12);
  CHECK_EQ(script->GetSourceLocation(start_d).GetColumnNumber(), 10);

  // Test offsets.
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(1, 10)), start_a);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(2, 13)), start_b);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(3, 0)), start_b + 5);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(3, 2)), start_b + 7);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(4, 0)), start_b + 16);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(5, 12)), start_c);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(6, 0)), start_c + 6);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(7, 0)), start_c + 19);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(8, 0)), start_c + 35);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(9, 0)), start_c + 48);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(10, 0)), start_c + 64);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(11, 0)), start_c + 70);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(12, 10)), start_d);
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(13, 0)), start_d + 6);
  for (int i = 1; i <= num_lines_d; ++i) {
    CHECK_EQ(script->GetSourceOffset(v8::debug::Location(start_line_d + i, 0)),
             6 + (i * line_length_d) + start_d);
  }
  CHECK_EQ(script->GetSourceOffset(v8::debug::Location(start_line_d + 17, 0)),
           start_d + 158);

  // Make sure invalid inputs work properly.
  const int last_position = static_cast<int>(strlen(source)) - 1;
  CHECK_EQ(script->GetSourceLocation(-1).GetLineNumber(), 0);
  CHECK_EQ(script->GetSourceLocation(last_position + 2).GetLineNumber(),
           i::kNoSourcePosition);

  // Test last position.
  CHECK_EQ(script->GetSourceLocation(last_position).GetLineNumber(), 28);
  CHECK_EQ(script->GetSourceLocation(last_position).GetColumnNumber(), 1);
  CHECK_EQ(script->GetSourceLocation(last_position + 1).GetLineNumber(), 29);
  CHECK_EQ(script->GetSourceLocation(last_position + 1).GetColumnNumber(), 0);
}

namespace {
class SetBreakpointOnScriptCompiled : public v8::debug::DebugDelegate {
 public:
  void ScriptCompiled(v8::Local<v8::debug::Script> script, bool is_live_edited,
                      bool has_compile_error) override {
    v8::Local<v8::String> name;
    if (!script->SourceURL().ToLocal(&name)) return;
    v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();
    if (!name->Equals(context, v8_str("test")).FromJust()) return;
    CHECK(!has_compile_error);
    v8::debug::Location loc(1, 2);
    CHECK(script->SetBreakpoint(v8_str(""), &loc, &id_));
    CHECK_EQ(loc.GetLineNumber(), 1);
    CHECK_EQ(loc.GetColumnNumber(), 10);
  }

  void BreakProgramRequested(v8::Local<v8::Context> paused_context,
                             const std::vector<v8::debug::BreakpointId>&
                                 inspector_break_points_hit) override {
    ++break_count_;
    CHECK_EQ(inspector_break_points_hit[0], id_);
  }

  int break_count() const { return break_count_; }

 private:
  int break_count_ = 0;
  v8::debug::BreakpointId id_;
};
}  // anonymous namespace

TEST(Regress517592) {
  LocalContext env;
  v8::HandleScope handle_scope(env->GetIsolate());
  SetBreakpointOnScriptCompiled delegate;
  v8::debug::SetDebugDelegate(env->GetIsolate(), &delegate);
  CompileRun(
      v8_str("eval('var foo = function foo() {\\n' +\n"
             "'  var a = 1;\\n' +\n"
             "'}\\n' +\n"
             "'//@ sourceURL=test')"));
  CHECK_EQ(delegate.break_count(), 0);
  CompileRun(v8_str("foo()"));
  CHECK_EQ(delegate.break_count(), 1);
  v8::debug::SetDebugDelegate(env->GetIsolate(), nullptr);
}
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563

TEST(GetPrivateFields) {
  LocalContext env;
  v8::Isolate* v8_isolate = CcTest::isolate();
  v8::internal::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(v8_isolate);
  v8::Local<v8::Context> context = env.local();
  v8::Local<v8::String> source = v8_str(
      "var X = class {\n"
      "  #foo = 1;\n"
      "  #bar = function() {};\n"
      "}\n"
      "var x = new X()");
  CompileRun(source);
  v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(
      env->Global()
          ->Get(context, v8_str(env->GetIsolate(), "x"))
          .ToLocalChecked());
  v8::Local<v8::Array> private_names =
      v8::debug::GetPrivateFields(context, object).ToLocalChecked();

  for (int i = 0; i < 4; i = i + 2) {
    Handle<v8::internal::JSReceiver> private_name =
        v8::Utils::OpenHandle(*private_names->Get(context, i)
                                   .ToLocalChecked()
                                   ->ToObject(context)
                                   .ToLocalChecked());
4564 4565
    Handle<v8::internal::JSPrimitiveWrapper> private_value =
        Handle<v8::internal::JSPrimitiveWrapper>::cast(private_name);
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592
    Handle<v8::internal::Symbol> priv_symbol(
        v8::internal::Symbol::cast(private_value->value()), isolate);
    CHECK(priv_symbol->is_private_name());
  }

  source = v8_str(
      "var Y = class {\n"
      "  #baz = 2;\n"
      "}\n"
      "var X = class extends Y{\n"
      "  #foo = 1;\n"
      "  #bar = function() {};\n"
      "}\n"
      "var x = new X()");
  CompileRun(source);
  object = v8::Local<v8::Object>::Cast(
      env->Global()
          ->Get(context, v8_str(env->GetIsolate(), "x"))
          .ToLocalChecked());
  private_names = v8::debug::GetPrivateFields(context, object).ToLocalChecked();

  for (int i = 0; i < 6; i = i + 2) {
    Handle<v8::internal::JSReceiver> private_name =
        v8::Utils::OpenHandle(*private_names->Get(context, i)
                                   .ToLocalChecked()
                                   ->ToObject(context)
                                   .ToLocalChecked());
4593 4594
    Handle<v8::internal::JSPrimitiveWrapper> private_value =
        Handle<v8::internal::JSPrimitiveWrapper>::cast(private_name);
4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623
    Handle<v8::internal::Symbol> priv_symbol(
        v8::internal::Symbol::cast(private_value->value()), isolate);
    CHECK(priv_symbol->is_private_name());
  }

  source = v8_str(
      "var Y = class {\n"
      "  constructor() {"
      "    return new Proxy({}, {});"
      "  }"
      "}\n"
      "var X = class extends Y{\n"
      "  #foo = 1;\n"
      "  #bar = function() {};\n"
      "}\n"
      "var x = new X()");
  CompileRun(source);
  object = v8::Local<v8::Object>::Cast(
      env->Global()
          ->Get(context, v8_str(env->GetIsolate(), "x"))
          .ToLocalChecked());
  private_names = v8::debug::GetPrivateFields(context, object).ToLocalChecked();

  for (int i = 0; i < 4; i = i + 2) {
    Handle<v8::internal::JSReceiver> private_name =
        v8::Utils::OpenHandle(*private_names->Get(context, i)
                                   .ToLocalChecked()
                                   ->ToObject(context)
                                   .ToLocalChecked());
4624 4625
    Handle<v8::internal::JSPrimitiveWrapper> private_value =
        Handle<v8::internal::JSPrimitiveWrapper>::cast(private_name);
4626 4627 4628 4629 4630
    Handle<v8::internal::Symbol> priv_symbol(
        v8::internal::Symbol::cast(private_value->value()), isolate);
    CHECK(priv_symbol->is_private_name());
  }
}