d8.js 39.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// How crappy is it that I have to implement completely basic stuff
// like this myself?  Answer: very.
String.prototype.startsWith = function (str) {
  if (str.length > this.length)
    return false;
  return this.substr(0, str.length) == str;
34 35 36 37 38
}

function log10(num) {
  return Math.log(num)/Math.log(10);
}
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

function ToInspectableObject(obj) {
  if (!obj && typeof obj === 'object') {
    return void 0;
  } else {
    return Object(obj);
  }
}

function GetCompletions(global, last, full) {
  var full_tokens = full.split();
  full = full_tokens.pop();
  var parts = full.split('.');
  parts.pop();
  var current = global;
  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];
    var next = current[part];
    if (!next)
      return [];
    current = next;
  }
  var result = [];
  current = ToInspectableObject(current);
  while (typeof current !== 'undefined') {
    var mirror = new $debug.ObjectMirror(current);
    var properties = mirror.properties();
    for (var i = 0; i < properties.length; i++) {
      var name = properties[i].name();
      if (typeof name === 'string' && name.startsWith(last))
        result.push(name);
    }
    current = ToInspectableObject(current.__proto__);
  }
  return result;
}
75 76 77 78 79 80 81


// Global object holding debugger related constants and state.
const Debug = {};


// Debug events which can occour in the V8 JavaScript engine. These originate
82
// from the API include file v8-debug.h.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
Debug.DebugEvent = { Break: 1,
                     Exception: 2,
                     NewFunction: 3,
                     BeforeCompile: 4,
                     AfterCompile: 5 };


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


// Current debug state.
const kNoFrame = -1;
Debug.State = {
  currentFrame: kNoFrame,
  currentSourceLine: -1
}
102
var trace_compile = false;  // Tracing all compile events?
103 104


105 106 107 108
// Process a debugger JSON message into a display text and a running status.
// This function returns an object with properties "text" and "running" holding
// this information.
function DebugMessageDetails(message) {
109
  // Convert the JSON string to an object.
110 111 112 113 114 115 116 117 118 119 120 121 122 123
  var response = new ProtocolPackage(message);

  if (response.type() == 'event') {
    return DebugEventDetails(response);
  } else {
    return DebugResponseDetails(response);
  }
}

function DebugEventDetails(response) {
  details = {text:'', running:false}

  // Get the running state.
  details.running = response.running();
124 125

  var body = response.body();
126
  var result = '';
127 128 129
  switch (response.event()) {
    case 'break':
      if (body.breakpoints) {
130
        result += 'breakpoint';
131
        if (body.breakpoints.length > 1) {
132
          result += 's';
133
        }
134
        result += ' #';
135
        for (var i = 0; i < body.breakpoints.length; i++) {
136
          if (i > 0) {
137
            result += ', #';
138
          }
139
          result += body.breakpoints[i];
140
        }
141
      } else {
142
        result += 'break';
143
      }
144 145 146 147 148 149
      result += ' in ';
      result += body.invocationText;
      result += ', ';
      result += SourceInfo(body);
      result += '\n';
      result += SourceUnderline(body.sourceLineText, body.sourceColumn);
150
      Debug.State.currentSourceLine = body.sourceLine;
151
      Debug.State.currentFrame = 0;
152 153
      details.text = result;
      break;
154 155 156
      
    case 'exception':
      if (body.uncaught) {
157
        result += 'Uncaught: ';
158
      } else {
159
        result += 'Exception: ';
160
      }
161 162 163
      result += '"';
      result += body.exception.text;
      result += '"';
164
      if (body.sourceLine >= 0) {
165 166 167 168
        result += ', ';
        result += SourceInfo(body);
        result += '\n';
        result += SourceUnderline(body.sourceLineText, body.sourceColumn);
169
        Debug.State.currentSourceLine = body.sourceLine;
170 171
        Debug.State.currentFrame = 0;
      } else {
172
        result += ' (empty stack)';
173 174 175
        Debug.State.currentSourceLine = -1;
        Debug.State.currentFrame = kNoFrame;
      }
176 177
      details.text = result;
      break;
178 179

    case 'afterCompile':
180
      if (trace_compile) {
181
        result = 'Source ' + body.script.name + ' compiled:\n'
182
        var source = body.script.source;
183
        if (!(source[source.length - 1] == '\n')) {
184
          result += source;
185
        } else {
186
          result += source.substring(0, source.length - 1);
187 188
        }
      }
189 190 191 192 193
      details.text = result;
      break;

    default:
      details.text = 'Unknown debug event ' + response.event();
194
  }
195 196

  return details;
197 198 199
};


200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
function SourceInfo(body) {
  var result = '';
  
  if (body.script) {
    if (body.script.name) {
      result += body.script.name;
    } else {
      result += '[unnamed]';
    }
  }
  result += ' line ';
  result += body.sourceLine + 1;
  result += ' column ';
  result += body.sourceColumn + 1;
  
  return result;
}


