debug.js 72.5 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5

(function (global, utils) {
6
"use strict";
7

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// ----------------------------------------------------------------------------
// Imports

var FrameMirror = global.FrameMirror;
var GlobalArray = global.Array;
var GlobalRegExp = global.RegExp;
var IsNaN = global.isNaN;
var JSONParse = global.JSON.parse;
var JSONStringify = global.JSON.stringify;
var LookupMirror = global.LookupMirror;
var MakeMirror = global.MakeMirror;
var MakeMirrorSerializer = global.MakeMirrorSerializer;
var MathMin = global.Math.min;
var Mirror = global.Mirror;
var MirrorType;
var ParseInt = global.parseInt;
var ValueMirror = global.ValueMirror;

utils.Import(function(from) {
  MirrorType = from.MirrorType;
});

//----------------------------------------------------------------------------

32
// Default number of frames to include in the response to backtrace request.
33
var kDefaultBacktraceLength = 10;
34

35
var Debug = {};
36 37 38 39

// Regular expression to skip "crud" at the beginning of a source line which is
// not really code. Currently the regular expression matches whitespace and
// comments.
40
var sourceLineBeginningSkip = /^(?:\s*(?:\/\*.*?\*\/)*)*/;
41 42 43 44 45 46 47

// Debug events which can occour in the V8 JavaScript engine. These originate
// from the API include file debug.h.
Debug.DebugEvent = { Break: 1,
                     Exception: 2,
                     NewFunction: 3,
                     BeforeCompile: 4,
48
                     AfterCompile: 5,
49
                     CompileError: 6,
50
                     AsyncTaskEvent: 7 };
51 52

// Types of exceptions that can be broken upon.
53
Debug.ExceptionBreak = { Caught : 0,
54 55 56 57 58 59
                         Uncaught: 1 };

// The different types of steps.
Debug.StepAction = { StepOut: 0,
                     StepNext: 1,
                     StepIn: 2,
60
                     StepFrame: 3 };
61 62 63 64

// The different types of scripts matching enum ScriptType in objects.h.
Debug.ScriptType = { Native: 0,
                     Extension: 1,
65 66
                     Normal: 2,
                     Wasm: 3};
67

68 69 70 71 72 73
// The different types of script compilations matching enum
// Script::CompilationType in objects.h.
Debug.ScriptCompilationType = { Host: 0,
                                Eval: 1,
                                JSON: 2 };

74 75
// The different script break point types.
Debug.ScriptBreakPointType = { ScriptId: 0,
76 77
                               ScriptName: 1,
                               ScriptRegExp: 2 };
78

79 80 81 82 83 84 85
// The different types of breakpoint position alignments.
// Must match BreakPositionAlignment in debug.h.
Debug.BreakPositionAlignment = {
  Statement: 0,
  BreakPosition: 1
};

86 87 88 89 90 91 92 93 94
function ScriptTypeFlag(type) {
  return (1 << type);
}

// Globals.
var next_response_seq = 0;
var next_break_point_number = 1;
var break_points = [];
var script_break_points = [];
95 96 97 98 99 100
var debugger_flags = {
  breakPointsActive: {
    value: true,
    getValue: function() { return this.value; },
    setValue: function(value) {
      this.value = !!value;
101
      %SetBreakPointsActive(this.value);
102
    }
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  },
  breakOnCaughtException: {
    getValue: function() { return Debug.isBreakOnException(); },
    setValue: function(value) {
      if (value) {
        Debug.setBreakOnException();
      } else {
        Debug.clearBreakOnException();
      }
    }
  },
  breakOnUncaughtException: {
    getValue: function() { return Debug.isBreakOnUncaughtException(); },
    setValue: function(value) {
      if (value) {
        Debug.setBreakOnUncaughtException();
      } else {
        Debug.clearBreakOnUncaughtException();
      }
    }
  },
124
};
125 126 127


// Create a new break point object and add it to the list of break points.
128 129
function MakeBreakPoint(source_position, opt_script_break_point) {
  var break_point = new BreakPoint(source_position, opt_script_break_point);
130 131
  break_points.push(break_point);
  return break_point;
132
}
133 134 135 136 137 138


// Object representing a break point.
// NOTE: This object does not have a reference to the function having break
// point as this would cause function not to be garbage collected when it is
// not used any more. We do not want break points to keep functions alive.
139
function BreakPoint(source_position, opt_script_break_point) {
140 141 142 143 144 145 146 147
  this.source_position_ = source_position;
  if (opt_script_break_point) {
    this.script_break_point_ = opt_script_break_point;
  } else {
    this.number_ = next_break_point_number++;
  }
  this.active_ = true;
  this.condition_ = null;
148
}
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209


BreakPoint.prototype.number = function() {
  return this.number_;
};


BreakPoint.prototype.func = function() {
  return this.func_;
};


BreakPoint.prototype.source_position = function() {
  return this.source_position_;
};


BreakPoint.prototype.active = function() {
  if (this.script_break_point()) {
    return this.script_break_point().active();
  }
  return this.active_;
};


BreakPoint.prototype.condition = function() {
  if (this.script_break_point() && this.script_break_point().condition()) {
    return this.script_break_point().condition();
  }
  return this.condition_;
};


BreakPoint.prototype.script_break_point = function() {
  return this.script_break_point_;
};


BreakPoint.prototype.enable = function() {
  this.active_ = true;
};


BreakPoint.prototype.disable = function() {
  this.active_ = false;
};


BreakPoint.prototype.setCondition = function(condition) {
  this.condition_ = condition;
};


BreakPoint.prototype.isTriggered = function(exec_state) {
  // Break point not active - not triggered.
  if (!this.active()) return false;

  // Check for conditional break point.
  if (this.condition()) {
    // If break point has condition try to evaluate it in the top frame.
    try {
210
      var mirror = exec_state.frame(0).evaluate(this.condition());
211
      // If no sensible mirror or non true value break point not triggered.
212
      if (!(mirror instanceof ValueMirror) || !mirror.value_) {
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        return false;
      }
    } catch (e) {
      // Exception evaluating condition counts as not triggered.
      return false;
    }
  }

  // Break point triggered.
  return true;
};


// Function called from the runtime when a break point is hit. Returns true if
// the break point is triggered and supposed to break execution.
function IsBreakPointTriggered(break_id, break_point) {
  return break_point.isTriggered(MakeExecutionState(break_id));
230
}
231 232 233


// Object representing a script break point. The script is referenced by its
234 235
// script name or script id and the break point is represented as line and
// column.
236
function ScriptBreakPoint(type, script_id_or_name, opt_line, opt_column,
237
                          opt_groupId, opt_position_alignment) {
238 239 240
  this.type_ = type;
  if (type == Debug.ScriptBreakPointType.ScriptId) {
    this.script_id_ = script_id_or_name;
241
  } else if (type == Debug.ScriptBreakPointType.ScriptName) {
242
    this.script_name_ = script_id_or_name;
243
  } else if (type == Debug.ScriptBreakPointType.ScriptRegExp) {
244
    this.script_regexp_object_ = new GlobalRegExp(script_id_or_name);
245
  } else {
246
    throw %make_error(kDebugger, "Unexpected breakpoint type " + type);
247
  }
248 249
  this.line_ = opt_line || 0;
  this.column_ = opt_column;
250
  this.groupId_ = opt_groupId;
251 252
  this.position_alignment_ = IS_UNDEFINED(opt_position_alignment)
      ? Debug.BreakPositionAlignment.Statement : opt_position_alignment;
253 254
  this.active_ = true;
  this.condition_ = null;
255
  this.break_points_ = [];
256
}
257 258


259
// Creates a clone of script breakpoint that is linked to another script.
260 261
ScriptBreakPoint.prototype.cloneForOtherScript = function (other_script) {
  var copy = new ScriptBreakPoint(Debug.ScriptBreakPointType.ScriptId,
262 263
      other_script.id, this.line_, this.column_, this.groupId_,
      this.position_alignment_);
264 265
  copy.number_ = next_break_point_number++;
  script_break_points.push(copy);
266

267 268 269
  copy.active_ = this.active_;
  copy.condition_ = this.condition_;
  return copy;
270
};
271 272


273 274 275 276 277
ScriptBreakPoint.prototype.number = function() {
  return this.number_;
};


278 279 280 281 282
ScriptBreakPoint.prototype.groupId = function() {
  return this.groupId_;
};


283 284 285 286 287 288 289 290 291 292
ScriptBreakPoint.prototype.type = function() {
  return this.type_;
};


ScriptBreakPoint.prototype.script_id = function() {
  return this.script_id_;
};


293 294 295 296 297
ScriptBreakPoint.prototype.script_name = function() {
  return this.script_name_;
};


298 299 300 301 302
ScriptBreakPoint.prototype.script_regexp_object = function() {
  return this.script_regexp_object_;
};


303 304 305 306 307 308 309 310 311 312
ScriptBreakPoint.prototype.line = function() {
  return this.line_;
};


ScriptBreakPoint.prototype.column = function() {
  return this.column_;
};


313 314 315 316 317 318
ScriptBreakPoint.prototype.actual_locations = function() {
  var locations = [];
  for (var i = 0; i < this.break_points_.length; i++) {
    locations.push(this.break_points_[i].actual_location);
  }
  return locations;
319
};
320 321


322 323 324
ScriptBreakPoint.prototype.update_positions = function(line, column) {
  this.line_ = line;
  this.column_ = column;
325
};
326 327


328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
ScriptBreakPoint.prototype.active = function() {
  return this.active_;
};


ScriptBreakPoint.prototype.condition = function() {
  return this.condition_;
};


ScriptBreakPoint.prototype.enable = function() {
  this.active_ = true;
};


ScriptBreakPoint.prototype.disable = function() {
  this.active_ = false;
};


ScriptBreakPoint.prototype.setCondition = function(condition) {
  this.condition_ = condition;
};


// Check whether a script matches this script break point. Currently this is
// only based on script name.
ScriptBreakPoint.prototype.matchesScript = function(script) {
356 357
  if (this.type_ == Debug.ScriptBreakPointType.ScriptId) {
    return this.script_id_ == script.id;
358 359 360
  } else {
    // We might want to account columns here as well.
    if (!(script.line_offset <= this.line_  &&
361
          this.line_ < script.line_offset + %ScriptLineCount(script))) {
362 363 364 365 366 367
      return false;
    }
    if (this.type_ == Debug.ScriptBreakPointType.ScriptName) {
      return this.script_name_ == script.nameOrSourceURL();
    } else if (this.type_ == Debug.ScriptBreakPointType.ScriptRegExp) {
      return this.script_regexp_object_.test(script.nameOrSourceURL());
368
    } else {
369
      throw %make_error(kDebugger, "Unexpected breakpoint type " + this.type_);
370
    }
371
  }
372 373 374 375 376 377 378 379 380 381 382
};


// Set the script break point in a script.
ScriptBreakPoint.prototype.set = function (script) {
  var column = this.column();
  var line = this.line();
  // If the column is undefined the break is on the line. To help locate the
  // first piece of breakable code on the line try to find the column on the
  // line which contains some source.
  if (IS_UNDEFINED(column)) {
383
    var source_line = %ScriptSourceLine(script, line || script.line_offset);
384 385 386

    // Allocate array for caching the columns where the actual source starts.
    if (!script.sourceColumnStart_) {
387
      script.sourceColumnStart_ = new GlobalArray(%ScriptLineCount(script));
388
    }
389

390 391 392 393 394 395 396 397 398
    // Fill cache if needed and get column where the actual source starts.
    if (IS_UNDEFINED(script.sourceColumnStart_[line])) {
      script.sourceColumnStart_[line] =
          source_line.match(sourceLineBeginningSkip)[0].length;
    }
    column = script.sourceColumnStart_[line];
  }

  // Convert the line and column into an absolute position within the script.
399
  var position = Debug.findScriptSourcePosition(script, this.line(), column);
400

401 402
  // If the position is not found in the script (the script might be shorter
  // than it used to be) just ignore it.
403
  if (IS_NULL(position)) return;
404

405
  // Create a break point object and set the break point.
406
  var break_point = MakeBreakPoint(position, this);
407 408 409
  var actual_position = %SetScriptBreakPoint(script, position,
                                             this.position_alignment_,
                                             break_point);
410 411
  if (IS_UNDEFINED(actual_position)) {
    actual_position = position;
412
  }
413 414
  var actual_location = script.locationFromPosition(actual_position, true);
  break_point.actual_location = { line: actual_location.line,
415 416
                                  column: actual_location.column,
                                  script_id: script.id };
417
  this.break_points_.push(break_point);
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
  return break_point;
};


// Clear all the break points created from this script break point
ScriptBreakPoint.prototype.clear = function () {
  var remaining_break_points = [];
  for (var i = 0; i < break_points.length; i++) {
    if (break_points[i].script_break_point() &&
        break_points[i].script_break_point() === this) {
      %ClearBreakPoint(break_points[i]);
    } else {
      remaining_break_points.push(break_points[i]);
    }
  }
  break_points = remaining_break_points;
434
  this.break_points_ = [];
435 436 437 438 439 440 441
};


// Function called from runtime when a new script is compiled to set any script
// break points set in this script.
function UpdateScriptBreakPoints(script) {
  for (var i = 0; i < script_break_points.length; i++) {
442
    var break_point = script_break_points[i];
443 444
    if ((break_point.type() == Debug.ScriptBreakPointType.ScriptName ||
         break_point.type() == Debug.ScriptBreakPointType.ScriptRegExp) &&
445 446
        break_point.matchesScript(script)) {
      break_point.set(script);
447 448
    }
  }
449
}
450 451


452 453 454 455 456 457 458 459 460 461 462
function GetScriptBreakPoints(script) {
  var result = [];
  for (var i = 0; i < script_break_points.length; i++) {
    if (script_break_points[i].matchesScript(script)) {
      result.push(script_break_points[i]);
    }
  }
  return result;
}


463 464
Debug.setListener = function(listener, opt_data) {
  if (!IS_FUNCTION(listener) && !IS_UNDEFINED(listener) && !IS_NULL(listener)) {
465
    throw %make_type_error(kDebuggerType);
466 467
  }
  %SetDebugEventListener(listener, opt_data);
468 469 470 471 472 473
};


// Returns a Script object. If the parameter is a function the return value
// is the script in which the function is defined. If the parameter is a string
// the return value is the script for which the script name has that string
474 475
// value.  If it is a regexp and there is a unique script whose name matches
// we return that, otherwise undefined.
476 477 478
Debug.findScript = function(func_or_script_name) {
  if (IS_FUNCTION(func_or_script_name)) {
    return %FunctionGetScript(func_or_script_name);
479
  } else if (IS_REGEXP(func_or_script_name)) {
480
    var scripts = this.scripts();
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    var last_result = null;
    var result_count = 0;
    for (var i in scripts) {
      var script = scripts[i];
      if (func_or_script_name.test(script.name)) {
        last_result = script;
        result_count++;
      }
    }
    // Return the unique script matching the regexp.  If there are more
    // than one we don't return a value since there is no good way to
    // decide which one to return.  Returning a "random" one, say the
    // first, would introduce nondeterminism (or something close to it)
    // because the order is the heap iteration order.
    if (result_count == 1) {
      return last_result;
    } else {
498
      return UNDEFINED;
499
    }
500 501 502 503 504 505 506 507 508 509 510 511 512
  } else {
    return %GetScript(func_or_script_name);
  }
};

// Returns the script source. If the parameter is a function the return value
// is the script source for the script in which the function is defined. If the
// parameter is a string the return value is the script for which the script
// name has that string value.
Debug.scriptSource = function(func_or_script_name) {
  return this.findScript(func_or_script_name).source;
};

513

514
Debug.source = function(f) {
515
  if (!IS_FUNCTION(f)) throw %make_type_error(kDebuggerType);
516 517 518
  return %FunctionGetSourceCode(f);
};

519

520
Debug.sourcePosition = function(f) {
521
  if (!IS_FUNCTION(f)) throw %make_type_error(kDebuggerType);
522 523 524
  return %FunctionGetScriptSourcePosition(f);
};

525 526

Debug.findFunctionSourceLocation = function(func, opt_line, opt_column) {
527 528
  var script = %FunctionGetScript(func);
  var script_offset = %FunctionGetScriptSourcePosition(func);
529
  return %ScriptLocationFromLine(script, opt_line, opt_column, script_offset);
530
};
531 532 533 534 535


// Returns the character position in a script based on a line number and an
// optional position within that line.
Debug.findScriptSourcePosition = function(script, opt_line, opt_column) {
536
  var location = %ScriptLocationFromLine(script, opt_line, opt_column, 0);
537
  return location ? location.position : null;
538
};
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559


Debug.findBreakPoint = function(break_point_number, remove) {
  var break_point;
  for (var i = 0; i < break_points.length; i++) {
    if (break_points[i].number() == break_point_number) {
      break_point = break_points[i];
      // Remove the break point from the list if requested.
      if (remove) {
        break_points.splice(i, 1);
      }
      break;
    }
  }
  if (break_point) {
    return break_point;
  } else {
    return this.findScriptBreakPoint(break_point_number, remove);
  }
};

560 561 562 563 564 565 566 567 568 569 570 571
Debug.findBreakPointActualLocations = function(break_point_number) {
  for (var i = 0; i < script_break_points.length; i++) {
    if (script_break_points[i].number() == break_point_number) {
      return script_break_points[i].actual_locations();
    }
  }
  for (var i = 0; i < break_points.length; i++) {
    if (break_points[i].number() == break_point_number) {
      return [break_points[i].actual_location];
    }
  }
  return [];
572
};
573 574

Debug.setBreakPoint = function(func, opt_line, opt_column, opt_condition) {
575
  if (!IS_FUNCTION(func)) throw %make_type_error(kDebuggerType);
576 577
  // Break points in API functions are not supported.
  if (%FunctionIsAPIFunction(func)) {
578
    throw %make_error(kDebugger, 'Cannot set break point in native code.');
579
  }
580 581
  // Find source position.
  var source_position =
582
      this.findFunctionSourceLocation(func, opt_line, opt_column).position;
583 584
  // Find the script for the function.
  var script = %FunctionGetScript(func);
585 586
  // Break in builtin JavaScript code is not supported.
  if (script.type == Debug.ScriptType.Native) {
587
    throw %make_error(kDebugger, 'Cannot set break point in native code.');
588
  }
589 590
  // If the script for the function has a name convert this to a script break
  // point.
591
  if (script && script.id) {
592 593
    // Find line and column for the position in the script and set a script
    // break point from that.
594
    var location = script.locationFromPosition(source_position, false);
595 596 597
    return this.setScriptBreakPointById(script.id,
                                        location.line, location.column,
                                        opt_condition);
598 599
  } else {
    // Set a break point directly on the function.
600
    var break_point = MakeBreakPoint(source_position);
601 602 603 604
    var actual_position =
        %SetFunctionBreakPoint(func, source_position, break_point);
    var actual_location = script.locationFromPosition(actual_position, true);
    break_point.actual_location = { line: actual_location.line,
605 606
                                    column: actual_location.column,
                                    script_id: script.id };
607 608 609 610 611 612
    break_point.setCondition(opt_condition);
    return break_point.number();
  }
};


613
Debug.setBreakPointByScriptIdAndPosition = function(script_id, position,
614 615
                                                    condition, enabled,
                                                    opt_position_alignment)
616
{
617
  var break_point = MakeBreakPoint(position);
618
  break_point.setCondition(condition);
619
  if (!enabled) {
620
    break_point.disable();
621
  }
622 623 624 625 626 627
  var script = scriptById(script_id);
  if (script) {
    var position_alignment = IS_UNDEFINED(opt_position_alignment)
        ? Debug.BreakPositionAlignment.Statement : opt_position_alignment;
    break_point.actual_position = %SetScriptBreakPoint(script, position,
        position_alignment, break_point);
628 629 630 631 632
  }
  return break_point;
};


633 634
Debug.enableBreakPoint = function(break_point_number) {
  var break_point = this.findBreakPoint(break_point_number, false);
635 636 637 638
  // Only enable if the breakpoint hasn't been deleted:
  if (break_point) {
    break_point.enable();
  }
639 640 641 642 643
};


Debug.disableBreakPoint = function(break_point_number) {
  var break_point = this.findBreakPoint(break_point_number, false);
644 645 646 647
  // Only enable if the breakpoint hasn't been deleted:
  if (break_point) {
    break_point.disable();
  }
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
};


Debug.changeBreakPointCondition = function(break_point_number, condition) {
  var break_point = this.findBreakPoint(break_point_number, false);
  break_point.setCondition(condition);
};


Debug.clearBreakPoint = function(break_point_number) {
  var break_point = this.findBreakPoint(break_point_number, true);
  if (break_point) {
    return %ClearBreakPoint(break_point);
  } else {
    break_point = this.findScriptBreakPoint(break_point_number, true);
663
    if (!break_point) throw %make_error(kDebugger, 'Invalid breakpoint');
664 665 666 667 668 669
  }
};


Debug.clearAllBreakPoints = function() {
  for (var i = 0; i < break_points.length; i++) {
670
    var break_point = break_points[i];
671 672 673 674 675 676
    %ClearBreakPoint(break_point);
  }
  break_points = [];
};


677 678 679 680 681 682 683 684 685 686 687
Debug.disableAllBreakPoints = function() {
  // Disable all user defined breakpoints:
  for (var i = 1; i < next_break_point_number; i++) {
    Debug.disableBreakPoint(i);
  }
  // Disable all exception breakpoints:
  %ChangeBreakOnException(Debug.ExceptionBreak.Caught, false);
  %ChangeBreakOnException(Debug.ExceptionBreak.Uncaught, false);
};


688 689 690 691 692 693 694 695 696 697 698 699 700 701
Debug.findScriptBreakPoint = function(break_point_number, remove) {
  var script_break_point;
  for (var i = 0; i < script_break_points.length; i++) {
    if (script_break_points[i].number() == break_point_number) {
      script_break_point = script_break_points[i];
      // Remove the break point from the list if requested.
      if (remove) {
        script_break_point.clear();
        script_break_points.splice(i,1);
      }
      break;
    }
  }
  return script_break_point;
702
};
703 704


705
// Sets a breakpoint in a script identified through id or name at the
706
// specified source line and column within that line.
707
Debug.setScriptBreakPoint = function(type, script_id_or_name,
708
                                     opt_line, opt_column, opt_condition,
709
                                     opt_groupId, opt_position_alignment) {
710
  // Create script break point object.
711
  var script_break_point =
712
      new ScriptBreakPoint(type, script_id_or_name, opt_line, opt_column,
713
                           opt_groupId, opt_position_alignment);
714 715 716 717 718 719

  // Assign number to the new script break point and add it.
  script_break_point.number_ = next_break_point_number++;
  script_break_point.setCondition(opt_condition);
  script_break_points.push(script_break_point);

720
  // Run through all scripts to see if this script break point matches any
721 722 723 724 725 726 727 728 729
  // loaded scripts.
  var scripts = this.scripts();
  for (var i = 0; i < scripts.length; i++) {
    if (script_break_point.matchesScript(scripts[i])) {
      script_break_point.set(scripts[i]);
    }
  }

  return script_break_point.number();
730
};
731 732


733 734
Debug.setScriptBreakPointById = function(script_id,
                                         opt_line, opt_column,
735 736
                                         opt_condition, opt_groupId,
                                         opt_position_alignment) {
737 738
  return this.setScriptBreakPoint(Debug.ScriptBreakPointType.ScriptId,
                                  script_id, opt_line, opt_column,
739 740
                                  opt_condition, opt_groupId,
                                  opt_position_alignment);
741
};
742 743 744 745


Debug.setScriptBreakPointByName = function(script_name,
                                           opt_line, opt_column,
746
                                           opt_condition, opt_groupId) {
747 748
  return this.setScriptBreakPoint(Debug.ScriptBreakPointType.ScriptName,
                                  script_name, opt_line, opt_column,
749
                                  opt_condition, opt_groupId);
750
};
751 752


753 754 755 756 757 758
Debug.setScriptBreakPointByRegExp = function(script_regexp,
                                             opt_line, opt_column,
                                             opt_condition, opt_groupId) {
  return this.setScriptBreakPoint(Debug.ScriptBreakPointType.ScriptRegExp,
                                  script_regexp, opt_line, opt_column,
                                  opt_condition, opt_groupId);
759
};
760 761


762 763 764 765 766 767 768 769 770 771 772 773
Debug.enableScriptBreakPoint = function(break_point_number) {
  var script_break_point = this.findScriptBreakPoint(break_point_number, false);
  script_break_point.enable();
};


Debug.disableScriptBreakPoint = function(break_point_number) {
  var script_break_point = this.findScriptBreakPoint(break_point_number, false);
  script_break_point.disable();
};


774 775
Debug.changeScriptBreakPointCondition = function(
    break_point_number, condition) {
776 777 778 779 780 781 782
  var script_break_point = this.findScriptBreakPoint(break_point_number, false);
  script_break_point.setCondition(condition);
};


Debug.scriptBreakPoints = function() {
  return script_break_points;
783
};
784 785 786


Debug.clearStepping = function() {
787
  %ClearStepping();
788
};
789 790

Debug.setBreakOnException = function() {
791
  return %ChangeBreakOnException(Debug.ExceptionBreak.Caught, true);
792 793 794
};

Debug.clearBreakOnException = function() {
795 796 797 798 799
  return %ChangeBreakOnException(Debug.ExceptionBreak.Caught, false);
};

Debug.isBreakOnException = function() {
  return !!%IsBreakOnException(Debug.ExceptionBreak.Caught);
800 801 802 803 804 805 806 807 808 809
};

Debug.setBreakOnUncaughtException = function() {
  return %ChangeBreakOnException(Debug.ExceptionBreak.Uncaught, true);
};

Debug.clearBreakOnUncaughtException = function() {
  return %ChangeBreakOnException(Debug.ExceptionBreak.Uncaught, false);
};

810 811 812 813
Debug.isBreakOnUncaughtException = function() {
  return !!%IsBreakOnException(Debug.ExceptionBreak.Uncaught);
};

814
Debug.showBreakPoints = function(f, full, opt_position_alignment) {
815
  if (!IS_FUNCTION(f)) throw %make_error(kDebuggerType);
816
  var source = full ? this.scriptSource(f) : this.source(f);
817 818 819 820
  var offset = full ? 0 : this.sourcePosition(f);
  var position_alignment = IS_UNDEFINED(opt_position_alignment)
      ? Debug.BreakPositionAlignment.Statement : opt_position_alignment;
  var locations = %GetBreakLocations(f, position_alignment);
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
  if (!locations) return source;
  locations.sort(function(x, y) { return x - y; });
  var result = "";
  var prev_pos = 0;
  var pos;
  for (var i = 0; i < locations.length; i++) {
    pos = locations[i] - offset;
    result += source.slice(prev_pos, pos);
    result += "[B" + i + "]";
    prev_pos = pos;
  }
  pos = source.length;
  result += source.substring(prev_pos, pos);
  return result;
};


// Get all the scripts currently loaded. Locating all the scripts is based on
// scanning the heap.
Debug.scripts = function() {
  // Collect all scripts in the heap.
842
  return %DebugGetLoadedScripts();
843 844 845
};


846 847 848 849 850 851 852 853 854 855 856
// Get a specific script currently loaded. This is based on scanning the heap.
// TODO(clemensh): Create a runtime function for this.
function scriptById(scriptId) {
  var scripts = Debug.scripts();
  for (var script of scripts) {
    if (script.id == scriptId) return script;
  }
  return UNDEFINED;
};


857 858 859 860
Debug.debuggerFlags = function() {
  return debugger_flags;
};

861 862 863 864 865 866 867 868 869 870
Debug.getWasmFunctionOffsetTable = function(scriptId) {
  var script = scriptById(scriptId);
  return script ? %GetWasmFunctionOffsetTable(script) : UNDEFINED;
}

Debug.disassembleWasmFunction = function(scriptId) {
  var script = scriptById(scriptId);
  return script ? %DisassembleWasmFunction(script) : UNDEFINED;
}

871
Debug.MakeMirror = MakeMirror;
872 873 874

function MakeExecutionState(break_id) {
  return new ExecutionState(break_id);
875
}
876 877 878 879

function ExecutionState(break_id) {
  this.break_id = break_id;
  this.selected_frame = 0;
880
}
881

882 883 884 885 886 887 888
ExecutionState.prototype.prepareStep = function(action) {
  if (action === Debug.StepAction.StepIn ||
      action === Debug.StepAction.StepOut ||
      action === Debug.StepAction.StepNext ||
      action === Debug.StepAction.StepFrame) {
    return %PrepareStep(this.break_id, action);
  }
889
  throw %make_type_error(kDebuggerType);
890
};
891

892 893 894
ExecutionState.prototype.evaluateGlobal = function(source, disable_break,
    opt_additional_context) {
  return MakeMirror(%DebugEvaluateGlobal(this.break_id, source,
895
                                         TO_BOOLEAN(disable_break),
896
                                         opt_additional_context));
897 898
};

899
ExecutionState.prototype.frameCount = function() {
900 901 902
  return %GetFrameCount(this.break_id);
};

903
ExecutionState.prototype.frame = function(opt_index) {
904 905
  // If no index supplied return the selected frame.
  if (opt_index == null) opt_index = this.selected_frame;
906
  if (opt_index < 0 || opt_index >= this.frameCount()) {
907
    throw %make_type_error(kDebuggerFrame);
908
  }
909 910 911 912
  return new FrameMirror(this.break_id, opt_index);
};

ExecutionState.prototype.setSelectedFrame = function(index) {
913
  var i = TO_NUMBER(index);
914
  if (i < 0 || i >= this.frameCount()) {
915
    throw %make_type_error(kDebuggerFrame);
916
  }
917 918 919
  this.selected_frame = i;
};

920
ExecutionState.prototype.selectedFrame = function() {
921 922 923
  return this.selected_frame;
};

924 925
ExecutionState.prototype.debugCommandProcessor = function(opt_is_running) {
  return new DebugCommandProcessor(this, opt_is_running);
926 927 928
};


929 930
function MakeBreakEvent(break_id, break_points_hit) {
  return new BreakEvent(break_id, break_points_hit);
931
}
932 933


934 935
function BreakEvent(break_id, break_points_hit) {
  this.frame_ = new FrameMirror(break_id, 0);
936
  this.break_points_hit_ = break_points_hit;
937
}
938 939


940 941 942 943 944
BreakEvent.prototype.eventType = function() {
  return Debug.DebugEvent.Break;
};


945
BreakEvent.prototype.func = function() {
946
  return this.frame_.func();
947 948 949 950
};


BreakEvent.prototype.sourceLine = function() {
951
  return this.frame_.sourceLine();
952 953 954 955
};


BreakEvent.prototype.sourceColumn = function() {
956
  return this.frame_.sourceColumn();
957 958 959 960
};


BreakEvent.prototype.sourceLineText = function() {
961
  return this.frame_.sourceLineText();
962 963 964 965 966 967 968 969 970 971 972 973
};


BreakEvent.prototype.breakPointsHit = function() {
  return this.break_points_hit_;
};


BreakEvent.prototype.toJSONProtocol = function() {
  var o = { seq: next_response_seq++,
            type: "event",
            event: "break",
974
            body: { invocationText: this.frame_.invocationText() }
975
          };
976 977 978 979 980 981 982

  // Add script related information to the event if available.
  var script = this.func().script();
  if (script) {
    o.body.sourceLine = this.sourceLine(),
    o.body.sourceColumn = this.sourceColumn(),
    o.body.sourceLineText = this.sourceLineText(),
983
    o.body.script = MakeScriptObject_(script, false);
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
  }

  // Add an Array of break points hit if any.
  if (this.breakPointsHit()) {
    o.body.breakpoints = [];
    for (var i = 0; i < this.breakPointsHit().length; i++) {
      // Find the break point number. For break points originating from a
      // script break point supply the script break point number.
      var breakpoint = this.breakPointsHit()[i];
      var script_break_point = breakpoint.script_break_point();
      var number;
      if (script_break_point) {
        number = script_break_point.number();
      } else {
        number = breakpoint.number();
      }
      o.body.breakpoints.push(number);
    }
  }
1003
  return JSONStringify(ObjectToProtocolObject_(o));
1004 1005 1006
};


1007 1008
function MakeExceptionEvent(break_id, exception, uncaught, promise) {
  return new ExceptionEvent(break_id, exception, uncaught, promise);
1009
}
1010

1011

1012 1013
function ExceptionEvent(break_id, exception, uncaught, promise) {
  this.exec_state_ = new ExecutionState(break_id);
1014 1015
  this.exception_ = exception;
  this.uncaught_ = uncaught;
1016
  this.promise_ = promise;
1017
}
1018

1019 1020 1021 1022 1023 1024

ExceptionEvent.prototype.eventType = function() {
  return Debug.DebugEvent.Exception;
};


1025 1026
ExceptionEvent.prototype.exception = function() {
  return this.exception_;
1027
};
1028 1029


1030 1031
ExceptionEvent.prototype.uncaught = function() {
  return this.uncaught_;
1032
};
1033

1034

1035 1036 1037 1038 1039
ExceptionEvent.prototype.promise = function() {
  return this.promise_;
};


1040
ExceptionEvent.prototype.func = function() {
1041
  return this.exec_state_.frame(0).func();
1042 1043 1044 1045
};


ExceptionEvent.prototype.sourceLine = function() {
1046
  return this.exec_state_.frame(0).sourceLine();
1047 1048 1049 1050
};


ExceptionEvent.prototype.sourceColumn = function() {
1051
  return this.exec_state_.frame(0).sourceColumn();
1052 1053 1054 1055
};


ExceptionEvent.prototype.sourceLineText = function() {
1056
  return this.exec_state_.frame(0).sourceLineText();
1057 1058 1059 1060
};


ExceptionEvent.prototype.toJSONProtocol = function() {
1061 1062 1063 1064
  var o = new ProtocolMessage();
  o.event = "exception";
  o.body = { uncaught: this.uncaught_,
             exception: MakeMirror(this.exception_)
1065
           };
1066

1067 1068 1069 1070 1071 1072 1073 1074 1075
  // Exceptions might happen whithout any JavaScript frames.
  if (this.exec_state_.frameCount() > 0) {
    o.body.sourceLine = this.sourceLine();
    o.body.sourceColumn = this.sourceColumn();
    o.body.sourceLineText = this.sourceLineText();

    // Add script information to the event if available.
    var script = this.func().script();
    if (script) {
1076
      o.body.script = MakeScriptObject_(script, false);
1077 1078 1079
    }
  } else {
    o.body.sourceLine = -1;
1080 1081
  }

1082
  return o.toJSONProtocol();
1083 1084
};

1085

1086 1087
function MakeCompileEvent(script, type) {
  return new CompileEvent(script, type);
1088
}
1089

1090

1091
function CompileEvent(script, type) {
1092
  this.script_ = MakeMirror(script);
1093
  this.type_ = type;
1094
}
1095 1096


1097
CompileEvent.prototype.eventType = function() {
1098
  return this.type_;
1099 1100 1101
};


1102 1103 1104 1105 1106
CompileEvent.prototype.script = function() {
  return this.script_;
};


1107 1108
CompileEvent.prototype.toJSONProtocol = function() {
  var o = new ProtocolMessage();
1109
  o.running = true;
1110 1111 1112
  switch (this.type_) {
    case Debug.DebugEvent.BeforeCompile:
      o.event = "beforeCompile";
1113
      break;
1114 1115
    case Debug.DebugEvent.AfterCompile:
      o.event = "afterCompile";
1116
      break;
1117 1118
    case Debug.DebugEvent.CompileError:
      o.event = "compileError";
1119
      break;
1120 1121
  }
  o.body = {};
1122
  o.body.script = this.script_;
1123 1124

  return o.toJSONProtocol();
1125
};
1126 1127


1128 1129 1130 1131 1132 1133 1134
function MakeScriptObject_(script, include_source) {
  var o = { id: script.id(),
            name: script.name(),
            lineOffset: script.lineOffset(),
            columnOffset: script.columnOffset(),
            lineCount: script.lineCount(),
          };
1135 1136 1137
  if (!IS_UNDEFINED(script.data())) {
    o.data = script.data();
  }
1138 1139 1140 1141
  if (include_source) {
    o.source = script.source();
  }
  return o;
1142
}
1143 1144


1145 1146
function MakeAsyncTaskEvent(type, id, name) {
  return new AsyncTaskEvent(type, id, name);
1147 1148 1149
}


1150 1151 1152 1153
function AsyncTaskEvent(type, id, name) {
  this.type_ = type;
  this.id_ = id;
  this.name_ = name;
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
}


AsyncTaskEvent.prototype.type = function() {
  return this.type_;
}


AsyncTaskEvent.prototype.name = function() {
  return this.name_;
}


AsyncTaskEvent.prototype.id = function() {
  return this.id_;
}


1172
function DebugCommandProcessor(exec_state, opt_is_running) {
1173
  this.exec_state_ = exec_state;
1174
  this.running_ = opt_is_running || false;
1175
}
1176 1177


1178 1179
DebugCommandProcessor.prototype.processDebugRequest = function (request) {
  return this.processDebugJSONRequest(request);
1180
};
1181 1182


1183 1184
function ProtocolMessage(request) {
  // Update sequence number.
1185
  this.seq = next_response_seq++;
1186

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
  if (request) {
    // If message is based on a request this is a response. Fill the initial
    // response from the request.
    this.type = 'response';
    this.request_seq = request.seq;
    this.command = request.command;
  } else {
    // If message is not based on a request it is a dabugger generated event.
    this.type = 'event';
  }
1197
  this.success = true;
1198
  // Handler may set this field to control debugger state.
1199
  this.running = UNDEFINED;
1200
}
1201 1202


1203 1204 1205 1206 1207
ProtocolMessage.prototype.setOption = function(name, value) {
  if (!this.options_) {
    this.options_ = {};
  }
  this.options_[name] = value;
1208
};
1209 1210


1211
ProtocolMessage.prototype.failed = function(message, opt_details) {
1212 1213
  this.success = false;
  this.message = message;
1214 1215 1216
  if (IS_OBJECT(opt_details)) {
    this.error_details = opt_details;
  }
1217
};
1218 1219


1220
ProtocolMessage.prototype.toJSONProtocol = function() {
1221
  // Encode the protocol header.
1222 1223
  var json = {};
  json.seq= this.seq;
1224
  if (this.request_seq) {
1225
    json.request_seq = this.request_seq;
1226
  }
1227
  json.type = this.type;
1228
  if (this.event) {
1229
    json.event = this.event;
1230
  }
1231
  if (this.command) {
1232
    json.command = this.command;
1233 1234
  }
  if (this.success) {
1235
    json.success = this.success;
1236
  } else {
1237
    json.success = false;
1238 1239 1240
  }
  if (this.body) {
    // Encode the body part.
1241
    var bodyJson;
1242
    var serializer = MakeMirrorSerializer(true, this.options_);
1243
    if (this.body instanceof Mirror) {
1244
      bodyJson = serializer.serializeValue(this.body);
1245
    } else if (this.body instanceof GlobalArray) {
1246
      bodyJson = [];
1247
      for (var i = 0; i < this.body.length; i++) {
1248
        if (this.body[i] instanceof Mirror) {
1249
          bodyJson.push(serializer.serializeValue(this.body[i]));
1250
        } else {
1251
          bodyJson.push(ObjectToProtocolObject_(this.body[i], serializer));
1252 1253 1254
        }
      }
    } else {
1255
      bodyJson = ObjectToProtocolObject_(this.body, serializer);
1256
    }
1257 1258
    json.body = bodyJson;
    json.refs = serializer.serializeReferencedObjects();
1259 1260
  }
  if (this.message) {
1261
    json.message = this.message;
1262
  }
1263 1264 1265
  if (this.error_details) {
    json.error_details = this.error_details;
  }
1266
  json.running = this.running;
1267
  return JSONStringify(json);
1268
};
1269 1270 1271


DebugCommandProcessor.prototype.createResponse = function(request) {
1272
  return new ProtocolMessage(request);
1273 1274 1275
};


1276 1277
DebugCommandProcessor.prototype.processDebugJSONRequest = function(
    json_request) {
1278 1279 1280 1281 1282
  var request;  // Current request.
  var response;  // Generated response.
  try {
    try {
      // Convert the JSON string to an object.
1283
      request = JSONParse(json_request);
1284 1285 1286 1287 1288

      // Create an initial response.
      response = this.createResponse(request);

      if (!request.type) {
1289
        throw %make_error(kDebugger, 'Type not specified');
1290 1291 1292
      }

      if (request.type != 'request') {
1293
        throw %make_error(kDebugger,
1294
                        "Illegal type '" + request.type + "' in request");
1295 1296 1297
      }

      if (!request.command) {
1298
        throw %make_error(kDebugger, 'Command not specified');
1299 1300
      }

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
      if (request.arguments) {
        var args = request.arguments;
        // TODO(yurys): remove request.arguments.compactFormat check once
        // ChromeDevTools are switched to 'inlineRefs'
        if (args.inlineRefs || args.compactFormat) {
          response.setOption('inlineRefs', true);
        }
        if (!IS_UNDEFINED(args.maxStringLength)) {
          response.setOption('maxStringLength', args.maxStringLength);
        }
1311 1312
      }

1313 1314 1315
      var key = request.command.toLowerCase();
      var handler = DebugCommandProcessor.prototype.dispatch_[key];
      if (IS_FUNCTION(handler)) {
1316
        %_Call(handler, this, request, response);
1317
      } else {
1318
        throw %make_error(kDebugger,
1319
                        'Unknown command "' + request.command + '" in request');
1320 1321 1322 1323 1324 1325 1326
      }
    } catch (e) {
      // If there is no response object created one (without command).
      if (!response) {
        response = this.createResponse();
      }
      response.success = false;
1327
      response.message = TO_STRING(e);
1328 1329 1330 1331
    }

    // Return the response as a JSON encoded string.
    try {
1332 1333 1334 1335
      if (!IS_UNDEFINED(response.running)) {
        // Response controls running state.
        this.running_ = response.running;
      }
1336
      response.running = this.running_;
1337 1338 1339 1340 1341 1342 1343
      return response.toJSONProtocol();
    } catch (e) {
      // Failed to generate response - return generic error.
      return '{"seq":' + response.seq + ',' +
              '"request_seq":' + request.seq + ',' +
              '"type":"response",' +
              '"success":false,' +
1344
              '"message":"Internal error: ' + TO_STRING(e) + '"}';
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
    }
  } catch (e) {
    // Failed in one of the catch blocks above - most generic error.
    return '{"seq":0,"type":"response","success":false,"message":"Internal error"}';
  }
};


DebugCommandProcessor.prototype.continueRequest_ = function(request, response) {
  // Check for arguments for continue.
  if (request.arguments) {
    var action = Debug.StepAction.StepIn;

    // Pull out arguments.
    var stepaction = request.arguments.stepaction;

    // Get the stepaction argument.
    if (stepaction) {
      if (stepaction == 'in') {
        action = Debug.StepAction.StepIn;
      } else if (stepaction == 'next') {
        action = Debug.StepAction.StepNext;
      } else if (stepaction == 'out') {
        action = Debug.StepAction.StepOut;
      } else {
1370
        throw %make_error(kDebugger,
1371
                        'Invalid stepaction argument "' + stepaction + '".');
1372 1373 1374
      }
    }

1375
    // Set up the VM for stepping.
1376
    this.exec_state_.prepareStep(action);
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
  }

  // VM should be running after executing this request.
  response.running = true;
};


DebugCommandProcessor.prototype.breakRequest_ = function(request, response) {
  // Ignore as break command does not do anything when broken.
};


DebugCommandProcessor.prototype.setBreakPointRequest_ =
    function(request, response) {
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
  var type = request.arguments.type;
  var target = request.arguments.target;
  var line = request.arguments.line;
  var column = request.arguments.column;
  var enabled = IS_UNDEFINED(request.arguments.enabled) ?
      true : request.arguments.enabled;
  var condition = request.arguments.condition;
1405
  var groupId = request.arguments.groupId;
1406 1407

  // Check for legal arguments.
1408
  if (!type || IS_UNDEFINED(target)) {
1409 1410 1411
    response.failed('Missing argument "type" or "target"');
    return;
  }
1412

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  // Either function or script break point.
  var break_point_number;
  if (type == 'function') {
    // Handle function break point.
    if (!IS_STRING(target)) {
      response.failed('Argument "target" is not a string value');
      return;
    }
    var f;
    try {
      // Find the function through a global evaluate.
1424
      f = this.exec_state_.evaluateGlobal(target).value();
1425
    } catch (e) {
1426
      response.failed('Error: "' + TO_STRING(e) +
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
                      '" evaluating "' + target + '"');
      return;
    }
    if (!IS_FUNCTION(f)) {
      response.failed('"' + target + '" does not evaluate to a function');
      return;
    }

    // Set function break point.
    break_point_number = Debug.setBreakPoint(f, line, column, condition);
1437 1438
  } else if (type == 'handle') {
    // Find the object pointed by the specified handle.
1439
    var handle = ParseInt(target, 10);
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    var mirror = LookupMirror(handle);
    if (!mirror) {
      return response.failed('Object #' + handle + '# not found');
    }
    if (!mirror.isFunction()) {
      return response.failed('Object #' + handle + '# is not a function');
    }

    // Set function break point.
    break_point_number = Debug.setBreakPoint(mirror.value(),
                                             line, column, condition);
1451
  } else if (type == 'script') {
1452
    // set script break point.
1453
    break_point_number =
1454 1455
        Debug.setScriptBreakPointByName(target, line, column, condition,
                                        groupId);
1456
  } else if (type == 'scriptId') {
1457
    break_point_number =
1458
        Debug.setScriptBreakPointById(target, line, column, condition, groupId);
1459
  } else if (type == 'scriptRegExp') {
1460 1461 1462 1463 1464 1465
    break_point_number =
        Debug.setScriptBreakPointByRegExp(target, line, column, condition,
                                          groupId);
  } else {
    response.failed('Illegal type "' + type + '"');
    return;
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
  }

  // Set additional break point properties.
  var break_point = Debug.findBreakPoint(break_point_number);
  if (!enabled) {
    Debug.disableBreakPoint(break_point_number);
  }

  // Add the break point number to the response.
  response.body = { type: type,
1476
                    breakpoint: break_point_number };
1477 1478 1479

  // Add break point information to the response.
  if (break_point instanceof ScriptBreakPoint) {
1480 1481 1482
    if (break_point.type() == Debug.ScriptBreakPointType.ScriptId) {
      response.body.type = 'scriptId';
      response.body.script_id = break_point.script_id();
1483
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptName) {
1484 1485
      response.body.type = 'scriptName';
      response.body.script_name = break_point.script_name();
1486 1487 1488 1489
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptRegExp) {
      response.body.type = 'scriptRegExp';
      response.body.script_regexp = break_point.script_regexp_object().source;
    } else {
1490
      throw %make_error(kDebugger,
1491
                      "Unexpected breakpoint type: " + break_point.type());
1492
    }
1493 1494
    response.body.line = break_point.line();
    response.body.column = break_point.column();
1495
    response.body.actual_locations = break_point.actual_locations();
1496 1497
  } else {
    response.body.type = 'function';
1498
    response.body.actual_locations = [break_point.actual_location];
1499 1500 1501 1502
  }
};


1503 1504
DebugCommandProcessor.prototype.changeBreakPointRequest_ = function(
    request, response) {
1505 1506 1507 1508 1509 1510 1511
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
1512
  var break_point = TO_NUMBER(request.arguments.breakpoint);
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  var enabled = request.arguments.enabled;
  var condition = request.arguments.condition;

  // Check for legal arguments.
  if (!break_point) {
    response.failed('Missing argument "breakpoint"');
    return;
  }

  // Change enabled state if supplied.
  if (!IS_UNDEFINED(enabled)) {
    if (enabled) {
      Debug.enableBreakPoint(break_point);
    } else {
      Debug.disableBreakPoint(break_point);
    }
  }

  // Change condition if supplied
  if (!IS_UNDEFINED(condition)) {
    Debug.changeBreakPointCondition(break_point, condition);
  }
1535
};
1536 1537


1538 1539
DebugCommandProcessor.prototype.clearBreakPointGroupRequest_ = function(
    request, response) {
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
  var group_id = request.arguments.groupId;

  // Check for legal arguments.
  if (!group_id) {
    response.failed('Missing argument "groupId"');
    return;
  }
1554

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
  var cleared_break_points = [];
  var new_script_break_points = [];
  for (var i = 0; i < script_break_points.length; i++) {
    var next_break_point = script_break_points[i];
    if (next_break_point.groupId() == group_id) {
      cleared_break_points.push(next_break_point.number());
      next_break_point.clear();
    } else {
      new_script_break_points.push(next_break_point);
    }
  }
  script_break_points = new_script_break_points;

  // Add the cleared break point numbers to the response.
  response.body = { breakpoints: cleared_break_points };
1570
};
1571 1572


1573 1574
DebugCommandProcessor.prototype.clearBreakPointRequest_ = function(
    request, response) {
1575 1576 1577 1578 1579 1580 1581
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
1582
  var break_point = TO_NUMBER(request.arguments.breakpoint);
1583 1584 1585 1586 1587 1588 1589 1590 1591

  // Check for legal arguments.
  if (!break_point) {
    response.failed('Missing argument "breakpoint"');
    return;
  }

  // Clear break point.
  Debug.clearBreakPoint(break_point);
1592 1593

  // Add the cleared break point number to the response.
1594 1595
  response.body = { breakpoint: break_point };
};
1596

1597

1598 1599
DebugCommandProcessor.prototype.listBreakpointsRequest_ = function(
    request, response) {
1600 1601
  var array = [];
  for (var i = 0; i < script_break_points.length; i++) {
peter.rybin@gmail.com's avatar
peter.rybin@gmail.com committed
1602 1603 1604 1605 1606 1607 1608 1609 1610
    var break_point = script_break_points[i];

    var description = {
      number: break_point.number(),
      line: break_point.line(),
      column: break_point.column(),
      groupId: break_point.groupId(),
      active: break_point.active(),
      condition: break_point.condition(),
1611
      actual_locations: break_point.actual_locations()
1612
    };
1613

1614 1615
    if (break_point.type() == Debug.ScriptBreakPointType.ScriptId) {
      description.type = 'scriptId';
peter.rybin@gmail.com's avatar
peter.rybin@gmail.com committed
1616
      description.script_id = break_point.script_id();
1617
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptName) {
1618 1619
      description.type = 'scriptName';
      description.script_name = break_point.script_name();
1620 1621 1622 1623
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptRegExp) {
      description.type = 'scriptRegExp';
      description.script_regexp = break_point.script_regexp_object().source;
    } else {
1624
      throw %make_error(kDebugger,
1625
                      "Unexpected breakpoint type: " + break_point.type());
1626
    }
peter.rybin@gmail.com's avatar
peter.rybin@gmail.com committed
1627
    array.push(description);
1628
  }
1629

1630 1631 1632 1633
  response.body = {
    breakpoints: array,
    breakOnExceptions: Debug.isBreakOnException(),
    breakOnUncaughtExceptions: Debug.isBreakOnUncaughtException()
1634 1635
  };
};
1636 1637 1638 1639 1640 1641


DebugCommandProcessor.prototype.disconnectRequest_ =
    function(request, response) {
  Debug.disableAllBreakPoints();
  this.continueRequest_(request, response);
1642
};
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665


DebugCommandProcessor.prototype.setExceptionBreakRequest_ =
    function(request, response) {
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out and check the 'type' argument:
  var type = request.arguments.type;
  if (!type) {
    response.failed('Missing argument "type"');
    return;
  }

  // Initialize the default value of enable:
  var enabled;
  if (type == 'all') {
    enabled = !Debug.isBreakOnException();
  } else if (type == 'uncaught') {
    enabled = !Debug.isBreakOnUncaughtException();
1666
  }
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686

  // Pull out and check the 'enabled' argument if present:
  if (!IS_UNDEFINED(request.arguments.enabled)) {
    enabled = request.arguments.enabled;
    if ((enabled != true) && (enabled != false)) {
      response.failed('Illegal value for "enabled":"' + enabled + '"');
    }
  }

  // Now set the exception break state:
  if (type == 'all') {
    %ChangeBreakOnException(Debug.ExceptionBreak.Caught, enabled);
  } else if (type == 'uncaught') {
    %ChangeBreakOnException(Debug.ExceptionBreak.Uncaught, enabled);
  } else {
    response.failed('Unknown "type":"' + type + '"');
  }

  // Add the cleared break point number to the response.
  response.body = { 'type': type, 'enabled': enabled };
1687
};
1688

1689

1690 1691
DebugCommandProcessor.prototype.backtraceRequest_ = function(
    request, response) {
1692
  // Get the number of frames.
1693
  var total_frames = this.exec_state_.frameCount();
1694

1695 1696 1697 1698
  // Create simple response if there are no frames.
  if (total_frames == 0) {
    response.body = {
      totalFrames: total_frames
1699
    };
1700 1701 1702
    return;
  }

1703
  // Default frame range to include in backtrace.
1704
  var from_index = 0;
1705 1706 1707 1708
  var to_index = kDefaultBacktraceLength;

  // Get the range from the arguments.
  if (request.arguments) {
1709 1710 1711 1712 1713 1714 1715 1716
    if (request.arguments.fromFrame) {
      from_index = request.arguments.fromFrame;
    }
    if (request.arguments.toFrame) {
      to_index = request.arguments.toFrame;
    }
    if (request.arguments.bottom) {
      var tmp_index = total_frames - from_index;
1717
      from_index = total_frames - to_index;
1718
      to_index = tmp_index;
1719
    }
1720
    if (from_index < 0 || to_index < 0) {
1721 1722 1723 1724 1725
      return response.failed('Invalid frame number');
    }
  }

  // Adjust the index.
1726
  to_index = MathMin(total_frames, to_index);
1727 1728 1729 1730 1731 1732 1733 1734 1735

  if (to_index <= from_index) {
    var error = 'Invalid frame range';
    return response.failed(error);
  }

  // Create the response body.
  var frames = [];
  for (var i = from_index; i < to_index; i++) {
1736
    frames.push(this.exec_state_.frame(i));
1737 1738 1739 1740 1741 1742
  }
  response.body = {
    fromFrame: from_index,
    toFrame: to_index,
    totalFrames: total_frames,
    frames: frames
1743
  };
1744 1745 1746 1747
};


DebugCommandProcessor.prototype.frameRequest_ = function(request, response) {
1748 1749 1750 1751 1752
  // No frames no source.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No frames');
  }

1753
  // With no arguments just keep the selected frame.
1754
  if (request.arguments) {
1755
    var index = request.arguments.number;
1756 1757 1758
    if (index < 0 || this.exec_state_.frameCount() <= index) {
      return response.failed('Invalid frame number');
    }
1759

1760 1761
    this.exec_state_.setSelectedFrame(request.arguments.number);
  }
1762
  response.body = this.exec_state_.frame();
1763 1764 1765
};


1766 1767
DebugCommandProcessor.prototype.resolveFrameFromScopeDescription_ =
    function(scope_description) {
1768 1769
  // Get the frame for which the scope or scopes are requested.
  // With no frameNumber argument use the currently selected frame.
1770
  if (scope_description && !IS_UNDEFINED(scope_description.frameNumber)) {
1771
    var frame_index = scope_description.frameNumber;
1772
    if (frame_index < 0 || this.exec_state_.frameCount() <= frame_index) {
1773
      throw %make_type_error(kDebuggerFrame);
1774 1775 1776 1777 1778
    }
    return this.exec_state_.frame(frame_index);
  } else {
    return this.exec_state_.frame();
  }
1779
};
1780 1781


1782 1783 1784
// Gets scope host object from request. It is either a function
// ('functionHandle' argument must be specified) or a stack frame
// ('frameNumber' may be specified and the current frame is taken by default).
1785 1786 1787 1788
DebugCommandProcessor.prototype.resolveScopeHolder_ =
    function(scope_description) {
  if (scope_description && "functionHandle" in scope_description) {
    if (!IS_NUMBER(scope_description.functionHandle)) {
1789
      throw %make_error(kDebugger, 'Function handle must be a number');
1790
    }
1791
    var function_mirror = LookupMirror(scope_description.functionHandle);
1792
    if (!function_mirror) {
1793
      throw %make_error(kDebugger, 'Failed to find function object by handle');
1794 1795
    }
    if (!function_mirror.isFunction()) {
1796
      throw %make_error(kDebugger,
1797
                      'Value of non-function type is found by handle');
1798 1799 1800 1801 1802
    }
    return function_mirror;
  } else {
    // No frames no scopes.
    if (this.exec_state_.frameCount() == 0) {
1803
      throw %make_error(kDebugger, 'No scopes');
1804 1805 1806
    }

    // Get the frame for which the scopes are requested.
1807
    var frame = this.resolveFrameFromScopeDescription_(scope_description);
1808
    return frame;
1809
  }
1810
}
1811

1812

1813
DebugCommandProcessor.prototype.scopesRequest_ = function(request, response) {
1814
  var scope_holder = this.resolveScopeHolder_(request.arguments);
1815 1816 1817

  // Fill all scopes for this frame or function.
  var total_scopes = scope_holder.scopeCount();
1818 1819
  var scopes = [];
  for (var i = 0; i < total_scopes; i++) {
1820
    scopes.push(scope_holder.scope(i));
1821 1822 1823 1824 1825 1826
  }
  response.body = {
    fromScope: 0,
    toScope: total_scopes,
    totalScopes: total_scopes,
    scopes: scopes
1827
  };
1828 1829 1830 1831
};


DebugCommandProcessor.prototype.scopeRequest_ = function(request, response) {
1832
  // Get the frame or function for which the scope is requested.
1833
  var scope_holder = this.resolveScopeHolder_(request.arguments);
1834 1835 1836 1837

  // With no scope argument just return top scope.
  var scope_index = 0;
  if (request.arguments && !IS_UNDEFINED(request.arguments.number)) {
1838
    scope_index = TO_NUMBER(request.arguments.number);
1839
    if (scope_index < 0 || scope_holder.scopeCount() <= scope_index) {
1840 1841 1842 1843
      return response.failed('Invalid scope number');
    }
  }

1844
  response.body = scope_holder.scope(scope_index);
1845 1846 1847
};


1848 1849 1850 1851 1852 1853 1854 1855
// Reads value from protocol description. Description may be in form of type
// (for singletons), raw value (primitive types supported in JSON),
// string value description plus type (for primitive values) or handle id.
// Returns raw value or throws exception.
DebugCommandProcessor.resolveValue_ = function(value_description) {
  if ("handle" in value_description) {
    var value_mirror = LookupMirror(value_description.handle);
    if (!value_mirror) {
1856
      throw %make_error(kDebugger, "Failed to resolve value by handle, ' #" +
1857
                                 value_description.handle + "# not found");
1858 1859 1860
    }
    return value_mirror.value();
  } else if ("stringDescription" in value_description) {
1861
    if (value_description.type == MirrorType.BOOLEAN_TYPE) {
1862
      return TO_BOOLEAN(value_description.stringDescription);
1863
    } else if (value_description.type == MirrorType.NUMBER_TYPE) {
1864
      return TO_NUMBER(value_description.stringDescription);
1865
    } if (value_description.type == MirrorType.STRING_TYPE) {
1866
      return TO_STRING(value_description.stringDescription);
1867
    } else {
1868
      throw %make_error(kDebugger, "Unknown type");
1869 1870 1871
    }
  } else if ("value" in value_description) {
    return value_description.value;
1872
  } else if (value_description.type == MirrorType.UNDEFINED_TYPE) {
1873
    return UNDEFINED;
1874
  } else if (value_description.type == MirrorType.NULL_TYPE) {
1875 1876
    return null;
  } else {
1877
    throw %make_error(kDebugger, "Failed to parse value description");
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
  }
};


DebugCommandProcessor.prototype.setVariableValueRequest_ =
    function(request, response) {
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  if (IS_UNDEFINED(request.arguments.name)) {
    response.failed('Missing variable name');
  }
  var variable_name = request.arguments.name;

  var scope_description = request.arguments.scope;

  // Get the frame or function for which the scope is requested.
  var scope_holder = this.resolveScopeHolder_(scope_description);

  if (IS_UNDEFINED(scope_description.number)) {
    response.failed('Missing scope number');
  }
1902
  var scope_index = TO_NUMBER(scope_description.number);
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918

  var scope = scope_holder.scope(scope_index);

  var new_value =
      DebugCommandProcessor.resolveValue_(request.arguments.newValue);

  scope.setVariableValue(variable_name, new_value);

  var new_value_mirror = MakeMirror(new_value);

  response.body = {
    newValue: new_value_mirror
  };
};


1919 1920 1921 1922 1923 1924 1925 1926 1927
DebugCommandProcessor.prototype.evaluateRequest_ = function(request, response) {
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }

  // Pull out arguments.
  var expression = request.arguments.expression;
  var frame = request.arguments.frame;
  var global = request.arguments.global;
1928
  var disable_break = request.arguments.disable_break;
1929
  var additional_context = request.arguments.additional_context;
1930 1931 1932 1933

  // The expression argument could be an integer so we convert it to a
  // string.
  try {
1934
    expression = TO_STRING(expression);
1935 1936 1937
  } catch(e) {
    return response.failed('Failed to convert expression argument to string');
  }
1938 1939 1940 1941 1942

  // Check for legal arguments.
  if (!IS_UNDEFINED(frame) && global) {
    return response.failed('Arguments "frame" and "global" are exclusive');
  }
1943

1944 1945 1946
  var additional_context_object;
  if (additional_context) {
    additional_context_object = {};
1947 1948
    for (var i = 0; i < additional_context.length; i++) {
      var mapping = additional_context[i];
1949 1950

      if (!IS_STRING(mapping.name)) {
1951
        return response.failed("Context element #" + i +
1952
            " doesn't contain name:string property");
1953
      }
1954 1955 1956

      var raw_value = DebugCommandProcessor.resolveValue_(mapping);
      additional_context_object[mapping.name] = raw_value;
1957 1958
    }
  }
1959 1960 1961

  // Global evaluate.
  if (global) {
1962
    // Evaluate in the native context.
1963
    response.body = this.exec_state_.evaluateGlobal(
1964
        expression, TO_BOOLEAN(disable_break), additional_context_object);
1965 1966 1967
    return;
  }

1968 1969 1970 1971 1972
  // Default value for disable_break is true.
  if (IS_UNDEFINED(disable_break)) {
    disable_break = true;
  }

1973 1974 1975 1976 1977
  // No frames no evaluate in frame.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No frames');
  }

