tickprocessor.js 28.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.


29 30 31 32 33 34 35
function inherits(childCtor, parentCtor) {
  childCtor.prototype.__proto__ = parentCtor.prototype;
};


function V8Profile(separateIc) {
  Profile.call(this);
36
  if (!separateIc) {
37
    this.skipThisFunction = function(name) { return V8Profile.IC_RE.test(name); };
38 39
  }
};
40
inherits(V8Profile, Profile);
41 42


43
V8Profile.IC_RE =
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    /^(?:CallIC|LoadIC|StoreIC)|(?:Builtin: (?:Keyed)?(?:Call|Load|Store)IC_)/;


/**
 * A thin wrapper around shell's 'read' function showing a file name on error.
 */
function readFile(fileName) {
  try {
    return read(fileName);
  } catch (e) {
    print(fileName + ': ' + (e.message || e));
    throw e;
  }
}


60 61 62 63 64 65 66 67 68 69 70 71 72
/**
 * Parser for dynamic code optimization state.
 */
function parseState(s) {
  switch (s) {
  case "": return Profile.CodeState.COMPILED;
  case "~": return Profile.CodeState.OPTIMIZABLE;
  case "*": return Profile.CodeState.OPTIMIZED;
  }
  throw new Error("unknown code state: " + s);
}


73
function SnapshotLogProcessor() {
74
  LogReader.call(this, {
75
      'code-creation': {
76
          parsers: [null, parseInt, parseInt, parseInt, null, 'var-args'],
77 78 79
          processor: this.processCodeCreation },
      'code-move': { parsers: [parseInt, parseInt],
          processor: this.processCodeMove },
80 81
      'code-delete': { parsers: [parseInt],
          processor: this.processCodeDelete },
82 83 84
      'function-creation': null,
      'function-move': null,
      'function-delete': null,
85
      'sfi-move': null,
86 87
      'snapshot-pos': { parsers: [parseInt, parseInt],
          processor: this.processSnapshotPosition }});
88

89 90
  V8Profile.prototype.handleUnknownCode = function(operation, addr) {
    var op = Profile.Operation;
91 92 93 94 95
    switch (operation) {
      case op.MOVE:
        print('Snapshot: Code move event for unknown code: 0x' +
              addr.toString(16));
        break;
96 97 98 99
      case op.DELETE:
        print('Snapshot: Code delete event for unknown code: 0x' +
              addr.toString(16));
        break;
100 101 102
    }
  };

103
  this.profile_ = new V8Profile();
104 105
  this.serializedEntries_ = [];
}
106
inherits(SnapshotLogProcessor, LogReader);
107 108 109


SnapshotLogProcessor.prototype.processCodeCreation = function(
110
    type, kind, start, size, name, maybe_func) {
111 112 113 114 115 116 117
  if (maybe_func.length) {
    var funcAddr = parseInt(maybe_func[0]);
    var state = parseState(maybe_func[1]);
    this.profile_.addFuncCode(type, name, start, size, funcAddr, state);
  } else {
    this.profile_.addCode(type, name, start, size);
  }
118 119 120 121 122 123 124 125
};


SnapshotLogProcessor.prototype.processCodeMove = function(from, to) {
  this.profile_.moveCode(from, to);
};


126 127 128 129 130
SnapshotLogProcessor.prototype.processCodeDelete = function(start) {
  this.profile_.deleteCode(start);
};


131 132 133 134 135 136 137 138 139 140 141 142 143 144
SnapshotLogProcessor.prototype.processSnapshotPosition = function(addr, pos) {
  this.serializedEntries_[pos] = this.profile_.findEntry(addr);
};


SnapshotLogProcessor.prototype.processLogFile = function(fileName) {
  var contents = readFile(fileName);
  this.processLogChunk(contents);
};


SnapshotLogProcessor.prototype.getSerializedEntryName = function(pos) {
  var entry = this.serializedEntries_[pos];
  return entry ? entry.getRawName() : null;
145 146 147
};