219 220 221 222 223
function SourceUnderline(source_text, position) {
  if (!source_text) {
    return;
  }

224 225 226
  // Create an underline with a caret pointing to the source position. If the
  // source contains a tab character the underline will have a tab character in
  // the same place otherwise the underline will have a space character.
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
  var underline = '';
  for (var i = 0; i < position; i++) {
    if (source_text[i] == '\t') {
      underline += '\t';
    } else {
      underline += ' ';
    }
  }
  underline += '^';

  // Return the source line text with the underline beneath.
  return source_text + '\n' + underline;
};


// Converts a text command to a JSON request.
function DebugCommandToJSONRequest(cmd_line) {
  return new DebugRequest(cmd_line).JSONRequest();
};


function DebugRequest(cmd_line) {
  // If the very first character is a { assume that a JSON request have been
  // entered as a command. Converting that to a JSON request is trivial.
  if (cmd_line && cmd_line.length > 0 && cmd_line.charAt(0) == '{') {
    this.request_ = cmd_line;
    return;
  }

  // Trim string for leading and trailing whitespace.
  cmd_line = cmd_line.replace(/^\s+|\s+$/g, '');

  // Find the command.
  var pos = cmd_line.indexOf(' ');
  var cmd;
  var args;
  if (pos == -1) {
    cmd = cmd_line;
    args = '';
  } else {
    cmd = cmd_line.slice(0, pos);
    args = cmd_line.slice(pos).replace(/^\s+|\s+$/g, '');
  }

  // Switch on command.
  switch (cmd) {
    case 'continue':
    case 'c':
      this.request_ = this.continueCommandToJSONRequest_(args);
      break;

    case 'step':
    case 's':
      this.request_ = this.stepCommandToJSONRequest_(args);
      break;

    case 'backtrace':
    case 'bt':
      this.request_ = this.backtraceCommandToJSONRequest_(args);
      break;
      
    case 'frame':
    case 'f':
      this.request_ = this.frameCommandToJSONRequest_(args);
      break;
      
    case 'print':
    case 'p':
      this.request_ = this.printCommandToJSONRequest_(args);
      break;

298 299 300 301
    case 'dir':
      this.request_ = this.dirCommandToJSONRequest_(args);
      break;

302 303 304 305 306 307 308 309
    case 'references':
      this.request_ = this.referencesCommandToJSONRequest_(args);
      break;

    case 'instances':
      this.request_ = this.instancesCommandToJSONRequest_(args);
      break;

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    case 'source':
      this.request_ = this.sourceCommandToJSONRequest_(args);
      break;
      
    case 'scripts':
      this.request_ = this.scriptsCommandToJSONRequest_(args);
      break;
      
    case 'break':
    case 'b':
      this.request_ = this.breakCommandToJSONRequest_(args);
      break;
      
    case 'clear':
      this.request_ = this.clearCommandToJSONRequest_(args);
      break;

327 328 329 330
    case 'threads':
      this.request_ = this.threadsCommandToJSONRequest_(args);
      break;

331 332 333 334 335 336
    case 'trace':
      // Return undefined to indicate command handled internally (no JSON).
      this.request_ = void 0;
      this.traceCommand_(args);
      break;

337 338 339
    case 'help':
    case '?':
      this.helpCommand_(args);
340 341
      // Return undefined to indicate command handled internally (no JSON).
      this.request_ = void 0;
342 343 344 345 346
      break;

    default:
      throw new Error('Unknown command "' + cmd + '"');
  }
347 348
  
  last_cmd = cmd;
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 386 387 388 389
}

DebugRequest.prototype.JSONRequest = function() {
  return this.request_;
}


function RequestPacket(command) {
  this.seq = 0;
  this.type = 'request';
  this.command = command;
}


RequestPacket.prototype.toJSONProtocol = function() {
  // Encode the protocol header.
  var json = '{';
  json += '"seq":' + this.seq;
  json += ',"type":"' + this.type + '"';
  if (this.command) {
    json += ',"command":' + StringToJSON_(this.command);
  }
  if (this.arguments) {
    json += ',"arguments":';
    // Encode the arguments part.
    if (this.arguments.toJSONProtocol) {
      json += this.arguments.toJSONProtocol()
    } else {
      json += SimpleObjectToJSON_(this.arguments);
    }
  }
  json += '}';
  return json;
}


DebugRequest.prototype.createRequest = function(command) {
  return new RequestPacket(command);
};