1978 1979
  // Check whether a frame was specified.
  if (!IS_UNDEFINED(frame)) {
1980
    var frame_number = TO_NUMBER(frame);
1981
    if (frame_number < 0 || frame_number >= this.exec_state_.frameCount()) {
1982 1983 1984
      return response.failed('Invalid frame "' + frame + '"');
    }
    // Evaluate in the specified frame.
1985
    response.body = this.exec_state_.frame(frame_number).evaluate(
1986
        expression, TO_BOOLEAN(disable_break), additional_context_object);
1987 1988 1989
    return;
  } else {
    // Evaluate in the selected frame.
1990
    response.body = this.exec_state_.frame().evaluate(
1991
        expression, TO_BOOLEAN(disable_break), additional_context_object);
1992 1993 1994 1995 1996
    return;
  }
};


1997 1998 1999 2000 2001 2002
DebugCommandProcessor.prototype.lookupRequest_ = function(request, response) {
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }

  // Pull out arguments.
2003
  var handles = request.arguments.handles;
2004 2005

  // Check for legal arguments.
2006 2007
  if (IS_UNDEFINED(handles)) {
    return response.failed('Argument "handles" missing');
2008 2009
  }

2010 2011
  // Set 'includeSource' option for script lookup.
  if (!IS_UNDEFINED(request.arguments.includeSource)) {
2012
    var includeSource = TO_BOOLEAN(request.arguments.includeSource);
2013 2014
    response.setOption('includeSource', includeSource);
  }