148
function TickProcessor(
149 150 151 152 153
    cppEntriesProvider,
    separateIc,
    callGraphSize,
    ignoreUnknown,
    stateFilter,
154 155
    snapshotLogProcessor,
    distortion,
156 157
    range,
    sourceMap) {
158
  LogReader.call(this, {
159 160 161
      'shared-library': { parsers: [null, parseInt, parseInt],
          processor: this.processSharedLibrary },
      'code-creation': {
162
          parsers: [null, parseInt, parseInt, parseInt, null, 'var-args'],
163 164 165
          processor: this.processCodeCreation },
      'code-move': { parsers: [parseInt, parseInt],
          processor: this.processCodeMove },
166 167
      'code-delete': { parsers: [parseInt],
          processor: this.processCodeDelete },
168
      'sfi-move': { parsers: [parseInt, parseInt],
169 170 171
          processor: this.processFunctionMove },
      'snapshot-pos': { parsers: [parseInt, parseInt],
          processor: this.processSnapshotPosition },
172
      'tick': {
173
          parsers: [parseInt, parseInt, parseInt,
174
                    parseInt, parseInt, 'var-args'],
175
          processor: this.processTick },
176 177 178 179
      'heap-sample-begin': { parsers: [null, null, parseInt],
          processor: this.processHeapSampleBegin },
      'heap-sample-end': { parsers: [null, null],
          processor: this.processHeapSampleEnd },
180 181 182 183
      'timer-event-start' : { parsers: [null, null, null],
                              processor: this.advanceDistortion },
      'timer-event-end' : { parsers: [null, null, null],
                            processor: this.advanceDistortion },
184
      // Ignored events.
185
      'profiler': null,
186 187 188
      'function-creation': null,
      'function-move': null,
      'function-delete': null,
189
      'heap-sample-item': null,
190 191 192 193 194
      // Obsolete row types.
      'code-allocate': null,
      'begin-code-region': null,
      'end-code-region': null });

195
  this.cppEntriesProvider_ = cppEntriesProvider;
196
  this.callGraphSize_ = callGraphSize;
197 198
  this.ignoreUnknown_ = ignoreUnknown;
  this.stateFilter_ = stateFilter;
199
  this.snapshotLogProcessor_ = snapshotLogProcessor;
200
  this.sourceMap = sourceMap;
201
  this.deserializedEntriesNames_ = [];
202 203 204
  var ticks = this.ticks_ =
    { total: 0, unaccounted: 0, excluded: 0, gc: 0 };

205 206 207 208
  distortion = parseInt(distortion);
  // Convert picoseconds to nanoseconds.
  this.distortion_per_entry = isNaN(distortion) ? 0 : (distortion / 1000);
  this.distortion = 0;
209
  var rangelimits = range ? range.split(",") : [];
210 211 212 213 214 215
  var range_start = parseInt(rangelimits[0]);
  var range_end = parseInt(rangelimits[1]);
  // Convert milliseconds to nanoseconds.
  this.range_start = isNaN(range_start) ? -Infinity : (range_start * 1000);
  this.range_end = isNaN(range_end) ? Infinity : (range_end * 1000)

216
  V8Profile.prototype.handleUnknownCode = function(
217
      operation, addr, opt_stackPos) {
218
    var op = Profile.Operation;
219 220 221 222
    switch (operation) {
      case op.MOVE:
        print('Code move event for unknown code: 0x' + addr.toString(16));
        break;
223 224 225
      case op.DELETE:
        print('Code delete event for unknown code: 0x' + addr.toString(16));
        break;
226 227 228 229 230 231 232 233 234 235 236
      case op.TICK:
        // Only unknown PCs (the first frame) are reported as unaccounted,
        // otherwise tick balance will be corrupted (this behavior is compatible
        // with the original tickprocessor.py script.)
        if (opt_stackPos == 0) {
          ticks.unaccounted++;
        }
        break;
    }
  };

237
  this.profile_ = new V8Profile(separateIc);
238 239
  this.codeTypes_ = {};
  // Count each tick as a time unit.
240
  this.viewBuilder_ = new ViewBuilder(1);
241
  this.lastLogFileName_ = null;
242 243 244

  this.generation_ = 1;
  this.currentProducerProfile_ = null;
245
};
246
inherits(TickProcessor, LogReader);
247 248 249 250 251 252


TickProcessor.VmStates = {
  JS: 0,
  GC: 1,
  COMPILER: 2,
253
  OTHER: 3,
254 255
  EXTERNAL: 4,
  IDLE: 5
256 257 258 259
};


TickProcessor.CodeTypes = {
260 261
  CPP: 0,
  SHARED_LIB: 1
262
};
263 264
// Otherwise, this is JS-related code. We are not adding it to
// codeTypes_ map because there can be zillions of them.
265 266 267 268