390 391 392 393 394
// Create a JSON request for the evaluation command.
DebugRequest.prototype.makeEvaluateJSONRequest_ = function(expression) {
  // Check if the expression is a handle id in the form #<handle>#.
  var handle_match = expression.match(/^#([0-9]*)#$/);
  if (handle_match) {
395
    // Build a lookup request.
396 397 398 399 400 401 402 403 404
    var request = this.createRequest('lookup');
    request.arguments = {};
    request.arguments.handle = parseInt(handle_match[1]);
    return request.toJSONProtocol();
  } else {
    // Build an evaluate request.
    var request = this.createRequest('evaluate');
    request.arguments = {};
    request.arguments.expression = expression;
405 406 407 408
    // Request a global evaluation if there is no current frame.
    if (Debug.State.currentFrame == kNoFrame) {
      request.arguments.global = true;
    }
409 410 411 412 413
    return request.toJSONProtocol();
  }
};


414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
// Create a JSON request for the references/instances command.
DebugRequest.prototype.makeReferencesJSONRequest_ = function(handle, type) {
  // Build a references request.
  var handle_match = handle.match(/^#([0-9]*)#$/);
  if (handle_match) {
    var request = this.createRequest('references');
    request.arguments = {};
    request.arguments.type = type;
    request.arguments.handle = parseInt(handle_match[1]);
    return request.toJSONProtocol();
  } else {
    throw new Error('Invalid object id.');
  }
};

429

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
// Create a JSON request for the continue command.
DebugRequest.prototype.continueCommandToJSONRequest_ = function(args) {
  var request = this.createRequest('continue');
  return request.toJSONProtocol();
};


// Create a JSON request for the step command.
DebugRequest.prototype.stepCommandToJSONRequest_ = function(args) {
  // Requesting a step is through the continue command with additional
  // arguments.
  var request = this.createRequest('continue');
  request.arguments = {};

  // Process arguments if any.
  if (args && args.length > 0) {
    args = args.split(/\s*[ ]+\s*/g);

    if (args.length > 2) {
      throw new Error('Invalid step arguments.');
    }

    if (args.length > 0) {
      // Get step count argument if any.
      if (args.length == 2) {
        var stepcount = parseInt(args[1]);
        if (isNaN(stepcount) || stepcount <= 0) {
          throw new Error('Invalid step count argument "' + args[0] + '".');
        }
        request.arguments.stepcount = stepcount;
      }

      // Get the step action.
      switch (args[0]) {
        case 'in':
        case 'i':
          request.arguments.stepaction = 'in';
          break;
          
        case 'min':
        case 'm':
          request.arguments.stepaction = 'min';
          break;
          
        case 'next':
        case 'n':
          request.arguments.stepaction = 'next';
          break;
          
        case 'out':
        case 'o':
          request.arguments.stepaction = 'out';
          break;
          
        default:
          throw new Error('Invalid step argument "' + args[0] + '".');
      }
    }
  } else {
    // Default is step next.
    request.arguments.stepaction = 'next';
  }

  return request.toJSONProtocol();
};


// Create a JSON request for the backtrace command.
DebugRequest.prototype.backtraceCommandToJSONRequest_ = function(args) {
  // Build a backtrace request from the text command.
  var request = this.createRequest('backtrace');
501 502 503 504 505 506
  
  // Default is to show top 10 frames.
  request.arguments = {};
  request.arguments.fromFrame = 0;
  request.arguments.toFrame = 10;

507
  args = args.split(/\s*[ ]+\s*/g);
508 509 510 511 512 513 514 515 516 517 518 519 520
  if (args.length == 1 && args[0].length > 0) {
    var frameCount = parseInt(args[0]);
    if (frameCount > 0) {
      // Show top frames.
      request.arguments.fromFrame = 0;
      request.arguments.toFrame = frameCount;
    } else {
      // Show bottom frames.
      request.arguments.fromFrame = 0;
      request.arguments.toFrame = -frameCount;
      request.arguments.bottom = true;
    }
  } else if (args.length == 2) {
521 522 523 524 525 526 527 528 529 530 531 532
    var fromFrame = parseInt(args[0]);
    var toFrame = parseInt(args[1]);
    if (isNaN(fromFrame) || fromFrame < 0) {
      throw new Error('Invalid start frame argument "' + args[0] + '".');
    }
    if (isNaN(toFrame) || toFrame < 0) {
      throw new Error('Invalid end frame argument "' + args[1] + '".');
    }
    if (fromFrame > toFrame) {
      throw new Error('Invalid arguments start frame cannot be larger ' +
                      'than end frame.');
    }
533
    // Show frame range.
534 535
    request.arguments.fromFrame = fromFrame;
    request.arguments.toFrame = toFrame + 1;
536 537
  } else if (args.length > 2) {
    throw new Error('Invalid backtrace arguments.');
538
  }
539

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
  return request.toJSONProtocol();
};


// Create a JSON request for the frame command.
DebugRequest.prototype.frameCommandToJSONRequest_ = function(args) {
  // Build a frame request from the text command.
  var request = this.createRequest('frame');
  args = args.split(/\s*[ ]+\s*/g);
  if (args.length > 0 && args[0].length > 0) {
    request.arguments = {};
    request.arguments.number = args[0];
  }
  return request.toJSONProtocol();
};


// Create a JSON request for the print command.
DebugRequest.prototype.printCommandToJSONRequest_ = function(args) {
559
  // Build an evaluate request from the text command.
560 561 562
  if (args.length == 0) {
    throw new Error('Missing expression.');
  }
563 564
  return this.makeEvaluateJSONRequest_(args);
};
565 566


567 568 569 570 571 572 573
// Create a JSON request for the dir command.
DebugRequest.prototype.dirCommandToJSONRequest_ = function(args) {
  // Build an evaluate request from the text command.
  if (args.length == 0) {
    throw new Error('Missing expression.');
  }
  return this.makeEvaluateJSONRequest_(args);
574 575 576
};


577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
// Create a JSON request for the references command.
DebugRequest.prototype.referencesCommandToJSONRequest_ = function(args) {
  // Build an evaluate request from the text command.
  if (args.length == 0) {
    throw new Error('Missing object id.');
  }
  
  return this.makeReferencesJSONRequest_(args, 'referencedBy');
};


// Create a JSON request for the instances command.
DebugRequest.prototype.instancesCommandToJSONRequest_ = function(args) {
  // Build an evaluate request from the text command.
  if (args.length == 0) {
    throw new Error('Missing object id.');
  }
  
  // Build a references request.
  return this.makeReferencesJSONRequest_(args, 'constructedBy');
};


600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
// Create a JSON request for the source command.
DebugRequest.prototype.sourceCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('source');

  // Default is ten lines starting five lines before the current location.
  var from = Debug.State.currentSourceLine - 5;
  var lines = 10;

  // Parse the arguments.
  args = args.split(/\s*[ ]+\s*/g);
  if (args.length > 1 && args[0].length > 0 && args[1].length > 0) {
    from = parseInt(args[0]) - 1;
    lines = parseInt(args[1]);
  } else if (args.length > 0 && args[0].length > 0) {
    from = parseInt(args[0]) - 1;
  }

  if (from < 0) from = 0;
  if (lines < 0) lines = 10;

  // Request source arround current source location.
  request.arguments = {};
  request.arguments.fromLine = from;
  request.arguments.toLine = from + lines;

  return request.toJSONProtocol();
};


// Create a JSON request for the scripts command.
DebugRequest.prototype.scriptsCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('scripts');

  // Process arguments if any.
  if (args && args.length > 0) {
    args = args.split(/\s*[ ]+\s*/g);

    if (args.length > 1) {
      throw new Error('Invalid scripts arguments.');
    }

    request.arguments = {};
    switch (args[0]) {
      case 'natives':
        request.arguments.types = ScriptTypeFlag(Debug.ScriptType.Native);
        break;
        
      case 'extensions':
        request.arguments.types = ScriptTypeFlag(Debug.ScriptType.Extension);
        break;
        
      case 'all':
        request.arguments.types =
            ScriptTypeFlag(Debug.ScriptType.Normal) |
            ScriptTypeFlag(Debug.ScriptType.Native) |
            ScriptTypeFlag(Debug.ScriptType.Extension);
        break;
        
      default:
        throw new Error('Invalid argument "' + args[0] + '".');
    }
  }

  return request.toJSONProtocol();
};