2015

2016 2017 2018 2019 2020 2021 2022 2023 2024
  // Lookup handles.
  var mirrors = {};
  for (var i = 0; i < handles.length; i++) {
    var handle = handles[i];
    var mirror = LookupMirror(handle);
    if (!mirror) {
      return response.failed('Object #' + handle + '# not found');
    }
    mirrors[handle] = mirror;
2025
  }
2026
  response.body = mirrors;
2027 2028 2029
};


2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
DebugCommandProcessor.prototype.referencesRequest_ =
    function(request, response) {
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }

  // Pull out arguments.
  var type = request.arguments.type;
  var handle = request.arguments.handle;

  // Check for legal arguments.
  if (IS_UNDEFINED(type)) {
    return response.failed('Argument "type" missing');
  }
  if (IS_UNDEFINED(handle)) {
    return response.failed('Argument "handle" missing');
  }
  if (type != 'referencedBy' && type != 'constructedBy') {
    return response.failed('Invalid type "' + type + '"');
  }

  // Lookup handle and return objects with references the object.
  var mirror = LookupMirror(handle);
  if (mirror) {
    if (type == 'referencedBy') {
      response.body = mirror.referencedBy();
    } else {
      response.body = mirror.constructedBy();
    }
  } else {
    return response.failed('Object #' + handle + '# not found');
  }
};