TickProcessor.CALL_PROFILE_CUTOFF_PCT = 2.0;

269
TickProcessor.CALL_GRAPH_SIZE = 5;
270

271 272 273 274 275 276 277 278
/**
 * @override
 */
TickProcessor.prototype.printError = function(str) {
  print(str);
};


279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
TickProcessor.prototype.setCodeType = function(name, type) {
  this.codeTypes_[name] = TickProcessor.CodeTypes[type];
};


TickProcessor.prototype.isSharedLibrary = function(name) {
  return this.codeTypes_[name] == TickProcessor.CodeTypes.SHARED_LIB;
};


TickProcessor.prototype.isCppCode = function(name) {
  return this.codeTypes_[name] == TickProcessor.CodeTypes.CPP;
};


TickProcessor.prototype.isJsCode = function(name) {
295
  return !(name in this.codeTypes_);
296 297 298 299 300
};


TickProcessor.prototype.processLogFile = function(fileName) {
  this.lastLogFileName_ = fileName;
301 302 303 304
  var line;
  while (line = readline()) {
    this.processLogLine(line);
  }
305 306 307
};


308 309 310 311 312 313 314 315
TickProcessor.prototype.processLogFileInTest = function(fileName) {
   // Hack file name to avoid dealing with platform specifics.
  this.lastLogFileName_ = 'v8.log';
  var contents = readFile(fileName);
  this.processLogChunk(contents);
};


316 317
TickProcessor.prototype.processSharedLibrary = function(
    name, startAddr, endAddr) {
318
  var entry = this.profile_.addLibrary(name, startAddr, endAddr);
319 320 321 322 323 324 325 326 327 328 329 330
  this.setCodeType(entry.getName(), 'SHARED_LIB');

  var self = this;
  var libFuncs = this.cppEntriesProvider_.parseVmSymbols(
      name, startAddr, endAddr, function(fName, fStart, fEnd) {
    self.profile_.addStaticCode(fName, fStart, fEnd);
    self.setCodeType(fName, 'CPP');
  });
};


TickProcessor.prototype.processCodeCreation = function(
331
    type, kind, start, size, name, maybe_func) {
332
  name = this.deserializedEntriesNames_[start] || name;
333 334 335 336 337 338 339
  if (maybe_func.length) {
    var funcAddr = parseInt(maybe_func[0]);
    var state = parseState(maybe_func[1]);
    this.profile_.addFuncCode(type, name, start, size, funcAddr, state);
  } else {
    this.profile_.addCode(type, name, start, size);
  }
340 341 342 343 344 345 346 347
};


TickProcessor.prototype.processCodeMove = function(from, to) {
  this.profile_.moveCode(from, to);
};


348 349 350 351 352
TickProcessor.prototype.processCodeDelete = function(start) {
  this.profile_.deleteCode(start);
};


353
TickProcessor.prototype.processFunctionMove = function(from, to) {
354
  this.profile_.moveFunc(from, to);
355 356 357
};


358 359 360 361 362 363 364 365
TickProcessor.prototype.processSnapshotPosition = function(addr, pos) {
  if (this.snapshotLogProcessor_) {
    this.deserializedEntriesNames_[addr] =
      this.snapshotLogProcessor_.getSerializedEntryName(pos);
  }
};


366 367 368 369
TickProcessor.prototype.includeTick = function(vmState) {
  return this.stateFilter_ == null || this.stateFilter_ == vmState;
};

370
TickProcessor.prototype.processTick = function(pc,
371
                                               ns_since_start,
372 373
                                               is_external_callback,
                                               tos_or_external_callback,
374 375
                                               vmState,
                                               stack) {
376 377 378 379 380
  this.distortion += this.distortion_per_entry;
  ns_since_start -= this.distortion;
  if (ns_since_start < this.range_start || ns_since_start > this.range_end) {
    return;
  }
381 382 383 384 385 386
  this.ticks_.total++;
  if (vmState == TickProcessor.VmStates.GC) this.ticks_.gc++;
  if (!this.includeTick(vmState)) {
    this.ticks_.excluded++;
    return;
  }
387
  if (is_external_callback) {
388 389
    // Don't use PC when in external callback code, as it can point
    // inside callback's code, and we will erroneously report
390 391
    // that a callback calls itself. Instead we use tos_or_external_callback,
    // as simply resetting PC will produce unaccounted ticks.
392 393 394 395 396 397 398 399 400 401
    pc = tos_or_external_callback;
    tos_or_external_callback = 0;
  } else if (tos_or_external_callback) {
    // Find out, if top of stack was pointing inside a JS function
    // meaning that we have encountered a frameless invocation.
    var funcEntry = this.profile_.findEntry(tos_or_external_callback);
    if (!funcEntry || !funcEntry.isJSFunction || !funcEntry.isJSFunction()) {
      tos_or_external_callback = 0;
    }
  }
402

403
  this.profile_.recordTick(this.processStack(pc, tos_or_external_callback, stack));
404 405 406
};