// Create a JSON request for the break command.
DebugRequest.prototype.breakCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('setbreakpoint');

  // Process arguments if any.
  if (args && args.length > 0) {
    var target = args;
677 678 679
    var type = 'function';
    var line;
    var column;
680
    var condition;
681
    var pos;
682

683 684
    // Check for breakpoint condition.
    pos = args.indexOf(' ');
685 686 687 688 689
    if (pos > 0) {
      target = args.substring(0, pos);
      condition = args.substring(pos + 1, args.length);
    }

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    // Check for script breakpoint (name:line[:column]). If no ':' in break
    // specification it is considered a function break point.
    pos = target.indexOf(':');
    if (pos > 0) {
      type = 'script';
      var tmp = target.substring(pos + 1, target.length);
      target = target.substring(0, pos);
      
      // Check for both line and column.
      pos = tmp.indexOf(':');
      if (pos > 0) {
        column = parseInt(tmp.substring(pos + 1, tmp.length)) - 1;
        line = parseInt(tmp.substring(0, pos)) - 1;
      } else {
        line = parseInt(tmp) - 1;
      }
    } else if (target[0] == '#' && target[target.length - 1] == '#') {
      type = 'handle';
      target = target.substring(1, target.length - 1);
    } else {
      type = 'function';
    }
  
713
    request.arguments = {};
714
    request.arguments.type = type;
715
    request.arguments.target = target;
716 717
    request.arguments.line = line;
    request.arguments.column = column;
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
    request.arguments.condition = condition;
  } else {
    throw new Error('Invalid break arguments.');
  }

  return request.toJSONProtocol();
};


// Create a JSON request for the clear command.
DebugRequest.prototype.clearCommandToJSONRequest_ = function(args) {
  // Build a evaluate request from the text command.
  var request = this.createRequest('clearbreakpoint');

  // Process arguments if any.
  if (args && args.length > 0) {
    request.arguments = {};
    request.arguments.breakpoint = parseInt(args);
  } else {
    throw new Error('Invalid break arguments.');
  }

  return request.toJSONProtocol();
};