2065
DebugCommandProcessor.prototype.sourceRequest_ = function(request, response) {
2066 2067 2068 2069 2070
  // No frames no source.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No source');
  }

2071 2072
  var from_line;
  var to_line;
2073
  var frame = this.exec_state_.frame();
2074 2075 2076 2077 2078 2079
  if (request.arguments) {
    // Pull out arguments.
    from_line = request.arguments.fromLine;
    to_line = request.arguments.toLine;

    if (!IS_UNDEFINED(request.arguments.frame)) {
2080
      var frame_number = TO_NUMBER(request.arguments.frame);
2081
      if (frame_number < 0 || frame_number >= this.exec_state_.frameCount()) {
2082 2083
        return response.failed('Invalid frame "' + frame + '"');
      }
2084
      frame = this.exec_state_.frame(frame_number);
2085 2086 2087 2088 2089 2090 2091 2092 2093
    }
  }

  // Get the script selected.
  var script = frame.func().script();
  if (!script) {
    return response.failed('No source');
  }

2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
  var raw_script = script.value();

  // Sanitize arguments and remove line offset.
  var line_offset = raw_script.line_offset;
  var line_count = %ScriptLineCount(raw_script);
  from_line = IS_UNDEFINED(from_line) ? 0 : from_line - line_offset;
  to_line = IS_UNDEFINED(to_line) ? line_count : to_line - line_offset;

  if (from_line < 0) from_line = 0;
  if (to_line > line_count) to_line = line_count;

  if (from_line >= line_count || to_line < 0 || from_line > to_line) {
2106 2107
    return response.failed('Invalid line interval');
  }