407 408 409 410 411
TickProcessor.prototype.advanceDistortion = function() {
  this.distortion += this.distortion_per_entry;
}


412 413
TickProcessor.prototype.processHeapSampleBegin = function(space, state, ticks) {
  if (space != 'Heap') return;
414
  this.currentProducerProfile_ = new CallTree();
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
};


TickProcessor.prototype.processHeapSampleEnd = function(space, state) {
  if (space != 'Heap' || !this.currentProducerProfile_) return;

  print('Generation ' + this.generation_ + ':');
  var tree = this.currentProducerProfile_;
  tree.computeTotalWeights();
  var producersView = this.viewBuilder_.buildView(tree);
  // Sort by total time, desc, then by name, desc.
  producersView.sort(function(rec1, rec2) {
      return rec2.totalTime - rec1.totalTime ||
          (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1); });
  this.printHeavyProfile(producersView.head.children);

  this.currentProducerProfile_ = null;
  this.generation_++;
};


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 501 502 503
TickProcessor.prototype.printStatistics = function() {
  print('Statistical profiling result from ' + this.lastLogFileName_ +
        ', (' + this.ticks_.total +
        ' ticks, ' + this.ticks_.unaccounted + ' unaccounted, ' +
        this.ticks_.excluded + ' excluded).');

  if (this.ticks_.total == 0) return;

  // Print the unknown ticks percentage if they are not ignored.
  if (!this.ignoreUnknown_ && this.ticks_.unaccounted > 0) {
    this.printHeader('Unknown');
    this.printCounter(this.ticks_.unaccounted, this.ticks_.total);
  }

  var flatProfile = this.profile_.getFlatProfile();
  var flatView = this.viewBuilder_.buildView(flatProfile);
  // Sort by self time, desc, then by name, desc.
  flatView.sort(function(rec1, rec2) {
      return rec2.selfTime - rec1.selfTime ||
          (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1); });
  var totalTicks = this.ticks_.total;
  if (this.ignoreUnknown_) {
    totalTicks -= this.ticks_.unaccounted;
  }
  // Our total time contains all the ticks encountered,
  // while profile only knows about the filtered ticks.
  flatView.head.totalTime = totalTicks;

  // Count library ticks
  var flatViewNodes = flatView.head.children;
  var self = this;
  var libraryTicks = 0;
  this.processProfile(flatViewNodes,
      function(name) { return self.isSharedLibrary(name); },
      function(rec) { libraryTicks += rec.selfTime; });
  var nonLibraryTicks = totalTicks - libraryTicks;

  this.printHeader('Shared libraries');
  this.printEntries(flatViewNodes, null,
      function(name) { return self.isSharedLibrary(name); });

  this.printHeader('JavaScript');
  this.printEntries(flatViewNodes, nonLibraryTicks,
      function(name) { return self.isJsCode(name); });

  this.printHeader('C++');
  this.printEntries(flatViewNodes, nonLibraryTicks,
      function(name) { return self.isCppCode(name); });

  this.printHeader('GC');
  this.printCounter(this.ticks_.gc, totalTicks);

  this.printHeavyProfHeader();
  var heavyProfile = this.profile_.getBottomUpProfile();
  var heavyView = this.viewBuilder_.buildView(heavyProfile);
  // To show the same percentages as in the flat profile.
  heavyView.head.totalTime = totalTicks;
  // Sort by total time, desc, then by name, desc.
  heavyView.sort(function(rec1, rec2) {
      return rec2.totalTime - rec1.totalTime ||
          (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1); });
  this.printHeavyProfile(heavyView.head.children);
};