744 745 746 747 748 749 750 751
// Create a JSON request for the threads command.
DebugRequest.prototype.threadsCommandToJSONRequest_ = function(args) {
  // Build a threads request from the text command.
  var request = this.createRequest('threads');
  return request.toJSONProtocol();
};


752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
// Handle the trace command.
DebugRequest.prototype.traceCommand_ = function(args) {
  // Process arguments.
  if (args && args.length > 0) {
    if (args == 'compile') {
      trace_compile = !trace_compile;
      print('Tracing of compiled scripts ' + (trace_compile ? 'on' : 'off'));
    } else {
      throw new Error('Invalid trace arguments.');
    }
  } else {
    throw new Error('Invalid trace arguments.');
  }
}

// Handle the help command.
768 769 770 771 772 773 774
DebugRequest.prototype.helpCommand_ = function(args) {
  // Help os quite simple.
  if (args && args.length > 0) {
    print('warning: arguments to \'help\' are ignored');
  }

  print('break location [condition]');
775 776 777
  print('  break on named function: location is a function name');
  print('  break on function: location is #<id>#');
  print('  break on script position: location is name:line[:column]');
778
  print('clear <breakpoint #>');
779
  print('backtrace [n] | [-n] | [from to]');
780 781 782 783 784 785
  print('frame <frame #>');
  print('step [in | next | out| min [step count]]');
  print('print <expression>');
  print('source [from line [num lines]]');
  print('scripts');
  print('continue');
786
  print('trace compile');
787 788 789 790
  print('help');
}


791 792 793 794 795
function formatHandleReference_(value) {
  return '#' + value.handle() + '#';
}


796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
function formatObject_(value, include_properties) {
  var result = '';
  result += formatHandleReference_(value);
  result += ', type: object'
  result += ', constructor ';
  var ctor = value.constructorFunctionValue();
  result += formatHandleReference_(ctor);
  result += ', __proto__ ';
  var proto = value.protoObjectValue();
  result += formatHandleReference_(proto);
  result += ', ';
  result += value.propertyCount();
  result +=  ' properties.';
  if (include_properties) {
    result +=  '\n';
    for (var i = 0; i < value.propertyCount(); i++) {
      result += '  ';
      result += value.propertyName(i);
      result += ': ';
      var property_value = value.propertyValue(i);
      if (property_value && property_value.type()) {
        result += property_value.type();
      } else {
        result += '<no type>';
      }
      result += ' ';
      result += formatHandleReference_(property_value);
      result += '\n';
    }
  }
  return result;
}