2108 2109 2110

  // Fill in the response.

2111
  response.body = {};
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
  response.body.fromLine = from_line + line_offset;
  response.body.toLine = to_line + line_offset;
  response.body.fromPosition = %ScriptLineStartPosition(raw_script, from_line);
  response.body.toPosition =
    (to_line == 0) ? 0 : %ScriptLineEndPosition(raw_script, to_line - 1);
  response.body.totalLines = %ScriptLineCount(raw_script);

  response.body.source = %_SubString(raw_script.source,
                                     response.body.fromPosition,
                                     response.body.toPosition);
2122 2123 2124 2125 2126
};


DebugCommandProcessor.prototype.scriptsRequest_ = function(request, response) {
  var types = ScriptTypeFlag(Debug.ScriptType.Normal);
2127
  var includeSource = false;
2128
  var idsToInclude = null;
2129 2130 2131
  if (request.arguments) {
    // Pull out arguments.
    if (!IS_UNDEFINED(request.arguments.types)) {
2132
      types = TO_NUMBER(request.arguments.types);
2133
      if (IsNaN(types) || types < 0) {
2134 2135
        return response.failed('Invalid types "' +
                               request.arguments.types + '"');
2136 2137
      }
    }
2138

2139
    if (!IS_UNDEFINED(request.arguments.includeSource)) {
2140
      includeSource = TO_BOOLEAN(request.arguments.includeSource);
2141
      response.setOption('includeSource', includeSource);
2142
    }
2143

2144 2145 2146 2147 2148 2149 2150
    if (IS_ARRAY(request.arguments.ids)) {
      idsToInclude = {};
      var ids = request.arguments.ids;
      for (var i = 0; i < ids.length; i++) {
        idsToInclude[ids[i]] = true;
      }
    }
2151 2152 2153 2154

    var filterStr = null;
    var filterNum = null;
    if (!IS_UNDEFINED(request.arguments.filter)) {
2155
      var num = TO_NUMBER(request.arguments.filter);
2156
      if (!IsNaN(num)) {
2157 2158 2159 2160
        filterNum = num;
      }
      filterStr = request.arguments.filter;
    }
2161 2162 2163
  }

  // Collect all scripts in the heap.
2164
  var scripts = Debug.scripts();
2165 2166 2167 2168

  response.body = [];

  for (var i = 0; i < scripts.length; i++) {
2169 2170 2171
    if (idsToInclude && !idsToInclude[scripts[i].id]) {
      continue;
    }
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
    if (filterStr || filterNum) {
      var script = scripts[i];
      var found = false;
      if (filterNum && !found) {
        if (script.id && script.id === filterNum) {
          found = true;
        }
      }
      if (filterStr && !found) {
        if (script.name && script.name.indexOf(filterStr) >= 0) {
          found = true;
        }
      }
      if (!found) continue;
    }
2187
    if (types & ScriptTypeFlag(scripts[i].type)) {
2188
      response.body.push(MakeMirror(scripts[i]));
2189 2190 2191 2192 2193
    }
  }
};


