debug-debugger.js 76.9 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
// 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.

// Default number of frames to include in the response to backtrace request.
29
var kDefaultBacktraceLength = 10;
30

31
var Debug = {};
32 33 34 35

// 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.
36
var sourceLineBeginningSkip = /^(?:\s*(?:\/\*.*?\*\/)*)*/;
37 38 39 40 41 42 43

// 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,
44 45
                     AfterCompile: 5,
                     ScriptCollected: 6 };
46 47

// Types of exceptions that can be broken upon.
48
Debug.ExceptionBreak = { Caught : 0,
49 50 51 52 53 54 55 56 57 58 59 60 61 62
                         Uncaught: 1 };

// The different types of steps.
Debug.StepAction = { StepOut: 0,
                     StepNext: 1,
                     StepIn: 2,
                     StepMin: 3,
                     StepInMin: 4 };

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

63 64 65 66 67 68
// The different types of script compilations matching enum
// Script::CompilationType in objects.h.
Debug.ScriptCompilationType = { Host: 0,
                                Eval: 1,
                                JSON: 2 };

69 70
// The different script break point types.
Debug.ScriptBreakPointType = { ScriptId: 0,
71 72
                               ScriptName: 1,
                               ScriptRegExp: 2 };
73

74 75 76 77 78 79 80 81 82
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 = [];
83 84 85 86 87 88 89 90
var debugger_flags = {
  breakPointsActive: {
    value: true,
    getValue: function() { return this.value; },
    setValue: function(value) {
      this.value = !!value;
      %SetDisableBreak(!this.value);
    }
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  },
  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();
      }
    }
  },
112
};
113
var lol_is_enabled = %HasLOLEnabled();
114 115 116


// Create a new break point object and add it to the list of break points.
117 118
function MakeBreakPoint(source_position, opt_script_break_point) {
  var break_point = new BreakPoint(source_position, opt_script_break_point);
119 120
  break_points.push(break_point);
  return break_point;
121
}
122 123 124 125 126 127


// 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.
128
function BreakPoint(source_position, opt_script_break_point) {
129 130 131 132 133 134 135 136 137 138
  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.hit_count_ = 0;
  this.active_ = true;
  this.condition_ = null;
  this.ignoreCount_ = 0;
139
}
140 141 142 143 144 145 146 147 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 210 211 212 213 214 215


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.hit_count = function() {
  return this.hit_count_;
};


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.ignoreCount = function() {
  return this.ignoreCount_;
};


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.setIgnoreCount = function(ignoreCount) {
  this.ignoreCount_ = ignoreCount;
};


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 {
216
      var mirror = exec_state.frame(0).evaluate(this.condition());
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
      // If no sensible mirror or non true value break point not triggered.
      if (!(mirror instanceof ValueMirror) || !%ToBoolean(mirror.value_)) {
        return false;
      }
    } catch (e) {
      // Exception evaluating condition counts as not triggered.
      return false;
    }
  }

  // Update the hit count.
  this.hit_count_++;
  if (this.script_break_point_) {
    this.script_break_point_.hit_count_++;
  }

  // If the break point has an ignore count it is not triggered.
  if (this.ignoreCount_ > 0) {
    this.ignoreCount_--;
    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));
248
}
249 250 251


// Object representing a script break point. The script is referenced by its
252 253
// script name or script id and the break point is represented as line and
// column.
254 255
function ScriptBreakPoint(type, script_id_or_name, opt_line, opt_column,
                          opt_groupId) {
256 257 258
  this.type_ = type;
  if (type == Debug.ScriptBreakPointType.ScriptId) {
    this.script_id_ = script_id_or_name;
259
  } else if (type == Debug.ScriptBreakPointType.ScriptName) {
260
    this.script_name_ = script_id_or_name;
261 262 263 264
  } else if (type == Debug.ScriptBreakPointType.ScriptRegExp) {
    this.script_regexp_object_ = new RegExp(script_id_or_name);
  } else {
    throw new Error("Unexpected breakpoint type " + type);
265
  }
266 267
  this.line_ = opt_line || 0;
  this.column_ = opt_column;
268
  this.groupId_ = opt_groupId;
269 270 271 272
  this.hit_count_ = 0;
  this.active_ = true;
  this.condition_ = null;
  this.ignoreCount_ = 0;
273
  this.break_points_ = [];
274
}
275 276


277 278 279 280 281 282
//Creates a clone of script breakpoint that is linked to another script.
ScriptBreakPoint.prototype.cloneForOtherScript = function (other_script) {
  var copy = new ScriptBreakPoint(Debug.ScriptBreakPointType.ScriptId,
      other_script.id, this.line_, this.column_, this.groupId_);
  copy.number_ = next_break_point_number++;
  script_break_points.push(copy);
283

284 285 286 287 288
  copy.hit_count_ = this.hit_count_;
  copy.active_ = this.active_;
  copy.condition_ = this.condition_;
  copy.ignoreCount_ = this.ignoreCount_;
  return copy;
289
};
290 291


292 293 294 295 296
ScriptBreakPoint.prototype.number = function() {
  return this.number_;
};


297 298 299 300 301
ScriptBreakPoint.prototype.groupId = function() {
  return this.groupId_;
};


302 303 304 305 306 307 308 309 310 311
ScriptBreakPoint.prototype.type = function() {
  return this.type_;
};


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


312 313 314 315 316
ScriptBreakPoint.prototype.script_name = function() {
  return this.script_name_;
};


317 318 319 320 321
ScriptBreakPoint.prototype.script_regexp_object = function() {
  return this.script_regexp_object_;
};


322 323 324 325 326 327 328 329 330 331
ScriptBreakPoint.prototype.line = function() {
  return this.line_;
};


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


332 333 334 335 336 337
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;
338
};
339 340


341 342 343
ScriptBreakPoint.prototype.update_positions = function(line, column) {
  this.line_ = line;
  this.column_ = column;
344
};
345 346


347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
ScriptBreakPoint.prototype.hit_count = function() {
  return this.hit_count_;
};


ScriptBreakPoint.prototype.active = function() {
  return this.active_;
};


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


ScriptBreakPoint.prototype.ignoreCount = function() {
  return this.ignoreCount_;
};


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


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


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


ScriptBreakPoint.prototype.setIgnoreCount = function(ignoreCount) {
  this.ignoreCount_ = ignoreCount;

  // Set ignore count on all break points created from this script break point.
386 387
  for (var i = 0; i < this.break_points_.length; i++) {
    this.break_points_[i].setIgnoreCount(ignoreCount);
388 389 390 391 392 393 394
  }
};


// Check whether a script matches this script break point. Currently this is
// only based on script name.
ScriptBreakPoint.prototype.matchesScript = function(script) {
395 396
  if (this.type_ == Debug.ScriptBreakPointType.ScriptId) {
    return this.script_id_ == script.id;
397 398 399 400 401 402 403 404 405 406
  } else {
    // We might want to account columns here as well.
    if (!(script.line_offset <= this.line_  &&
          this.line_ < script.line_offset + script.lineCount())) {
      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());
407
    } else {
408 409
      throw new Error("Unexpected breakpoint type " + this.type_);
    }
410
  }
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
};


// 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)) {
    var source_line = script.sourceLine(this.line());

    // Allocate array for caching the columns where the actual source starts.
    if (!script.sourceColumnStart_) {
      script.sourceColumnStart_ = new Array(script.lineCount());
    }
428

429 430 431 432 433 434 435 436 437
    // 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.
438
  var position = Debug.findScriptSourcePosition(script, this.line(), column);