830
// Convert a JSON response to text for display in a text based debugger.
831
function DebugResponseDetails(response) {
832 833 834
  details = {text:'', running:false}

  try {
835 836
    if (!response.success()) {
      details.text = response.message();
837 838 839 840
      return details;
    }

    // Get the running state.
841
    details.running = response.running();
842

843 844 845
    var body = response.body();
    var result = '';
    switch (response.command()) {
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
      case 'setbreakpoint':
        result = 'set breakpoint #';
        result += body.breakpoint;
        details.text = result;
        break;
        
      case 'clearbreakpoint':
        result = 'cleared breakpoint #';
        result += body.breakpoint;
        details.text = result;
        break;
        
      case 'backtrace':
        if (body.totalFrames == 0) {
          result = '(empty stack)';
        } else {
          var result = 'Frames #' + body.fromFrame + ' to #' +
              (body.toFrame - 1) + ' of ' + body.totalFrames + '\n';
          for (i = 0; i < body.frames.length; i++) {
            if (i != 0) result += '\n';
            result += body.frames[i].text;
          }
        }
        details.text = result;
        break;
        
      case 'frame':
873 874 875 876
        details.text = SourceUnderline(body.sourceLineText,
                                       body.column);
        Debug.State.currentSourceLine = body.line;
        Debug.State.currentFrame = body.index;
877 878 879
        break;
        
      case 'evaluate':
880 881
      case 'lookup':
        if (last_cmd == 'p' || last_cmd == 'print') {
882
          result = body.text;
883 884 885
        } else {
          var value = response.bodyValue();
          if (value.isObject()) {
886
            result += formatObject_(value, true);
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
          } else {
            result += 'type: ';
            result += value.type();
            if (!value.isUndefined() && !value.isNull()) {
              result += ', ';
              if (value.isString()) {
                result += '"';
              }
              result += value.value();
              if (value.isString()) {
                result += '"';
              }
            }
            result += '\n';
          }
        }
        details.text = result;
904
        break;
905 906 907 908 909 910 911 912 913 914 915 916

      case 'references':
        var count = body.length;
        result += 'found ' + count + ' objects';
        result += '\n';
        for (var i = 0; i < count; i++) {
          var value = response.bodyValue(i);
          result += formatObject_(value, false);
          result += '\n';
        }
        details.text = result;
        break;
917 918 919
        
      case 'source':
        // Get the source from the response.
920 921
        var source = body.source;
        var from_line = body.fromLine + 1;
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
        var lines = source.split('\n');
        var maxdigits = 1 + Math.floor(log10(from_line + lines.length));
        if (maxdigits < 3) {
          maxdigits = 3;
        }
        var result = '';
        for (var num = 0; num < lines.length; num++) {
          // Check if there's an extra newline at the end.
          if (num == (lines.length - 1) && lines[num].length == 0) {
            break;
          }

          var current_line = from_line + num;
          spacer = maxdigits - (1 + Math.floor(log10(current_line)));
          if (current_line == Debug.State.currentSourceLine + 1) {
            for (var i = 0; i < maxdigits; i++) {
              result += '>';
            }
            result += '  ';
          } else {
            for (var i = 0; i < spacer; i++) {
              result += ' ';
            }
            result += current_line + ': ';
          }
          result += lines[num];
          result += '\n';
        }
        details.text = result;
        break;
        
      case 'scripts':
        var result = '';
955
        for (i = 0; i < body.length; i++) {
956
          if (i != 0) result += '\n';
957 958 959 960 961 962
          if (body[i].id) {
            result += body[i].id;
          } else {
            result += '[no id]';
          }
          result += ', ';
963 964
          if (body[i].name) {
            result += body[i].name;
965 966 967 968
          } else {
            result += '[unnamed] ';
          }
          result += ' (lines: ';
969
          result += body[i].lineCount;
970
          result += ', length: ';
971 972
          result += body[i].sourceLength;
          if (body[i].type == Debug.ScriptType.Native) {
973
            result += ', native';
974
          } else if (body[i].type == Debug.ScriptType.Extension) {
975 976
            result += ', extension';
          }
977 978 979 980 981 982 983
          result += '), [';
          var sourceStart = body[i].sourceStart;
          if (sourceStart.length > 40) {
            sourceStart = sourceStart.substring(0, 37) + '...';
          }
          result += sourceStart;
          result += ']';
984 985 986 987
        }
        details.text = result;
        break;

988 989 990 991 992 993 994 995 996 997 998 999
      case 'threads':
        var result = 'Active V8 threads: ' + body.totalThreads + '\n';
        body.threads.sort(function(a, b) { return a.id - b.id; });
        for (i = 0; i < body.threads.length; i++) {
          result += body.threads[i].current ? '*' : ' ';
          result += ' ';
          result += body.threads[i].id;
          result += '\n';
        }
        details.text = result;
        break;

1000 1001 1002 1003
      case 'continue':
        details.text = "(running)";
        break;
        
1004 1005
      default:
        details.text =
1006 1007
            'Response for unknown command \'' + response.command + '\'' +
            ' (' + json_response + ')';
1008 1009 1010 1011 1012 1013 1014 1015 1016
    }
  } catch (e) {
    details.text = 'Error: "' + e + '" formatting response';
  }
  
  return details;
};


1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
/**
 * Protocol packages send from the debugger.
 * @param {string} json - raw protocol packet as JSON string.
 * @constructor
 */
function ProtocolPackage(json) {
  this.packet_ = eval('(' + json + ')');
  this.refs_ = [];
  if (this.packet_.refs) {
    for (var i = 0; i < this.packet_.refs.length; i++) {
      this.refs_[this.packet_.refs[i].handle] = this.packet_.refs[i];
    }
  }
}


/**
 * Get the packet type.
 * @return {String} the packet type
 */
ProtocolPackage.prototype.type = function() {
  return this.packet_.type;
}


/**
 * Get the packet event.
 * @return {Object} the packet event
 */
ProtocolPackage.prototype.event = function() {
  return this.packet_.event;
}


/**
 * Get the packet request sequence.
 * @return {number} the packet request sequence
 */
ProtocolPackage.prototype.requestSeq = function() {
  return this.packet_.request_seq;
}


/**
 * Get the packet request sequence.
 * @return {number} the packet request sequence
 */
ProtocolPackage.prototype.running = function() {
  return this.packet_.running ? true : false;
}


ProtocolPackage.prototype.success = function() {
  return this.packet_.success ? true : false;
}


ProtocolPackage.prototype.message = function() {
  return this.packet_.message;
}


ProtocolPackage.prototype.command = function() {
  return this.packet_.command;
}


ProtocolPackage.prototype.body = function() {
  return this.packet_.body;
}


1089
ProtocolPackage.prototype.bodyValue = function(index) {
1090
  if (index) {
1091
    return new ProtocolValue(this.packet_.body[index], this);
1092 1093
  } else {
    return new ProtocolValue(this.packet_.body, this);
1094
  }
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 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 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
}


ProtocolPackage.prototype.body = function() {
  return this.packet_.body;
}