2194 2195 2196 2197 2198
DebugCommandProcessor.prototype.suspendRequest_ = function(request, response) {
  response.running = false;
};


2199
// TODO(5510): remove this.
2200 2201 2202
DebugCommandProcessor.prototype.versionRequest_ = function(request, response) {
  response.body = {
    V8Version: %GetV8Version()
2203
  };
2204 2205 2206
};


2207 2208
DebugCommandProcessor.prototype.changeLiveRequest_ = function(
    request, response) {
2209 2210 2211 2212
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }
  var script_id = request.arguments.script_id;
2213
  var preview_only = !!request.arguments.preview_only;
2214

2215
  var the_script = scriptById(script_id);
2216 2217 2218 2219
  if (!the_script) {
    response.failed('Script not found');
    return;
  }
2220

2221
  var change_log = new GlobalArray();
2222

2223 2224
  if (!IS_STRING(request.arguments.new_source)) {
    throw "new_source argument expected";
2225 2226
  }

2227
  var new_source = request.arguments.new_source;
2228

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
  var result_description;
  try {
    result_description = Debug.LiveEdit.SetScriptSource(the_script,
        new_source, preview_only, change_log);
  } catch (e) {
    if (e instanceof Debug.LiveEdit.Failure && "details" in e) {
      response.failed(e.message, e.details);
      return;
    }
    throw e;
  }