439

440 441
  // If the position is not found in the script (the script might be shorter
  // than it used to be) just ignore it.
442
  if (position === null) return;
443

444
  // Create a break point object and set the break point.
445
  break_point = MakeBreakPoint(position, this);
446
  break_point.setIgnoreCount(this.ignoreCount());
447 448 449
  var actual_position = %SetScriptBreakPoint(script, position, break_point);
  if (IS_UNDEFINED(actual_position)) {
    actual_position = position;
450
  }
451 452
  var actual_location = script.locationFromPosition(actual_position, true);
  break_point.actual_location = { line: actual_location.line,
453 454
                                  column: actual_location.column,
                                  script_id: script.id };
455
  this.break_points_.push(break_point);
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  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;
472
  this.break_points_ = [];
473 474 475 476 477 478 479
};


// 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++) {
480
    var break_point = script_break_points[i];
481 482
    if ((break_point.type() == Debug.ScriptBreakPointType.ScriptName ||
         break_point.type() == Debug.ScriptBreakPointType.ScriptRegExp) &&
483 484
        break_point.matchesScript(script)) {
      break_point.set(script);
485 486
    }
  }
487
}
488 489


490 491 492 493 494 495 496 497 498 499 500
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;
}


501 502 503 504 505
Debug.setListener = function(listener, opt_data) {
  if (!IS_FUNCTION(listener) && !IS_UNDEFINED(listener) && !IS_NULL(listener)) {
    throw new Error('Parameters have wrong types.');
  }
  %SetDebugEventListener(listener, opt_data);
506 507 508
};


509
Debug.breakExecution = function(f) {
510
  %Break();
511 512 513 514 515 516 517 518 519 520
};

Debug.breakLocations = function(f) {
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
  return %GetBreakLocations(f);
};

// 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
521 522
// value.  If it is a regexp and there is a unique script whose name matches
// we return that, otherwise undefined.
523 524 525
Debug.findScript = function(func_or_script_name) {
  if (IS_FUNCTION(func_or_script_name)) {
    return %FunctionGetScript(func_or_script_name);
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
  } else if (IS_REGEXP(func_or_script_name)) {
    var scripts = Debug.scripts();
    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 {
      return undefined;
    }
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
  } 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;
};

Debug.source = function(f) {
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
  return %FunctionGetSourceCode(f);
};

565
Debug.disassemble = function(f) {
566
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
567 568 569 570 571 572
  return %DebugDisassembleFunction(f);
};

Debug.disassembleConstructor = function(f) {
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
  return %DebugDisassembleConstructor(f);
573 574
};

575 576 577 578 579
Debug.ExecuteInDebugContext = function(f, without_debugger) {
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
  return %ExecuteInDebugContext(f, !!without_debugger);
};

580 581 582 583 584
Debug.sourcePosition = function(f) {
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
  return %FunctionGetScriptSourcePosition(f);
};

585 586

Debug.findFunctionSourceLocation = function(func, opt_line, opt_column) {
587 588
  var script = %FunctionGetScript(func);
  var script_offset = %FunctionGetScriptSourcePosition(func);
589
  return script.locationFromLine(opt_line, opt_column, script_offset);
590
};
591 592 593 594 595


// 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) {
596
  var location = script.locationFromLine(opt_line, opt_column);
597
  return location ? location.position : null;
598
};
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619


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);
  }
};

620 621 622 623 624 625 626 627 628 629 630 631
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 [];
632
};
633 634 635

Debug.setBreakPoint = function(func, opt_line, opt_column, opt_condition) {
  if (!IS_FUNCTION(func)) throw new Error('Parameters have wrong types.');
636 637 638 639
  // Break points in API functions are not supported.
  if (%FunctionIsAPIFunction(func)) {
    throw new Error('Cannot set break point in native code.');
  }
640 641 642 643
  // Find source position relative to start of the function
  var break_position =
      this.findFunctionSourceLocation(func, opt_line, opt_column).position;
  var source_position = break_position - this.sourcePosition(func);
644 645
  // Find the script for the function.
  var script = %FunctionGetScript(func);
646 647 648 649
  // Break in builtin JavaScript code is not supported.
  if (script.type == Debug.ScriptType.Native) {
    throw new Error('Cannot set break point in native code.');
  }
650 651
  // If the script for the function has a name convert this to a script break
  // point.
652
  if (script && script.id) {
653 654 655 656
    // Adjust the source position to be script relative.
    source_position += %FunctionGetScriptSourcePosition(func);
    // Find line and column for the position in the script and set a script
    // break point from that.
657
    var location = script.locationFromPosition(source_position, false);
658 659 660
    return this.setScriptBreakPointById(script.id,
                                        location.line, location.column,
                                        opt_condition);
661 662
  } else {
    // Set a break point directly on the function.
663
    var break_point = MakeBreakPoint(source_position);
664 665 666 667 668
    var actual_position =
        %SetFunctionBreakPoint(func, source_position, break_point);
    actual_position += this.sourcePosition(func);
    var actual_location = script.locationFromPosition(actual_position, true);
    break_point.actual_location = { line: actual_location.line,
669 670
                                    column: actual_location.column,
                                    script_id: script.id };
671 672 673 674 675 676
    break_point.setCondition(opt_condition);
    return break_point.number();
  }
};


677 678 679 680 681
Debug.setBreakPointByScriptIdAndPosition = function(script_id, position,
                                                    condition, enabled)
{
  break_point = MakeBreakPoint(position);
  break_point.setCondition(condition);
682
  if (!enabled) {
683
    break_point.disable();
684
  }
685 686 687 688 689 690 691 692 693 694 695 696
  var scripts = this.scripts();
  for (var i = 0; i < scripts.length; i++) {
    if (script_id == scripts[i].id) {
      break_point.actual_position = %SetScriptBreakPoint(scripts[i], position,
                                                         break_point);
      break;
    }
  }
  return break_point;
};


697 698
Debug.enableBreakPoint = function(break_point_number) {
  var break_point = this.findBreakPoint(break_point_number, false);
699 700 701 702
  // Only enable if the breakpoint hasn't been deleted:
  if (break_point) {
    break_point.enable();
  }
703 704 705 706 707
};


Debug.disableBreakPoint = function(break_point_number) {
  var break_point = this.findBreakPoint(break_point_number, false);
708 709 710 711
  // Only enable if the breakpoint hasn't been deleted:
  if (break_point) {
    break_point.disable();
  }
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
};


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


Debug.changeBreakPointIgnoreCount = function(break_point_number, ignoreCount) {
  if (ignoreCount < 0) {
    throw new Error('Invalid argument');
  }
  var break_point = this.findBreakPoint(break_point_number, false);
  break_point.setIgnoreCount(ignoreCount);
};


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);
    if (!break_point) {
      throw new Error('Invalid breakpoint');
    }
  }
};


Debug.clearAllBreakPoints = function() {
  for (var i = 0; i < break_points.length; i++) {
    break_point = break_points[i];
    %ClearBreakPoint(break_point);
  }
  break_points = [];
};


752 753 754 755 756 757 758 759 760 761 762
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);
};


763 764 765 766 767 768 769 770 771 772 773 774 775 776
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;
777
};
778 779


780
// Sets a breakpoint in a script identified through id or name at the
781
// specified source line and column within that line.
782
Debug.setScriptBreakPoint = function(type, script_id_or_name,
783 784
                                     opt_line, opt_column, opt_condition,
                                     opt_groupId) {
785
  // Create script break point object.
786
  var script_break_point =
787 788
      new ScriptBreakPoint(type, script_id_or_name, opt_line, opt_column,
                           opt_groupId);
789 790 791 792 793 794

  // 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);

795
  // Run through all scripts to see if this script break point matches any
796 797 798 799 800 801 802 803 804
  // 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();
805
};
806 807