ProtocolPackage.prototype.lookup = function(handle) {
  var value = this.refs_[handle];
  if (value) {
    return new ProtocolValue(value, this);
  } else {
    return new ProtocolReference(handle);
  }
}


function ProtocolValue(value, packet) {
  this.value_ = value;
  this.packet_ = packet;
}


/**
 * Get the value type.
 * @return {String} the value type
 */
ProtocolValue.prototype.type = function() {
  return this.value_.type;
}


/**
 * Check is the value is a primitive value.
 * @return {boolean} true if the value is primitive
 */
ProtocolValue.prototype.isPrimitive = function() {
  return this.isUndefined() || this.isNull() || this.isBoolean() ||
         this.isNumber() || this.isString();
}


/**
 * Get the object handle.
 * @return {number} the value handle
 */
ProtocolValue.prototype.handle = function() {
  return this.value_.handle;
}


/**
 * Check is the value is undefined.
 * @return {boolean} true if the value is undefined
 */
ProtocolValue.prototype.isUndefined = function() {
  return this.value_.type == 'undefined';
}


/**
 * Check is the value is null.
 * @return {boolean} true if the value is null
 */
ProtocolValue.prototype.isNull = function() {
  return this.value_.type == 'null';
}


/**
 * Check is the value is a boolean.
 * @return {boolean} true if the value is a boolean
 */
ProtocolValue.prototype.isBoolean = function() {
  return this.value_.type == 'boolean';
}


/**
 * Check is the value is a number.
 * @return {boolean} true if the value is a number
 */
ProtocolValue.prototype.isNumber = function() {
  return this.value_.type == 'number';
}


/**
 * Check is the value is a string.
 * @return {boolean} true if the value is a string
 */
ProtocolValue.prototype.isString = function() {
  return this.value_.type == 'string';
}


/**
 * Check is the value is an object.
 * @return {boolean} true if the value is an object
 */
ProtocolValue.prototype.isObject = function() {
  return this.value_.type == 'object' || this.value_.type == 'function' ||
         this.value_.type == 'error' || this.value_.type == 'regexp';
}


/**
 * Get the constructor function
 * @return {ProtocolValue} constructor function
 */
ProtocolValue.prototype.constructorFunctionValue = function() {
  var ctor = this.value_.constructorFunction;
  return this.packet_.lookup(ctor.ref);
}


/**
 * Get the __proto__ value
 * @return {ProtocolValue} __proto__ value
 */
ProtocolValue.prototype.protoObjectValue = function() {
  var proto = this.value_.protoObject;
  return this.packet_.lookup(proto.ref);
}


/**
 * Get the number og properties.
 * @return {number} the number of properties
 */
ProtocolValue.prototype.propertyCount = function() {
  return this.value_.properties ? this.value_.properties.length : 0;
}


/**
 * Get the specified property name.
 * @return {string} property name
 */
ProtocolValue.prototype.propertyName = function(index) {
  var property = this.value_.properties[index];
  return property.name;
}


/**
 * Return index for the property name.
 * @param name The property name to look for
 * @return {number} index for the property name
 */
ProtocolValue.prototype.propertyIndex = function(name) {
  for (var i = 0; i < this.propertyCount(); i++) {
    if (this.value_.properties[i].name == name) {
      return i;
    }
  }
  return null;
}


/**
 * Get the specified property value.
 * @return {ProtocolValue} property value
 */
ProtocolValue.prototype.propertyValue = function(index) {
  var property = this.value_.properties[index];
  return this.packet_.lookup(property.ref);
}


/**
 * Check is the value is a string.
 * @return {boolean} true if the value is a string
 */
ProtocolValue.prototype.value = function() {
  return this.value_.value;
}


function ProtocolReference(handle) {
  this.handle_ = handle;
}


ProtocolReference.prototype.handle = function() {
  return this.handle_;
}


1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 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 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
function MakeJSONPair_(name, value) {
  return '"' + name + '":' + value;
}


function ArrayToJSONObject_(content) {
  return '{' + content.join(',') + '}';
}


function ArrayToJSONArray_(content) {
  return '[' + content.join(',') + ']';
}


function BooleanToJSON_(value) {
  return String(value); 
}


function NumberToJSON_(value) {
  return String(value); 
}


// Mapping of some control characters to avoid the \uXXXX syntax for most
// commonly used control cahracters.
const ctrlCharMap_ = {
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\f': '\\f',
  '\r': '\\r',
  '"' : '\\"',
  '\\': '\\\\'
};


// Regular expression testing for ", \ and control characters (0x00 - 0x1F).
const ctrlCharTest_ = new RegExp('["\\\\\x00-\x1F]');


// Regular expression matching ", \ and control characters (0x00 - 0x1F)
// globally.
const ctrlCharMatch_ = new RegExp('["\\\\\x00-\x1F]', 'g');