2240
  response.body = {change_log: change_log, result: result_description};
2241

2242 2243 2244
  if (!preview_only && !this.running_ && result_description.stack_modified) {
    response.body.stepin_recommended = true;
  }
2245 2246 2247
};


2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
DebugCommandProcessor.prototype.restartFrameRequest_ = function(
    request, response) {
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }
  var frame = request.arguments.frame;

  // No frames to evaluate in frame.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No frames');
  }

  var frame_mirror;
  // Check whether a frame was specified.
  if (!IS_UNDEFINED(frame)) {
2263
    var frame_number = TO_NUMBER(frame);
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
    if (frame_number < 0 || frame_number >= this.exec_state_.frameCount()) {
      return response.failed('Invalid frame "' + frame + '"');
    }
    // Restart specified frame.
    frame_mirror = this.exec_state_.frame(frame_number);
  } else {
    // Restart selected frame.
    frame_mirror = this.exec_state_.frame();
  }

2274
  var result_description = frame_mirror.restart();
2275 2276 2277 2278
  response.body = {result: result_description};
};


2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
DebugCommandProcessor.prototype.debuggerFlagsRequest_ = function(request,
                                                                 response) {
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
  var flags = request.arguments.flags;

  response.body = { flags: [] };
  if (!IS_UNDEFINED(flags)) {
    for (var i = 0; i < flags.length; i++) {
      var name = flags[i].name;
      var debugger_flag = debugger_flags[name];
      if (!debugger_flag) {
        continue;
      }
      if ('value' in flags[i]) {
        debugger_flag.setValue(flags[i].value);
      }
      response.body.flags.push({ name: name, value: debugger_flag.getValue() });
    }
  } else {
    for (var name in debugger_flags) {
      var value = debugger_flags[name].getValue();
      response.body.flags.push({ name: name, value: value });
    }
  }
2309
};
2310 2311