808 809
Debug.setScriptBreakPointById = function(script_id,
                                         opt_line, opt_column,
810
                                         opt_condition, opt_groupId) {
811 812
  return this.setScriptBreakPoint(Debug.ScriptBreakPointType.ScriptId,
                                  script_id, opt_line, opt_column,
813
                                  opt_condition, opt_groupId);
814
};
815 816 817 818


Debug.setScriptBreakPointByName = function(script_name,
                                           opt_line, opt_column,
819
                                           opt_condition, opt_groupId) {
820 821
  return this.setScriptBreakPoint(Debug.ScriptBreakPointType.ScriptName,
                                  script_name, opt_line, opt_column,
822
                                  opt_condition, opt_groupId);
823
};
824 825


826 827 828 829 830 831
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);
832
};
833 834


835 836 837 838 839 840 841 842 843 844 845 846
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();
};


847 848
Debug.changeScriptBreakPointCondition = function(
    break_point_number, condition) {
849 850 851 852 853
  var script_break_point = this.findScriptBreakPoint(break_point_number, false);
  script_break_point.setCondition(condition);
};


854 855
Debug.changeScriptBreakPointIgnoreCount = function(
    break_point_number, ignoreCount) {
856 857 858 859 860 861 862 863 864 865
  if (ignoreCount < 0) {
    throw new Error('Invalid argument');
  }
  var script_break_point = this.findScriptBreakPoint(break_point_number, false);
  script_break_point.setIgnoreCount(ignoreCount);
};


Debug.scriptBreakPoints = function() {
  return script_break_points;
866
};
867 868 869


Debug.clearStepping = function() {
870
  %ClearStepping();
871
};
872 873

Debug.setBreakOnException = function() {
874
  return %ChangeBreakOnException(Debug.ExceptionBreak.Caught, true);
875 876 877
};

Debug.clearBreakOnException = function() {
878 879 880 881 882
  return %ChangeBreakOnException(Debug.ExceptionBreak.Caught, false);
};

Debug.isBreakOnException = function() {
  return !!%IsBreakOnException(Debug.ExceptionBreak.Caught);
883 884 885 886 887 888 889 890 891 892
};

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

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

893 894 895 896
Debug.isBreakOnUncaughtException = function() {
  return !!%IsBreakOnException(Debug.ExceptionBreak.Uncaught);
};

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
Debug.showBreakPoints = function(f, full) {
  if (!IS_FUNCTION(f)) throw new Error('Parameters have wrong types.');
  var source = full ? this.scriptSource(f) : this.source(f);
  var offset = full ? this.sourcePosition(f) : 0;
  var locations = this.breakLocations(f);
  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.
923
  return %DebugGetLoadedScripts();
924 925 926 927 928 929 930
};


Debug.debuggerFlags = function() {
  return debugger_flags;
};

931
Debug.MakeMirror = MakeMirror;
932 933 934

function MakeExecutionState(break_id) {
  return new ExecutionState(break_id);
935
}
936 937 938 939

function ExecutionState(break_id) {
  this.break_id = break_id;
  this.selected_frame = 0;
940
}
941 942 943 944 945 946 947

ExecutionState.prototype.prepareStep = function(opt_action, opt_count) {
  var action = Debug.StepAction.StepIn;
  if (!IS_UNDEFINED(opt_action)) action = %ToNumber(opt_action);
  var count = opt_count ? %ToNumber(opt_count) : 1;

  return %PrepareStep(this.break_id, action, count);
948
};
949

950 951 952 953 954
ExecutionState.prototype.evaluateGlobal = function(source, disable_break,
    opt_additional_context) {
  return MakeMirror(%DebugEvaluateGlobal(this.break_id, source,
                                         Boolean(disable_break),
                                         opt_additional_context));
955 956
};

957
ExecutionState.prototype.frameCount = function() {
958 959 960
  return %GetFrameCount(this.break_id);
};

961 962 963 964
ExecutionState.prototype.threadCount = function() {
  return %GetThreadCount(this.break_id);
};

965
ExecutionState.prototype.frame = function(opt_index) {
966 967
  // If no index supplied return the selected frame.
  if (opt_index == null) opt_index = this.selected_frame;
968
  if (opt_index < 0 || opt_index >= this.frameCount()) {
969
    throw new Error('Illegal frame index.');
970
  }
971 972 973 974 975
  return new FrameMirror(this.break_id, opt_index);
};

ExecutionState.prototype.setSelectedFrame = function(index) {
  var i = %ToNumber(index);
976
  if (i < 0 || i >= this.frameCount()) throw new Error('Illegal frame index.');
977 978 979
  this.selected_frame = i;
};

980
ExecutionState.prototype.selectedFrame = function() {
981 982 983
  return this.selected_frame;
};

984 985
ExecutionState.prototype.debugCommandProcessor = function(opt_is_running) {
  return new DebugCommandProcessor(this, opt_is_running);
986 987 988 989 990
};


function MakeBreakEvent(exec_state, break_points_hit) {
  return new BreakEvent(exec_state, break_points_hit);
991
}
992 993 994 995 996


function BreakEvent(exec_state, break_points_hit) {
  this.exec_state_ = exec_state;
  this.break_points_hit_ = break_points_hit;
997
}
998 999


1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
BreakEvent.prototype.executionState = function() {
  return this.exec_state_;
};


BreakEvent.prototype.eventType = function() {
  return Debug.DebugEvent.Break;
};


1010
BreakEvent.prototype.func = function() {
1011
  return this.exec_state_.frame(0).func();
1012 1013 1014 1015
};


BreakEvent.prototype.sourceLine = function() {
1016
  return this.exec_state_.frame(0).sourceLine();
1017 1018 1019 1020
};


BreakEvent.prototype.sourceColumn = function() {
1021
  return this.exec_state_.frame(0).sourceColumn();
1022 1023 1024 1025
};


BreakEvent.prototype.sourceLineText = function() {
1026
  return this.exec_state_.frame(0).sourceLineText();
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
};


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


BreakEvent.prototype.toJSONProtocol = function() {
  var o = { seq: next_response_seq++,
            type: "event",
            event: "break",
1039
            body: { invocationText: this.exec_state_.frame(0).invocationText(),
1040
                  }
1041
          };
1042 1043 1044 1045 1046 1047 1048

  // 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(),
1049
    o.body.script = MakeScriptObject_(script, false);
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
  }

  // 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);
    }
  }
1069
  return JSON.stringify(ObjectToProtocolObject_(o));
1070 1071 1072 1073 1074
};


function MakeExceptionEvent(exec_state, exception, uncaught) {
  return new ExceptionEvent(exec_state, exception, uncaught);
1075
}
1076

1077

1078 1079 1080 1081
function ExceptionEvent(exec_state, exception, uncaught) {
  this.exec_state_ = exec_state;
  this.exception_ = exception;
  this.uncaught_ = uncaught;
1082
}
1083

1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

ExceptionEvent.prototype.executionState = function() {
  return this.exec_state_;
};


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


1095 1096
ExceptionEvent.prototype.exception = function() {
  return this.exception_;
1097
};
1098 1099


1100 1101
ExceptionEvent.prototype.uncaught = function() {
  return this.uncaught_;
1102
};
1103

1104