function padLeft(s, len) {
  s = s.toString();
  if (s.length < len) {
504 505 506 507 508
    var padLength = len - s.length;
    if (!(padLength in padLeft)) {
      padLeft[padLength] = new Array(padLength + 1).join(' ');
    }
    s = padLeft[padLength] + s;
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  }
  return s;
};


TickProcessor.prototype.printHeader = function(headerTitle) {
  print('\n [' + headerTitle + ']:');
  print('   ticks  total  nonlib   name');
};


TickProcessor.prototype.printHeavyProfHeader = function() {
  print('\n [Bottom up (heavy) profile]:');
  print('  Note: percentage shows a share of a particular caller in the ' +
        'total\n' +
        '  amount of its parent calls.');
  print('  Callers occupying less than ' +
        TickProcessor.CALL_PROFILE_CUTOFF_PCT.toFixed(1) +
        '% are not shown.\n');
  print('   ticks parent  name');
};


TickProcessor.prototype.printCounter = function(ticksCount, totalTicksCount) {
  var pct = ticksCount * 100.0 / totalTicksCount;
  print('  ' + padLeft(ticksCount, 5) + '  ' + padLeft(pct.toFixed(1), 5) + '%');
};


TickProcessor.prototype.processProfile = function(
    profile, filterP, func) {
  for (var i = 0, n = profile.length; i < n; ++i) {
    var rec = profile[i];
542
    if (!filterP(rec.internalFuncName)) {
543 544 545 546 547 548
      continue;
    }
    func(rec);
  }
};

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
TickProcessor.prototype.getLineAndColumn = function(name) {
  var re = /:([0-9]+):([0-9]+)$/;
  var array = re.exec(name);
  if (!array) {
    return null;
  }
  return {line: array[1], column: array[2]};
}

TickProcessor.prototype.hasSourceMap = function() {
  return this.sourceMap != null;
};


TickProcessor.prototype.formatFunctionName = function(funcName) {
  if (!this.hasSourceMap()) {
    return funcName;
  }
  var lc = this.getLineAndColumn(funcName);
  if (lc == null) {
    return funcName;
  }
  // in source maps lines and columns are zero based
  var lineNumber = lc.line - 1;
  var column = lc.column - 1;
  var entry = this.sourceMap.findEntry(lineNumber, column);
  var sourceFile = entry[2];
  var sourceLine = entry[3] + 1;
  var sourceColumn = entry[4] + 1;

  return sourceFile + ':' + sourceLine + ':' + sourceColumn + ' -> ' + funcName;
};
581 582 583

TickProcessor.prototype.printEntries = function(
    profile, nonLibTicks, filterP) {
584
  var that = this;
585 586 587 588
  this.processProfile(profile, filterP, function (rec) {
    if (rec.selfTime == 0) return;
    var nonLibPct = nonLibTicks != null ?
        rec.selfTime * 100.0 / nonLibTicks : 0.0;
589 590
    var funcName = that.formatFunctionName(rec.internalFuncName);

591 592 593
    print('  ' + padLeft(rec.selfTime, 5) + '  ' +
          padLeft(rec.selfPercent.toFixed(1), 5) + '%  ' +
          padLeft(nonLibPct.toFixed(1), 5) + '%  ' +
594
          funcName);
595 596 597 598 599 600 601 602 603 604 605
  });
};


TickProcessor.prototype.printHeavyProfile = function(profile, opt_indent) {
  var self = this;
  var indent = opt_indent || 0;
  var indentStr = padLeft('', indent);
  this.processProfile(profile, function() { return true; }, function (rec) {
    // Cut off too infrequent callers.
    if (rec.parentTotalPercent < TickProcessor.CALL_PROFILE_CUTOFF_PCT) return;
606
    var funcName = self.formatFunctionName(rec.internalFuncName);
607 608
    print('  ' + padLeft(rec.totalTime, 5) + '  ' +
          padLeft(rec.parentTotalPercent.toFixed(1), 5) + '%  ' +
609
          indentStr + funcName);
610
    // Limit backtrace depth.
611
    if (indent < 2 * self.callGraphSize_) {
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
      self.printHeavyProfile(rec.children, indent + 2);
    }
    // Delimit top-level functions.
    if (indent == 0) {
      print('');
    }
  });
};


function CppEntriesProvider() {
};