2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
DebugCommandProcessor.prototype.v8FlagsRequest_ = function(request, response) {
  var flags = request.arguments.flags;
  if (!flags) flags = '';
  %SetFlags(flags);
};


DebugCommandProcessor.prototype.gcRequest_ = function(request, response) {
  var type = request.arguments.type;
  if (!type) type = 'all';

  var before = %GetHeapUsage();
  %CollectGarbage(type);
  var after = %GetHeapUsage();

  response.body = { "before": before, "after": after };
};


2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
DebugCommandProcessor.prototype.dispatch_ = (function() {
  var proto = DebugCommandProcessor.prototype;
  return {
    "continue":             proto.continueRequest_,
    "break"   :             proto.breakRequest_,
    "setbreakpoint" :       proto.setBreakPointRequest_,
    "changebreakpoint":     proto.changeBreakPointRequest_,
    "clearbreakpoint":      proto.clearBreakPointRequest_,
    "clearbreakpointgroup": proto.clearBreakPointGroupRequest_,
    "disconnect":           proto.disconnectRequest_,
    "setexceptionbreak":    proto.setExceptionBreakRequest_,
    "listbreakpoints":      proto.listBreakpointsRequest_,
    "backtrace":            proto.backtraceRequest_,
    "frame":                proto.frameRequest_,
    "scopes":               proto.scopesRequest_,
    "scope":                proto.scopeRequest_,
    "setvariablevalue":     proto.setVariableValueRequest_,
    "evaluate":             proto.evaluateRequest_,
    "lookup":               proto.lookupRequest_,
    "references":           proto.referencesRequest_,
    "source":               proto.sourceRequest_,
    "scripts":              proto.scriptsRequest_,
    "suspend":              proto.suspendRequest_,
    "version":              proto.versionRequest_,
    "changelive":           proto.changeLiveRequest_,
    "restartframe":         proto.restartFrameRequest_,
    "flags":                proto.debuggerFlagsRequest_,
    "v8flag":               proto.v8FlagsRequest_,
    "gc":                   proto.gcRequest_,
  };
})();


2364 2365 2366 2367
// Check whether the previously processed command caused the VM to become
// running.
DebugCommandProcessor.prototype.isRunning = function() {
  return this.running_;
2368
};
2369 2370 2371


DebugCommandProcessor.prototype.systemBreak = function(cmd, args) {
2372
  return %SystemBreak();
2373 2374 2375 2376
};


/**
2377 2378 2379 2380 2381 2382 2383
 * Convert an Object to its debugger protocol representation. The representation
 * may be serilized to a JSON object using JSON.stringify().
 * This implementation simply runs through all string property names, converts
 * each property value to a protocol value and adds the property to the result
 * object. For type "object" the function will be called recursively. Note that
 * circular structures will cause infinite recursion.
 * @param {Object} object The object to format as protocol object.
2384 2385
 * @param {MirrorSerializer} mirror_serializer The serializer to use if any
 *     mirror objects are encountered.
2386
 * @return {Object} Protocol object value.
2387
 */
2388 2389
function ObjectToProtocolObject_(object, mirror_serializer) {
  var content = {};
2390 2391 2392 2393
  for (var key in object) {
    // Only consider string keys.
    if (typeof key == 'string') {
      // Format the value based on its type.
2394 2395
      var property_value_json = ValueToProtocolValue_(object[key],
                                                      mirror_serializer);
2396
      // Add the property if relevant.
2397 2398
      if (!IS_UNDEFINED(property_value_json)) {
        content[key] = property_value_json;
2399 2400 2401
      }
    }
  }
2402

2403
  return content;
2404
}
2405

2406

2407
/**
2408 2409 2410
 * Convert an array to its debugger protocol representation. It will convert
 * each array element to a protocol value.
 * @param {Array} array The array to format as protocol array.
2411 2412
 * @param {MirrorSerializer} mirror_serializer The serializer to use if any
 *     mirror objects are encountered.
2413
 * @return {Array} Protocol array value.
2414
 */
2415 2416
function ArrayToProtocolArray_(array, mirror_serializer) {
  var json = [];
2417
  for (var i = 0; i < array.length; i++) {
2418 2419 2420 2421 2422 2423 2424
    json.push(ValueToProtocolValue_(array[i], mirror_serializer));
  }
  return json;
}


/**
2425
 * Convert a value to its debugger protocol representation.
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448
 * @param {*} value The value to format as protocol value.
 * @param {MirrorSerializer} mirror_serializer The serializer to use if any
 *     mirror objects are encountered.
 * @return {*} Protocol value.
 */
function ValueToProtocolValue_(value, mirror_serializer) {
  // Format the value based on its type.
  var json;
  switch (typeof value) {
    case 'object':
      if (value instanceof Mirror) {
        json = mirror_serializer.serializeValue(value);
      } else if (IS_ARRAY(value)){
        json = ArrayToProtocolArray_(value, mirror_serializer);
      } else {
        json = ObjectToProtocolObject_(value, mirror_serializer);
      }
      break;

    case 'boolean':
    case 'string':
    case 'number':
      json = value;
2449
      break;
2450 2451 2452

    default:
      json = null;
2453 2454
  }
  return json;
2455
}
2456 2457 2458 2459 2460 2461 2462 2463


// -------------------------------------------------------------------
// Exports

utils.InstallConstants(global, [
  "Debug", Debug,
  "DebugCommandProcessor", DebugCommandProcessor,
2464 2465 2466
  "BreakEvent", BreakEvent,
  "CompileEvent", CompileEvent,
  "BreakPoint", BreakPoint,
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
]);

// Functions needed by the debugger runtime.
utils.InstallFunctions(utils, DONT_ENUM, [
  "MakeExecutionState", MakeExecutionState,
  "MakeExceptionEvent", MakeExceptionEvent,
  "MakeBreakEvent", MakeBreakEvent,
  "MakeCompileEvent", MakeCompileEvent,
  "MakeAsyncTaskEvent", MakeAsyncTaskEvent,
  "IsBreakPointTriggered", IsBreakPointTriggered,
  "UpdateScriptBreakPoints", UpdateScriptBreakPoints,
]);

// Export to liveedit.js
utils.Export(function(to) {
  to.GetScriptBreakPoints = GetScriptBreakPoints;
});

})