1105
ExceptionEvent.prototype.func = function() {
1106
  return this.exec_state_.frame(0).func();
1107 1108 1109 1110
};


ExceptionEvent.prototype.sourceLine = function() {
1111
  return this.exec_state_.frame(0).sourceLine();
1112 1113 1114 1115
};


ExceptionEvent.prototype.sourceColumn = function() {
1116
  return this.exec_state_.frame(0).sourceColumn();
1117 1118 1119 1120
};


ExceptionEvent.prototype.sourceLineText = function() {
1121
  return this.exec_state_.frame(0).sourceLineText();
1122 1123 1124 1125
};


ExceptionEvent.prototype.toJSONProtocol = function() {
1126 1127 1128 1129
  var o = new ProtocolMessage();
  o.event = "exception";
  o.body = { uncaught: this.uncaught_,
             exception: MakeMirror(this.exception_)
1130
           };
1131

1132 1133 1134 1135 1136 1137 1138 1139 1140
  // 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) {
1141
      o.body.script = MakeScriptObject_(script, false);
1142 1143 1144
    }
  } else {
    o.body.sourceLine = -1;
1145 1146
  }

1147
  return o.toJSONProtocol();
1148 1149
};

1150

1151 1152
function MakeCompileEvent(exec_state, script, before) {
  return new CompileEvent(exec_state, script, before);
1153
}
1154

1155

1156 1157 1158 1159
function CompileEvent(exec_state, script, before) {
  this.exec_state_ = exec_state;
  this.script_ = MakeMirror(script);
  this.before_ = before;
1160
}
1161 1162


1163 1164 1165 1166 1167
CompileEvent.prototype.executionState = function() {
  return this.exec_state_;
};


1168
CompileEvent.prototype.eventType = function() {
1169 1170
  if (this.before_) {
    return Debug.DebugEvent.BeforeCompile;
1171
  } else {
1172
    return Debug.DebugEvent.AfterCompile;
1173 1174 1175 1176
  }
};


1177 1178 1179 1180 1181
CompileEvent.prototype.script = function() {
  return this.script_;
};


1182 1183
CompileEvent.prototype.toJSONProtocol = function() {
  var o = new ProtocolMessage();
1184
  o.running = true;
1185 1186 1187 1188 1189 1190
  if (this.before_) {
    o.event = "beforeCompile";
  } else {
    o.event = "afterCompile";
  }
  o.body = {};
1191
  o.body.script = this.script_;
1192 1193

  return o.toJSONProtocol();
1194
};
1195 1196


1197 1198
function MakeNewFunctionEvent(func) {
  return new NewFunctionEvent(func);
1199
}
1200

1201

1202 1203
function NewFunctionEvent(func) {
  this.func = func;
1204
}
1205

1206 1207 1208 1209 1210 1211

NewFunctionEvent.prototype.eventType = function() {
  return Debug.DebugEvent.NewFunction;
};


1212 1213 1214 1215
NewFunctionEvent.prototype.name = function() {
  return this.func.name;
};

1216

1217 1218 1219 1220
NewFunctionEvent.prototype.setBreakPoint = function(p) {
  Debug.setBreakPoint(this.func, p || 0);
};

1221

1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
function MakeScriptCollectedEvent(exec_state, id) {
  return new ScriptCollectedEvent(exec_state, id);
}


function ScriptCollectedEvent(exec_state, id) {
  this.exec_state_ = exec_state;
  this.id_ = id;
}


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


ScriptCollectedEvent.prototype.executionState = function() {
  return this.exec_state_;
};


ScriptCollectedEvent.prototype.toJSONProtocol = function() {
  var o = new ProtocolMessage();
  o.running = true;
  o.event = "scriptCollected";
  o.body = {};
  o.body.script = { id: this.id() };
  return o.toJSONProtocol();
1250
};
1251 1252


1253 1254 1255 1256 1257 1258 1259
function MakeScriptObject_(script, include_source) {
  var o = { id: script.id(),
            name: script.name(),
            lineOffset: script.lineOffset(),
            columnOffset: script.columnOffset(),
            lineCount: script.lineCount(),
          };
1260 1261 1262
  if (!IS_UNDEFINED(script.data())) {
    o.data = script.data();
  }
1263 1264 1265 1266
  if (include_source) {
    o.source = script.source();
  }
  return o;
1267
}
1268 1269


1270
function DebugCommandProcessor(exec_state, opt_is_running) {
1271
  this.exec_state_ = exec_state;
1272
  this.running_ = opt_is_running || false;
1273
}
1274 1275


1276 1277
DebugCommandProcessor.prototype.processDebugRequest = function (request) {
  return this.processDebugJSONRequest(request);
1278
};
1279 1280


1281 1282
function ProtocolMessage(request) {
  // Update sequence number.
1283
  this.seq = next_response_seq++;
1284

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  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';
  }
1295
  this.success = true;
1296 1297
  // Handler may set this field to control debugger state.
  this.running = undefined;
1298
}
1299 1300


1301 1302 1303 1304 1305
ProtocolMessage.prototype.setOption = function(name, value) {
  if (!this.options_) {
    this.options_ = {};
  }
  this.options_[name] = value;
1306
};
1307 1308


1309
ProtocolMessage.prototype.failed = function(message) {
1310 1311
  this.success = false;
  this.message = message;
1312
};
1313 1314


1315
ProtocolMessage.prototype.toJSONProtocol = function() {
1316
  // Encode the protocol header.
1317 1318
  var json = {};
  json.seq= this.seq;
1319
  if (this.request_seq) {
1320
    json.request_seq = this.request_seq;
1321
  }
1322
  json.type = this.type;
1323
  if (this.event) {
1324
    json.event = this.event;
1325
  }
1326
  if (this.command) {
1327
    json.command = this.command;
1328 1329
  }
  if (this.success) {
1330
    json.success = this.success;
1331
  } else {
1332
    json.success = false;
1333 1334 1335
  }
  if (this.body) {
    // Encode the body part.
1336
    var bodyJson;
1337
    var serializer = MakeMirrorSerializer(true, this.options_);
1338
    if (this.body instanceof Mirror) {
1339
      bodyJson = serializer.serializeValue(this.body);
1340
    } else if (this.body instanceof Array) {
1341
      bodyJson = [];
1342
      for (var i = 0; i < this.body.length; i++) {
1343
        if (this.body[i] instanceof Mirror) {
1344
          bodyJson.push(serializer.serializeValue(this.body[i]));
1345
        } else {
1346
          bodyJson.push(ObjectToProtocolObject_(this.body[i], serializer));
1347 1348 1349
        }
      }
    } else {
1350
      bodyJson = ObjectToProtocolObject_(this.body, serializer);
1351
    }
1352 1353
    json.body = bodyJson;
    json.refs = serializer.serializeReferencedObjects();
1354 1355
  }
  if (this.message) {
1356
    json.message = this.message;
1357
  }
1358
  json.running = this.running;
1359
  return JSON.stringify(json);
1360
};
1361 1362 1363


DebugCommandProcessor.prototype.createResponse = function(request) {
1364
  return new ProtocolMessage(request);
1365 1366 1367
};