CppEntriesProvider.prototype.parseVmSymbols = function(
    libName, libStart, libEnd, processorFunc) {
628
  this.loadSymbols(libName);
629 630 631

  var prevEntry;

632
  function addEntry(funcInfo) {
633 634
    // Several functions can be mapped onto the same address. To avoid
    // creating zero-sized entries, skip such duplicates.
635
    // Also double-check that function belongs to the library address space.
636 637 638 639
    if (prevEntry && !prevEntry.end &&
        prevEntry.start < funcInfo.start &&
        prevEntry.start >= libStart && funcInfo.start <= libEnd) {
      processorFunc(prevEntry.name, prevEntry.start, funcInfo.start);
640
    }
641 642 643 644 645 646
    if (funcInfo.end &&
        (!prevEntry || prevEntry.start != funcInfo.start) &&
        funcInfo.start >= libStart && funcInfo.end <= libEnd) {
      processorFunc(funcInfo.name, funcInfo.start, funcInfo.end);
    }
    prevEntry = funcInfo;
647 648
  }

649 650 651
  while (true) {
    var funcInfo = this.parseNextLine();
    if (funcInfo === null) {
652
      continue;
653 654
    } else if (funcInfo === false) {
      break;
655 656 657 658
    }
    if (funcInfo.start < libStart && funcInfo.start < libEnd - libStart) {
      funcInfo.start += libStart;
    }
659 660 661 662
    if (funcInfo.size) {
      funcInfo.end = funcInfo.start + funcInfo.size;
    }
    addEntry(funcInfo);
663
  }
664
  addEntry({name: '', start: libEnd});
665 666 667 668 669 670 671
};


CppEntriesProvider.prototype.loadSymbols = function(libName) {
};


672 673
CppEntriesProvider.prototype.parseNextLine = function() {
  return false;
674 675 676
};


677
function UnixCppEntriesProvider(nmExec, targetRootFS) {
678 679
  this.symbols = [];
  this.parsePos = 0;
680
  this.nmExec = nmExec;
681
  this.targetRootFS = targetRootFS;
682
  this.FUNC_RE = /^([0-9a-fA-F]{8,16}) ([0-9a-fA-F]{8,16} )?[tTwW] (.*)$/;
683 684 685 686 687
};
inherits(UnixCppEntriesProvider, CppEntriesProvider);


UnixCppEntriesProvider.prototype.loadSymbols = function(libName) {
688
  this.parsePos = 0;
689
  libName = this.targetRootFS + libName;
690 691
  try {
    this.symbols = [
692 693
      os.system(this.nmExec, ['-C', '-n', '-S', libName], -1, -1),
      os.system(this.nmExec, ['-C', '-n', '-S', '-D', libName], -1, -1)
694 695 696
    ];
  } catch (e) {
    // If the library cannot be found on this system let's not panic.
697
    this.symbols = ['', ''];
698
  }
699 700 701
};


702 703 704 705 706 707 708 709 710 711 712 713 714
UnixCppEntriesProvider.prototype.parseNextLine = function() {
  if (this.symbols.length == 0) {
    return false;
  }
  var lineEndPos = this.symbols[0].indexOf('\n', this.parsePos);
  if (lineEndPos == -1) {
    this.symbols.shift();
    this.parsePos = 0;
    return this.parseNextLine();
  }

  var line = this.symbols[0].substring(this.parsePos, lineEndPos);
  this.parsePos = lineEndPos + 1;
715
  var fields = line.match(this.FUNC_RE);
716 717 718 719 720 721 722 723
  var funcInfo = null;
  if (fields) {
    funcInfo = { name: fields[3], start: parseInt(fields[1], 16) };
    if (fields[2]) {
      funcInfo.size = parseInt(fields[2], 16);
    }
  }
  return funcInfo;
724 725 726
};


727 728
function MacCppEntriesProvider(nmExec, targetRootFS) {
  UnixCppEntriesProvider.call(this, nmExec, targetRootFS);
729
  // Note an empty group. It is required, as UnixCppEntriesProvider expects 3 groups.
730
  this.FUNC_RE = /^([0-9a-fA-F]{8,16}) ()[iItT] (.*)$/;
731 732 733 734 735 736
};
inherits(MacCppEntriesProvider, UnixCppEntriesProvider);