/**
 * Convert a String to its JSON representation (see http://www.json.org/). To
 * avoid depending on the String object this method calls the functions in
 * string.js directly and not through the value.
 * @param {String} value The String value to format as JSON
 * @return {string} JSON formatted String value
 */
function StringToJSON_(value) {
  // Check for" , \ and control characters (0x00 - 0x1F). No need to call
  // RegExpTest as ctrlchar is constructed using RegExp.
  if (ctrlCharTest_.test(value)) {
    // Replace ", \ and control characters (0x00 - 0x1F).
    return '"' +
      value.replace(ctrlCharMatch_, function (char) {
        // Use charmap if possible.
        var mapped = ctrlCharMap_[char];
        if (mapped) return mapped;
        mapped = char.charCodeAt();
        // Convert control character to unicode escape sequence.
        return '\\u00' +
          '0' + // TODO %NumberToRadixString(Math.floor(mapped / 16), 16) +
          '0' // TODO %NumberToRadixString(mapped % 16, 16);
      })
    + '"';
  }

  // Simple string with no special characters.
  return '"' + value + '"';
}


/**
 * Convert a Date to ISO 8601 format. To avoid depending on the Date object
 * this method calls the functions in date.js directly and not through the
 * value.
 * @param {Date} value The Date value to format as JSON
 * @return {string} JSON formatted Date value
 */
function DateToISO8601_(value) {
  function f(n) {
    return n < 10 ? '0' + n : n;
  }
  function g(n) {
    return n < 10 ? '00' + n : n < 100 ? '0' + n : n;
  }
  return builtins.GetUTCFullYearFrom(value)         + '-' +
          f(builtins.GetUTCMonthFrom(value) + 1)    + '-' +
          f(builtins.GetUTCDateFrom(value))         + 'T' +
          f(builtins.GetUTCHoursFrom(value))        + ':' +
          f(builtins.GetUTCMinutesFrom(value))      + ':' +
          f(builtins.GetUTCSecondsFrom(value))      + '.' +
          g(builtins.GetUTCMillisecondsFrom(value)) + 'Z';
}


/**
 * Convert a Date to ISO 8601 format. To avoid depending on the Date object
 * this method calls the functions in date.js directly and not through the
 * value.
 * @param {Date} value The Date value to format as JSON
 * @return {string} JSON formatted Date value
 */
function DateToJSON_(value) {
  return '"' + DateToISO8601_(value) + '"';
}


/**
 * Convert an Object to its JSON representation (see http://www.json.org/).
 * This implementation simply runs through all string property names and adds
 * each property to the JSON representation for some predefined types. For type
 * "object" the function calls itself recursively unless the object has the
 * function property "toJSONProtocol" in which case that is used. This is not
 * a general implementation but sufficient for the debugger. Note that circular
 * structures will cause infinite recursion.
 * @param {Object} object The object to format as JSON
 * @return {string} JSON formatted object value
 */
function SimpleObjectToJSON_(object) {
  var content = [];
  for (var key in object) {
    // Only consider string keys.
    if (typeof key == 'string') {
      var property_value = object[key];

      // Format the value based on its type.
      var property_value_json;
      switch (typeof property_value) {
        case 'object':
          if (typeof property_value.toJSONProtocol == 'function') {
            property_value_json = property_value.toJSONProtocol(true)
          } else if (property_value.constructor.name == 'Array'){
            property_value_json = SimpleArrayToJSON_(property_value);
          } else {
            property_value_json = SimpleObjectToJSON_(property_value);
          }
          break;

        case 'boolean':
          property_value_json = BooleanToJSON_(property_value);
          break;

        case 'number':
          property_value_json = NumberToJSON_(property_value);
          break;

        case 'string':
          property_value_json = StringToJSON_(property_value);
          break;

        default:
          property_value_json = null;
      }

      // Add the property if relevant.
      if (property_value_json) {
        content.push(StringToJSON_(key) + ':' + property_value_json);
      }
    }
  }

  // Make JSON object representation.
  return '{' + content.join(',') + '}';
}


/**
 * Convert an array to its JSON representation. This is a VERY simple
 * implementation just to support what is needed for the debugger.
 * @param {Array} arrya The array to format as JSON
 * @return {string} JSON formatted array value
 */
function SimpleArrayToJSON_(array) {
  // Make JSON array representation.
  var json = '[';
  for (var i = 0; i < array.length; i++) {
    if (i != 0) {
      json += ',';
    }
    var elem = array[i];
    if (elem.toJSONProtocol) {
      json += elem.toJSONProtocol(true)
    } else if (typeof(elem) === 'object')  {
      json += SimpleObjectToJSON_(elem);
    } else if (typeof(elem) === 'boolean')  {
      json += BooleanToJSON_(elem);
    } else if (typeof(elem) === 'number')  {
      json += NumberToJSON_(elem);
    } else if (typeof(elem) === 'string')  {
      json += StringToJSON_(elem);
    } else {
      json += elem;
    }
  }
  json += ']';
  return json;
}