1368 1369
DebugCommandProcessor.prototype.processDebugJSONRequest = function(
    json_request) {
1370 1371 1372 1373 1374
  var request;  // Current request.
  var response;  // Generated response.
  try {
    try {
      // Convert the JSON string to an object.
1375
      request = JSON.parse(json_request);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391

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

      if (!request.type) {
        throw new Error('Type not specified');
      }

      if (request.type != 'request') {
        throw new Error("Illegal type '" + request.type + "' in request");
      }

      if (!request.command) {
        throw new Error('Command not specified');
      }

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
      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);
        }
1402 1403
      }

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
      if (request.command == 'continue') {
        this.continueRequest_(request, response);
      } else if (request.command == 'break') {
        this.breakRequest_(request, response);
      } else if (request.command == 'setbreakpoint') {
        this.setBreakPointRequest_(request, response);
      } else if (request.command == 'changebreakpoint') {
        this.changeBreakPointRequest_(request, response);
      } else if (request.command == 'clearbreakpoint') {
        this.clearBreakPointRequest_(request, response);
1414 1415
      } else if (request.command == 'clearbreakpointgroup') {
        this.clearBreakPointGroupRequest_(request, response);
1416 1417 1418 1419
      } else if (request.command == 'disconnect') {
        this.disconnectRequest_(request, response);
      } else if (request.command == 'setexceptionbreak') {
        this.setExceptionBreakRequest_(request, response);
1420 1421
      } else if (request.command == 'listbreakpoints') {
        this.listBreakpointsRequest_(request, response);
1422 1423 1424 1425
      } else if (request.command == 'backtrace') {
        this.backtraceRequest_(request, response);
      } else if (request.command == 'frame') {
        this.frameRequest_(request, response);
1426 1427 1428 1429
      } else if (request.command == 'scopes') {
        this.scopesRequest_(request, response);
      } else if (request.command == 'scope') {
        this.scopeRequest_(request, response);
1430 1431
      } else if (request.command == 'evaluate') {
        this.evaluateRequest_(request, response);
1432 1433
      } else if (lol_is_enabled && request.command == 'getobj') {
        this.getobjRequest_(request, response);
1434 1435
      } else if (request.command == 'lookup') {
        this.lookupRequest_(request, response);
1436 1437
      } else if (request.command == 'references') {
        this.referencesRequest_(request, response);
1438 1439 1440 1441
      } else if (request.command == 'source') {
        this.sourceRequest_(request, response);
      } else if (request.command == 'scripts') {
        this.scriptsRequest_(request, response);
1442 1443
      } else if (request.command == 'threads') {
        this.threadsRequest_(request, response);
1444 1445
      } else if (request.command == 'suspend') {
        this.suspendRequest_(request, response);
1446 1447
      } else if (request.command == 'version') {
        this.versionRequest_(request, response);
1448
      } else if (request.command == 'profile') {
1449
        this.profileRequest_(request, response);
1450
      } else if (request.command == 'changelive') {
1451 1452 1453
        this.changeLiveRequest_(request, response);
      } else if (request.command == 'flags') {
        this.debuggerFlagsRequest_(request, response);
1454 1455 1456 1457 1458 1459 1460
      } else if (request.command == 'v8flags') {
        this.v8FlagsRequest_(request, response);

      // GC tools:
      } else if (request.command == 'gc') {
        this.gcRequest_(request, response);

1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
      // LiveObjectList tools:
      } else if (lol_is_enabled && request.command == 'lol-capture') {
        this.lolCaptureRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-delete') {
        this.lolDeleteRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-diff') {
        this.lolDiffRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-getid') {
        this.lolGetIdRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-info') {
        this.lolInfoRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-reset') {
        this.lolResetRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-retainers') {
        this.lolRetainersRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-path') {
        this.lolPathRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-print') {
        this.lolPrintRequest_(request, response);
      } else if (lol_is_enabled && request.command == 'lol-stats') {
        this.lolStatsRequest_(request, response);

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
      } else {
        throw new Error('Unknown command "' + request.command + '" in request');
      }
    } catch (e) {
      // If there is no response object created one (without command).
      if (!response) {
        response = this.createResponse();
      }
      response.success = false;
      response.message = %ToString(e);
    }

    // Return the response as a JSON encoded string.
    try {
1497 1498 1499 1500
      if (!IS_UNDEFINED(response.running)) {
        // Response controls running state.
        this.running_ = response.running;
      }
1501
      response.running = this.running_;
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
      return response.toJSONProtocol();
    } catch (e) {
      // Failed to generate response - return generic error.
      return '{"seq":' + response.seq + ',' +
              '"request_seq":' + request.seq + ',' +
              '"type":"response",' +
              '"success":false,' +
              '"message":"Internal error: ' + %ToString(e) + '"}';
    }
  } 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 count = 1;
    var action = Debug.StepAction.StepIn;

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

    // Get the stepcount argument if any.
    if (stepcount) {
      count = %ToNumber(stepcount);
      if (count < 0) {
        throw new Error('Invalid stepcount argument "' + stepcount + '".');
      }
    }

    // Get the stepaction argument.
    if (stepaction) {
      if (stepaction == 'in') {
        action = Debug.StepAction.StepIn;
      } else if (stepaction == 'min') {
        action = Debug.StepAction.StepMin;
      } else if (stepaction == 'next') {
        action = Debug.StepAction.StepNext;
      } else if (stepaction == 'out') {
        action = Debug.StepAction.StepOut;
      } else {
        throw new Error('Invalid stepaction argument "' + stepaction + '".');
      }
    }

1551
    // Set up the VM for stepping.
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
    this.exec_state_.prepareStep(action, count);
  }

  // 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;
  var ignoreCount = request.arguments.ignoreCount;
1582
  var groupId = request.arguments.groupId;
1583 1584

  // Check for legal arguments.
1585
  if (!type || IS_UNDEFINED(target)) {
1586 1587 1588
    response.failed('Missing argument "type" or "target"');
    return;
  }
1589

1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
  // 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.
1601
      f = this.exec_state_.evaluateGlobal(target).value();
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
    } catch (e) {
      response.failed('Error: "' + %ToString(e) +
                      '" 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);
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
  } else if (type == 'handle') {
    // Find the object pointed by the specified handle.
    var handle = parseInt(target, 10);
    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);
1628
  } else if (type == 'script') {
1629
    // set script break point.
1630
    break_point_number =
1631 1632
        Debug.setScriptBreakPointByName(target, line, column, condition,
                                        groupId);
1633
  } else if (type == 'scriptId') {
1634
    break_point_number =
1635
        Debug.setScriptBreakPointById(target, line, column, condition, groupId);
1636
  } else if (type == 'scriptRegExp') {
1637 1638 1639 1640 1641 1642
    break_point_number =
        Debug.setScriptBreakPointByRegExp(target, line, column, condition,
                                          groupId);
  } else {
    response.failed('Illegal type "' + type + '"');
    return;
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
  }

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

  // Add the break point number to the response.
  response.body = { type: type,
1656
                    breakpoint: break_point_number };
1657 1658 1659

  // Add break point information to the response.
  if (break_point instanceof ScriptBreakPoint) {
1660 1661 1662
    if (break_point.type() == Debug.ScriptBreakPointType.ScriptId) {
      response.body.type = 'scriptId';
      response.body.script_id = break_point.script_id();
1663
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptName) {
1664 1665
      response.body.type = 'scriptName';
      response.body.script_name = break_point.script_name();
1666 1667 1668 1669
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptRegExp) {
      response.body.type = 'scriptRegExp';
      response.body.script_regexp = break_point.script_regexp_object().source;
    } else {
1670 1671
      throw new Error("Internal error: Unexpected breakpoint type: " +
                      break_point.type());
1672
    }
1673 1674
    response.body.line = break_point.line();
    response.body.column = break_point.column();
1675
    response.body.actual_locations = break_point.actual_locations();
1676 1677
  } else {
    response.body.type = 'function';
1678
    response.body.actual_locations = [break_point.actual_location];
1679 1680 1681 1682
  }
};