MacCppEntriesProvider.prototype.loadSymbols = function(libName) {
  this.parsePos = 0;
737
  libName = this.targetRootFS + libName;
738 739 740 741 742 743 744 745 746
  try {
    this.symbols = [os.system(this.nmExec, ['-n', '-f', libName], -1, -1), ''];
  } catch (e) {
    // If the library cannot be found on this system let's not panic.
    this.symbols = '';
  }
};


747 748
function WindowsCppEntriesProvider(_ignored_nmExec, targetRootFS) {
  this.targetRootFS = targetRootFS;
749 750
  this.symbols = '';
  this.parsePos = 0;
751 752 753 754
};
inherits(WindowsCppEntriesProvider, CppEntriesProvider);


755
WindowsCppEntriesProvider.FILENAME_RE = /^(.*)\.([^.]+)$/;
756 757 758


WindowsCppEntriesProvider.FUNC_RE =
759 760 761 762 763 764 765 766 767
    /^\s+0001:[0-9a-fA-F]{8}\s+([_\?@$0-9a-zA-Z]+)\s+([0-9a-fA-F]{8}).*$/;


WindowsCppEntriesProvider.IMAGE_BASE_RE =
    /^\s+0000:00000000\s+___ImageBase\s+([0-9a-fA-F]{8}).*$/;


// This is almost a constant on Windows.
WindowsCppEntriesProvider.EXE_IMAGE_BASE = 0x00400000;
768 769 770


WindowsCppEntriesProvider.prototype.loadSymbols = function(libName) {
771
  libName = this.targetRootFS + libName;
772
  var fileNameFields = libName.match(WindowsCppEntriesProvider.FILENAME_RE);
773
  if (!fileNameFields) return;
774
  var mapFileName = fileNameFields[1] + '.map';
775 776 777 778 779 780 781
  this.moduleType_ = fileNameFields[2].toLowerCase();
  try {
    this.symbols = read(mapFileName);
  } catch (e) {
    // If .map file cannot be found let's not panic.
    this.symbols = '';
  }
782 783 784
};


785 786 787 788 789 790 791 792
WindowsCppEntriesProvider.prototype.parseNextLine = function() {
  var lineEndPos = this.symbols.indexOf('\r\n', this.parsePos);
  if (lineEndPos == -1) {
    return false;
  }

  var line = this.symbols.substring(this.parsePos, lineEndPos);
  this.parsePos = lineEndPos + 2;
793 794 795 796 797 798 799 800 801 802 803 804

  // Image base entry is above all other symbols, so we can just
  // terminate parsing.
  var imageBaseFields = line.match(WindowsCppEntriesProvider.IMAGE_BASE_RE);
  if (imageBaseFields) {
    var imageBase = parseInt(imageBaseFields[1], 16);
    if ((this.moduleType_ == 'exe') !=
        (imageBase == WindowsCppEntriesProvider.EXE_IMAGE_BASE)) {
      return false;
    }
  }

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
  var fields = line.match(WindowsCppEntriesProvider.FUNC_RE);
  return fields ?
      { name: this.unmangleName(fields[1]), start: parseInt(fields[2], 16) } :
      null;
};


/**
 * Performs very simple unmangling of C++ names.
 *
 * Does not handle arguments and template arguments. The mangled names have
 * the form:
 *
 *   ?LookupInDescriptor@JSObject@internal@v8@@...arguments info...
 */
WindowsCppEntriesProvider.prototype.unmangleName = function(name) {
  // Empty or non-mangled name.
  if (name.length < 1 || name.charAt(0) != '?') return name;
  var nameEndPos = name.indexOf('@@');
  var components = name.substring(1, nameEndPos).split('@');
  components.reverse();
  return components.join('::');
};


830 831 832
function ArgumentsProcessor(args) {
  this.args_ = args;
  this.result_ = ArgumentsProcessor.DEFAULTS;
833

834
  this.argsDispatch_ = {
835 836 837 838 839 840 841 842 843 844
    '-j': ['stateFilter', TickProcessor.VmStates.JS,
        'Show only ticks from JS VM state'],
    '-g': ['stateFilter', TickProcessor.VmStates.GC,
        'Show only ticks from GC VM state'],
    '-c': ['stateFilter', TickProcessor.VmStates.COMPILER,
        'Show only ticks from COMPILER VM state'],
    '-o': ['stateFilter', TickProcessor.VmStates.OTHER,
        'Show only ticks from OTHER VM state'],
    '-e': ['stateFilter', TickProcessor.VmStates.EXTERNAL,
        'Show only ticks from EXTERNAL VM state'],
845 846
    '--call-graph-size': ['callGraphSize', TickProcessor.CALL_GRAPH_SIZE,
        'Set the call graph size'],
847 848 849 850 851 852 853
    '--ignore-unknown': ['ignoreUnknown', true,
        'Exclude ticks of unknown code entries from processing'],
    '--separate-ic': ['separateIc', true,
        'Separate IC entries'],
    '--unix': ['platform', 'unix',
        'Specify that we are running on *nix platform'],
    '--windows': ['platform', 'windows',
854
        'Specify that we are running on Windows platform'],
855 856
    '--mac': ['platform', 'mac',
        'Specify that we are running on Mac OS X platform'],
857
    '--nm': ['nm', 'nm',
858
        'Specify the \'nm\' executable to use (e.g. --nm=/my_dir/nm)'],
859 860
    '--target': ['targetRootFS', '',
        'Specify the target root directory for cross environment'],
861
    '--snapshot-log': ['snapshotLogFileName', 'snapshot.log',
862 863
        'Specify snapshot log file to use (e.g. --snapshot-log=snapshot.log)'],
    '--range': ['range', 'auto,auto',
864
        'Specify the range limit as [start],[end]'],
865
    '--distortion': ['distortion', 0,
866 867 868
        'Specify the logging overhead in picoseconds'],
    '--source-map': ['sourceMap', null,
        'Specify the source map that should be used for output']
869
  };
870 871 872 873 874 875 876
  this.argsDispatch_['--js'] = this.argsDispatch_['-j'];
  this.argsDispatch_['--gc'] = this.argsDispatch_['-g'];
  this.argsDispatch_['--compiler'] = this.argsDispatch_['-c'];
  this.argsDispatch_['--other'] = this.argsDispatch_['-o'];
  this.argsDispatch_['--external'] = this.argsDispatch_['-e'];
};

877

878 879
ArgumentsProcessor.DEFAULTS = {
  logFileName: 'v8.log',
880
  snapshotLogFileName: null,
881 882
  platform: 'unix',
  stateFilter: null,
883
  callGraphSize: 5,
884 885
  ignoreUnknown: false,
  separateIc: false,
886
  targetRootFS: '',
887 888 889
  nm: 'nm',
  range: 'auto,auto',
  distortion: 0
890 891 892 893 894 895
};


ArgumentsProcessor.prototype.parse = function() {
  while (this.args_.length) {
    var arg = this.args_[0];
896 897 898
    if (arg.charAt(0) != '-') {
      break;
    }
899
    this.args_.shift();
900 901 902 903 904 905
    var userValue = null;
    var eqPos = arg.indexOf('=');
    if (eqPos != -1) {
      userValue = arg.substr(eqPos + 1);
      arg = arg.substr(0, eqPos);
    }
906 907 908
    if (arg in this.argsDispatch_) {
      var dispatch = this.argsDispatch_[arg];
      this.result_[dispatch[0]] = userValue == null ? dispatch[1] : userValue;
909
    } else {
910
      return false;
911 912 913
    }
  }

914 915
  if (this.args_.length >= 1) {
      this.result_.logFileName = this.args_.shift();
916
  }
917
  return true;
918 919 920
};


921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
ArgumentsProcessor.prototype.result = function() {
  return this.result_;
};


ArgumentsProcessor.prototype.printUsageAndExit = function() {

  function padRight(s, len) {
    s = s.toString();
    if (s.length < len) {
      s = s + (new Array(len - s.length + 1).join(' '));
    }
    return s;
  }

  print('Cmdline args: [options] [log-file-name]\n' +
        'Default log file name is "' +
        ArgumentsProcessor.DEFAULTS.logFileName + '".\n');
  print('Options:');
  for (var arg in this.argsDispatch_) {
    var synonims = [arg];
    var dispatch = this.argsDispatch_[arg];
    for (var synArg in this.argsDispatch_) {
      if (arg !== synArg && dispatch === this.argsDispatch_[synArg]) {
        synonims.push(synArg);
        delete this.argsDispatch_[synArg];
      }
    }
    print('  ' + padRight(synonims.join(', '), 20) + dispatch[2]);
  }
  quit(2);
};