1683 1684
DebugCommandProcessor.prototype.changeBreakPointRequest_ = function(
    request, response) {
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
  var break_point = %ToNumber(request.arguments.breakpoint);
  var enabled = request.arguments.enabled;
  var condition = request.arguments.condition;
  var ignoreCount = request.arguments.ignoreCount;

  // 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);
  }

  // Change ignore count if supplied
  if (!IS_UNDEFINED(ignoreCount)) {
    Debug.changeBreakPointIgnoreCount(break_point, ignoreCount);
  }
1721
};
1722 1723


1724 1725
DebugCommandProcessor.prototype.clearBreakPointGroupRequest_ = function(
    request, response) {
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
  // 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;
  }
1740

1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
  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 };
1756
};
1757 1758


1759 1760
DebugCommandProcessor.prototype.clearBreakPointRequest_ = function(
    request, response) {
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
  // Check for legal request.
  if (!request.arguments) {
    response.failed('Missing arguments');
    return;
  }

  // Pull out arguments.
  var break_point = %ToNumber(request.arguments.breakpoint);

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

  // Clear break point.
  Debug.clearBreakPoint(break_point);
1778 1779

  // Add the cleared break point number to the response.
1780 1781
  response.body = { breakpoint: break_point };
};
1782

1783

1784 1785
DebugCommandProcessor.prototype.listBreakpointsRequest_ = function(
    request, response) {
1786 1787
  var array = [];
  for (var i = 0; i < script_break_points.length; i++) {
peter.rybin@gmail.com's avatar
peter.rybin@gmail.com committed
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
    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(),
      hit_count: break_point.hit_count(),
      active: break_point.active(),
      condition: break_point.condition(),
1798 1799
      ignoreCount: break_point.ignoreCount(),
      actual_locations: break_point.actual_locations()
1800
    };
1801

1802 1803
    if (break_point.type() == Debug.ScriptBreakPointType.ScriptId) {
      description.type = 'scriptId';
peter.rybin@gmail.com's avatar
peter.rybin@gmail.com committed
1804
      description.script_id = break_point.script_id();
1805
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptName) {
1806 1807
      description.type = 'scriptName';
      description.script_name = break_point.script_name();
1808 1809 1810 1811
    } else if (break_point.type() == Debug.ScriptBreakPointType.ScriptRegExp) {
      description.type = 'scriptRegExp';
      description.script_regexp = break_point.script_regexp_object().source;
    } else {
1812 1813
      throw new Error("Internal error: Unexpected breakpoint type: " +
                      break_point.type());
1814
    }
peter.rybin@gmail.com's avatar
peter.rybin@gmail.com committed
1815
    array.push(description);
1816
  }
1817

1818 1819 1820 1821
  response.body = {
    breakpoints: array,
    breakOnExceptions: Debug.isBreakOnException(),
    breakOnUncaughtExceptions: Debug.isBreakOnUncaughtException()
1822 1823
  };
};
1824 1825 1826 1827 1828 1829


DebugCommandProcessor.prototype.disconnectRequest_ =
    function(request, response) {
  Debug.disableAllBreakPoints();
  this.continueRequest_(request, response);
1830
};
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853


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();
1854
  }
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874

  // 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 };
1875
};
1876

1877

1878 1879
DebugCommandProcessor.prototype.backtraceRequest_ = function(
    request, response) {
1880
  // Get the number of frames.
1881
  var total_frames = this.exec_state_.frameCount();
1882

1883 1884 1885 1886
  // Create simple response if there are no frames.
  if (total_frames == 0) {
    response.body = {
      totalFrames: total_frames
1887
    };
1888 1889 1890
    return;
  }

1891
  // Default frame range to include in backtrace.
1892
  var from_index = 0;
1893 1894 1895 1896
  var to_index = kDefaultBacktraceLength;

  // Get the range from the arguments.
  if (request.arguments) {
1897 1898 1899 1900 1901 1902 1903 1904
    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;
1905
      from_index = total_frames - to_index;
1906
      to_index = tmp_index;
1907
    }
1908
    if (from_index < 0 || to_index < 0) {
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
      return response.failed('Invalid frame number');
    }
  }

  // Adjust the index.
  to_index = Math.min(total_frames, to_index);

  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++) {
1924
    frames.push(this.exec_state_.frame(i));
1925 1926 1927 1928 1929 1930
  }
  response.body = {
    fromFrame: from_index,
    toFrame: to_index,
    totalFrames: total_frames,
    frames: frames
1931
  };
1932 1933 1934 1935
};


DebugCommandProcessor.prototype.frameRequest_ = function(request, response) {
1936 1937 1938 1939 1940
  // No frames no source.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No frames');
  }

1941
  // With no arguments just keep the selected frame.
1942
  if (request.arguments) {
1943
    var index = request.arguments.number;
1944 1945 1946
    if (index < 0 || this.exec_state_.frameCount() <= index) {
      return response.failed('Invalid frame number');
    }
1947

1948 1949
    this.exec_state_.setSelectedFrame(request.arguments.number);
  }
1950
  response.body = this.exec_state_.frame();
1951 1952 1953
};


1954
DebugCommandProcessor.prototype.frameForScopeRequest_ = function(request) {
1955 1956
  // Get the frame for which the scope or scopes are requested.
  // With no frameNumber argument use the currently selected frame.
1957 1958 1959
  if (request.arguments && !IS_UNDEFINED(request.arguments.frameNumber)) {
    frame_index = request.arguments.frameNumber;
    if (frame_index < 0 || this.exec_state_.frameCount() <= frame_index) {
1960
      throw new Error('Invalid frame number');
1961 1962 1963 1964 1965
    }
    return this.exec_state_.frame(frame_index);
  } else {
    return this.exec_state_.frame();
  }
1966
};
1967 1968


1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
// 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).
DebugCommandProcessor.prototype.scopeHolderForScopeRequest_ =
    function(request) {
  if (request.arguments && "functionHandle" in request.arguments) {
    if (!IS_NUMBER(request.arguments.functionHandle)) {
      throw new Error('Function handle must be a number');
    }
    var function_mirror = LookupMirror(request.arguments.functionHandle);
    if (!function_mirror) {
      throw new Error('Failed to find function object by handle');
    }
    if (!function_mirror.isFunction()) {
      throw new Error('Value of non-function type is found by handle');
    }
    return function_mirror;
  } else {
    // No frames no scopes.
    if (this.exec_state_.frameCount() == 0) {
      throw new Error('No scopes');
    }

    // Get the frame for which the scopes are requested.
    var frame = this.frameForScopeRequest_(request);
    return frame;
1995
  }
1996
}
1997

1998

1999 2000 2001 2002 2003
DebugCommandProcessor.prototype.scopesRequest_ = function(request, response) {
  var scope_holder = this.scopeHolderForScopeRequest_(request);

  // Fill all scopes for this frame or function.
  var total_scopes = scope_holder.scopeCount();
2004 2005
  var scopes = [];
  for (var i = 0; i < total_scopes; i++) {
2006
    scopes.push(scope_holder.scope(i));
2007 2008 2009 2010 2011 2012
  }
  response.body = {
    fromScope: 0,
    toScope: total_scopes,
    totalScopes: total_scopes,
    scopes: scopes
2013
  };
2014 2015 2016 2017
};


DebugCommandProcessor.prototype.scopeRequest_ = function(request, response) {
2018 2019
  // Get the frame or function for which the scope is requested.
  var scope_holder = this.scopeHolderForScopeRequest_(request);
2020 2021 2022 2023 2024

  // With no scope argument just return top scope.
  var scope_index = 0;
  if (request.arguments && !IS_UNDEFINED(request.arguments.number)) {
    scope_index = %ToNumber(request.arguments.number);
2025
    if (scope_index < 0 || scope_holder.scopeCount() <= scope_index) {
2026 2027 2028 2029
      return response.failed('Invalid scope number');
    }
  }

2030
  response.body = scope_holder.scope(scope_index);
2031 2032 2033
};


2034 2035 2036 2037 2038 2039 2040 2041 2042
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;
2043
  var disable_break = request.arguments.disable_break;
2044
  var additional_context = request.arguments.additional_context;
2045 2046 2047 2048 2049 2050 2051 2052

  // The expression argument could be an integer so we convert it to a
  // string.
  try {
    expression = String(expression);
  } catch(e) {
    return response.failed('Failed to convert expression argument to string');
  }
2053 2054 2055 2056 2057

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

2059 2060 2061
  var additional_context_object;
  if (additional_context) {
    additional_context_object = {};
2062 2063 2064
    for (var i = 0; i < additional_context.length; i++) {
      var mapping = additional_context[i];
      if (!IS_STRING(mapping.name) || !IS_NUMBER(mapping.handle)) {
2065
        return response.failed("Context element #" + i +
2066
            " must contain name:string and handle:number");
2067
      }
2068
      var context_value_mirror = LookupMirror(mapping.handle);
2069
      if (!context_value_mirror) {
2070 2071
        return response.failed("Context object '" + mapping.name +
            "' #" + mapping.handle + "# not found");
2072
      }
2073
      additional_context_object[mapping.name] = context_value_mirror.value();
2074 2075
    }
  }
2076 2077 2078 2079

  // Global evaluate.
  if (global) {
    // Evaluate in the global context.
2080 2081
    response.body = this.exec_state_.evaluateGlobal(
        expression, Boolean(disable_break), additional_context_object);
2082 2083 2084
    return;
  }

2085 2086 2087 2088 2089
  // Default value for disable_break is true.
  if (IS_UNDEFINED(disable_break)) {
    disable_break = true;
  }

2090 2091 2092 2093 2094
  // No frames no evaluate in frame.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No frames');
  }

2095 2096 2097
  // Check whether a frame was specified.
  if (!IS_UNDEFINED(frame)) {
    var frame_number = %ToNumber(frame);
2098
    if (frame_number < 0 || frame_number >= this.exec_state_.frameCount()) {
2099 2100 2101
      return response.failed('Invalid frame "' + frame + '"');
    }
    // Evaluate in the specified frame.
2102
    response.body = this.exec_state_.frame(frame_number).evaluate(
2103
        expression, Boolean(disable_break), additional_context_object);
2104 2105 2106
    return;
  } else {
    // Evaluate in the selected frame.
2107
    response.body = this.exec_state_.frame().evaluate(
2108
        expression, Boolean(disable_break), additional_context_object);
2109 2110 2111 2112 2113
    return;
  }
};


2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
DebugCommandProcessor.prototype.getobjRequest_ = function(request, response) {
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }

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

  // Check for legal arguments.
  if (IS_UNDEFINED(obj_id)) {
    return response.failed('Argument "obj_id" missing');
  }

  // Dump the object.
  response.body = MakeMirror(%GetLOLObj(obj_id));
};


2132 2133 2134 2135 2136 2137
DebugCommandProcessor.prototype.lookupRequest_ = function(request, response) {
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }

  // Pull out arguments.
2138
  var handles = request.arguments.handles;
2139 2140

  // Check for legal arguments.
2141 2142
  if (IS_UNDEFINED(handles)) {
    return response.failed('Argument "handles" missing');
2143 2144
  }

2145 2146 2147 2148 2149
  // Set 'includeSource' option for script lookup.
  if (!IS_UNDEFINED(request.arguments.includeSource)) {
    includeSource = %ToBoolean(request.arguments.includeSource);
    response.setOption('includeSource', includeSource);
  }
2150

2151 2152 2153 2154 2155 2156 2157 2158 2159
  // 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;
2160
  }
2161
  response.body = mirrors;
2162 2163 2164
};


2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
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');
  }
};


2200
DebugCommandProcessor.prototype.sourceRequest_ = function(request, response) {
2201 2202 2203 2204 2205
  // No frames no source.
  if (this.exec_state_.frameCount() == 0) {
    return response.failed('No source');
  }

2206 2207
  var from_line;
  var to_line;
2208
  var frame = this.exec_state_.frame();
2209 2210 2211 2212 2213 2214 2215
  if (request.arguments) {
    // Pull out arguments.
    from_line = request.arguments.fromLine;
    to_line = request.arguments.toLine;

    if (!IS_UNDEFINED(request.arguments.frame)) {
      var frame_number = %ToNumber(request.arguments.frame);
2216
      if (frame_number < 0 || frame_number >= this.exec_state_.frameCount()) {
2217 2218
        return response.failed('Invalid frame "' + frame + '"');
      }
2219
      frame = this.exec_state_.frame(frame_number);
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
    }
  }

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

  // Get the source slice and fill it into the response.
  var slice = script.sourceSlice(from_line, to_line);
  if (!slice) {
    return response.failed('Invalid line interval');
  }
  response.body = {};
  response.body.source = slice.sourceText();
  response.body.fromLine = slice.from_line;
  response.body.toLine = slice.to_line;
  response.body.fromPosition = slice.from_position;
  response.body.toPosition = slice.to_position;
  response.body.totalLines = script.lineCount();
};


DebugCommandProcessor.prototype.scriptsRequest_ = function(request, response) {
  var types = ScriptTypeFlag(Debug.ScriptType.Normal);
2246
  var includeSource = false;
2247
  var idsToInclude = null;
2248 2249 2250 2251 2252
  if (request.arguments) {
    // Pull out arguments.
    if (!IS_UNDEFINED(request.arguments.types)) {
      types = %ToNumber(request.arguments.types);
      if (isNaN(types) || types < 0) {
2253 2254
        return response.failed('Invalid types "' +
                               request.arguments.types + '"');
2255 2256
      }
    }
2257

2258 2259
    if (!IS_UNDEFINED(request.arguments.includeSource)) {
      includeSource = %ToBoolean(request.arguments.includeSource);
2260
      response.setOption('includeSource', includeSource);
2261
    }
2262

2263 2264 2265 2266 2267 2268 2269
    if (IS_ARRAY(request.arguments.ids)) {
      idsToInclude = {};
      var ids = request.arguments.ids;
      for (var i = 0; i < ids.length; i++) {
        idsToInclude[ids[i]] = true;
      }
    }
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279

    var filterStr = null;
    var filterNum = null;
    if (!IS_UNDEFINED(request.arguments.filter)) {
      var num = %ToNumber(request.arguments.filter);
      if (!isNaN(num)) {
        filterNum = num;
      }
      filterStr = request.arguments.filter;
    }
2280 2281 2282
  }

  // Collect all scripts in the heap.
2283
  var scripts = %DebugGetLoadedScripts();
2284 2285 2286 2287

  response.body = [];

  for (var i = 0; i < scripts.length; i++) {
2288 2289 2290
    if (idsToInclude && !idsToInclude[scripts[i].id]) {
      continue;
    }
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
    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;
    }
2306
    if (types & ScriptTypeFlag(scripts[i].type)) {
2307
      response.body.push(MakeMirror(scripts[i]));
2308 2309 2310 2311 2312
    }
  }
};


2313 2314 2315 2316 2317 2318 2319 2320 2321 2322
DebugCommandProcessor.prototype.threadsRequest_ = function(request, response) {
  // Get the number of threads.
  var total_threads = this.exec_state_.threadCount();

  // Get information for all threads.
  var threads = [];
  for (var i = 0; i < total_threads; i++) {
    var details = %GetThreadDetails(this.exec_state_.break_id, i);
    var thread_info = { current: details[0],
                        id: details[1]
2323
                      };
2324 2325 2326 2327 2328 2329 2330
    threads.push(thread_info);
  }

  // Create the response body.
  response.body = {
    totalThreads: total_threads,
    threads: threads
2331
  };
2332 2333 2334
};


2335 2336 2337 2338 2339
DebugCommandProcessor.prototype.suspendRequest_ = function(request, response) {
  response.running = false;
};


2340 2341 2342
DebugCommandProcessor.prototype.versionRequest_ = function(request, response) {
  response.body = {
    V8Version: %GetV8Version()
2343
  };
2344 2345 2346
};


2347 2348
DebugCommandProcessor.prototype.profileRequest_ = function(request, response) {
  if (request.arguments.command == 'resume') {
2349
    %ProfilerResume();
2350
  } else if (request.arguments.command == 'pause') {
2351
    %ProfilerPause();
2352 2353 2354 2355 2356 2357 2358
  } else {
    return response.failed('Unknown command');
  }
  response.body = {};
};


2359 2360
DebugCommandProcessor.prototype.changeLiveRequest_ = function(
    request, response) {
2361
  if (!Debug.LiveEdit) {
2362 2363 2364 2365 2366 2367
    return response.failed('LiveEdit feature is not supported');
  }
  if (!request.arguments) {
    return response.failed('Missing arguments');
  }
  var script_id = request.arguments.script_id;
2368
  var preview_only = !!request.arguments.preview_only;
2369

2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
  var scripts = %DebugGetLoadedScripts();

  var the_script = null;
  for (var i = 0; i < scripts.length; i++) {
    if (scripts[i].id == script_id) {
      the_script = scripts[i];
    }
  }
  if (!the_script) {
    response.failed('Script not found');
    return;
  }
2382

2383
  var change_log = new Array();
2384

2385 2386
  if (!IS_STRING(request.arguments.new_source)) {
    throw "new_source argument expected";
2387 2388
  }

2389
  var new_source = request.arguments.new_source;
2390

2391 2392 2393
  var result_description = Debug.LiveEdit.SetScriptSource(the_script,
      new_source, preview_only, change_log);
  response.body = {change_log: change_log, result: result_description};
2394

2395 2396 2397
  if (!preview_only && !this.running_ && result_description.stack_modified) {
    response.body.stepin_recommended = true;
  }
2398 2399 2400
};


2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430
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 });
    }
  }
2431
};
2432 2433


2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
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 };
};


2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
DebugCommandProcessor.prototype.lolCaptureRequest_ =
    function(request, response) {
  response.body = %CaptureLOL();
};


DebugCommandProcessor.prototype.lolDeleteRequest_ =
    function(request, response) {
  var id = request.arguments.id;
  var result = %DeleteLOL(id);
  if (result) {
    response.body = { id: id };
  } else {
    response.failed('Failed to delete: live object list ' + id + ' not found.');
  }
};


DebugCommandProcessor.prototype.lolDiffRequest_ = function(request, response) {
  var id1 = request.arguments.id1;
  var id2 = request.arguments.id2;
  var verbose = request.arguments.verbose;
  var filter = request.arguments.filter;
  if (verbose === true) {
    var start = request.arguments.start;
    var count = request.arguments.count;
    response.body = %DumpLOL(id1, id2, start, count, filter);
  } else {
    response.body = %SummarizeLOL(id1, id2, filter);
  }
};


DebugCommandProcessor.prototype.lolGetIdRequest_ = function(request, response) {
  var address = request.arguments.address;
  response.body = {};
  response.body.id = %GetLOLObjId(address);
};


DebugCommandProcessor.prototype.lolInfoRequest_ = function(request, response) {
  var start = request.arguments.start;
  var count = request.arguments.count;
  response.body = %InfoLOL(start, count);
};


DebugCommandProcessor.prototype.lolResetRequest_ = function(request, response) {
  %ResetLOL();
};


DebugCommandProcessor.prototype.lolRetainersRequest_ =
    function(request, response) {
  var id = request.arguments.id;
  var verbose = request.arguments.verbose;
  var start = request.arguments.start;
  var count = request.arguments.count;
  var filter = request.arguments.filter;

  response.body = %GetLOLObjRetainers(id, Mirror.prototype, verbose,
                                      start, count, filter);
};


DebugCommandProcessor.prototype.lolPathRequest_ = function(request, response) {
  var id1 = request.arguments.id1;
  var id2 = request.arguments.id2;
  response.body = {};
  response.body.path = %GetLOLPath(id1, id2, Mirror.prototype);
};


DebugCommandProcessor.prototype.lolPrintRequest_ = function(request, response) {
  var id = request.arguments.id;
  response.body = {};
  response.body.dump = %PrintLOLObj(id);
};
2531 2532


2533 2534 2535 2536
// Check whether the previously processed command caused the VM to become
// running.
DebugCommandProcessor.prototype.isRunning = function() {
  return this.running_;
2537
};
2538 2539 2540


DebugCommandProcessor.prototype.systemBreak = function(cmd, args) {
2541
  return %SystemBreak();
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
};


function NumberToHex8Str(n) {
  var r = "";
  for (var i = 0; i < 8; ++i) {
    var c = hexCharArray[n & 0x0F];  // hexCharArray is defined in uri.js
    r = c + r;
    n = n >>> 4;
  }
  return r;
2553
}
2554 2555 2556


/**
2557 2558 2559 2560 2561 2562 2563
 * 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.
2564 2565
 * @param {MirrorSerializer} mirror_serializer The serializer to use if any
 *     mirror objects are encountered.
2566
 * @return {Object} Protocol object value.
2567
 */
2568 2569
function ObjectToProtocolObject_(object, mirror_serializer) {
  var content = {};
2570 2571 2572 2573
  for (var key in object) {
    // Only consider string keys.
    if (typeof key == 'string') {
      // Format the value based on its type.
2574 2575
      var property_value_json = ValueToProtocolValue_(object[key],
                                                      mirror_serializer);
2576
      // Add the property if relevant.
2577 2578
      if (!IS_UNDEFINED(property_value_json)) {
        content[key] = property_value_json;
2579 2580 2581
      }
    }
  }
2582

2583
  return content;
2584
}
2585

2586

2587
/**
2588 2589 2590
 * 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.
2591 2592
 * @param {MirrorSerializer} mirror_serializer The serializer to use if any
 *     mirror objects are encountered.
2593
 * @return {Array} Protocol array value.
2594
 */
2595 2596
function ArrayToProtocolArray_(array, mirror_serializer) {
  var json = [];
2597
  for (var i = 0; i < array.length; i++) {
2598 2599 2600 2601 2602 2603 2604
    json.push(ValueToProtocolValue_(array[i], mirror_serializer));
  }
  return json;
}


/**
2605
 * Convert a value to its debugger protocol representation.
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
 * @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;
2629
      break;
2630 2631 2632

    default:
      json = null;
2633 2634
  }
  return json;
2635
}