tickprocessor.js 29.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
// 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.

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


33 34
function V8Profile(separateIc, separateBytecodes, separateBuiltins,
    separateStubs) {
35
  Profile.call(this);
36 37 38 39 40 41 42 43 44 45 46 47
  var regexps = [];
  if (!separateIc) regexps.push(V8Profile.IC_RE);
  if (!separateBytecodes) regexps.push(V8Profile.BYTECODES_RE);
  if (!separateBuiltins) regexps.push(V8Profile.BUILTINS_RE);
  if (!separateStubs) regexps.push(V8Profile.STUBS_RE);
  if (regexps.length > 0) {
    this.skipThisFunction = function(name) {
      for (var i=0; i<regexps.length; i++) {
        if (regexps[i].test(name)) return true;
      }
      return false;
    };
48 49
  }
};
50
inherits(V8Profile, Profile);
51 52


53
V8Profile.IC_RE =
54 55 56 57
    /^(LoadGlobalIC: )|(Handler: )|(?:CallIC|LoadIC|StoreIC)|(?:Builtin: (?:Keyed)?(?:Load|Store)IC_)/;
V8Profile.BYTECODES_RE = /^(BytecodeHandler: )/
V8Profile.BUILTINS_RE = /^(Builtin: )/
V8Profile.STUBS_RE = /^(Stub: )/
58 59 60 61 62 63 64 65 66


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


73 74 75 76 77 78 79 80 81 82 83 84 85
/**
 * 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);
}


86
function TickProcessor(
87 88
    cppEntriesProvider,
    separateIc,
89 90 91
    separateBytecodes,
    separateBuiltins,
    separateStubs,
92 93 94
    callGraphSize,
    ignoreUnknown,
    stateFilter,
95
    distortion,
96
    range,
jkummerow's avatar
jkummerow committed
97
    sourceMap,
98
    timedRange,
99
    pairwiseTimedRange,
100
    onlySummary,
101 102 103
    runtimeTimerFilter,
    preprocessJson) {
  this.preprocessJson = preprocessJson;
104
  LogReader.call(this, {
105
      'shared-library': { parsers: [parseString, parseInt, parseInt, parseInt],
106 107
          processor: this.processSharedLibrary },
      'code-creation': {
108 109
          parsers: [parseString, parseInt, parseInt, parseInt, parseInt,
                    parseString, parseVarArgs],
110
          processor: this.processCodeCreation },
111 112
      'code-deopt': {
          parsers: [parseInt, parseInt, parseInt, parseInt, parseInt,
113
                    parseString, parseString, parseString],
114 115
          processor: this.processCodeDeopt },
      'code-move': { parsers: [parseInt, parseInt, ],
116
          processor: this.processCodeMove },
117 118
      'code-delete': { parsers: [parseInt],
          processor: this.processCodeDelete },
119
      'code-source-info': {
120 121
          parsers: [parseInt, parseInt, parseInt, parseInt, parseString,
                    parseString, parseString],
122
          processor: this.processCodeSourceInfo },
123
      'script-source': {
124
          parsers: [parseInt, parseString, parseString],
125
          processor: this.processScriptSource },
126
      'sfi-move': { parsers: [parseInt, parseInt],
127
          processor: this.processFunctionMove },
128
      'active-runtime-timer': {
129
        parsers: [parseString],
130
        processor: this.processRuntimeTimerEvent },
131
      'tick': {
132
          parsers: [parseInt, parseInt, parseInt,
133
                    parseInt, parseInt, parseVarArgs],
134
          processor: this.processTick },
135
      'heap-sample-begin': { parsers: [parseString, parseString, parseInt],
136
          processor: this.processHeapSampleBegin },
137
      'heap-sample-end': { parsers: [parseString, parseString],
138
          processor: this.processHeapSampleEnd },
139
      'timer-event-start' : { parsers: [parseString, parseString, parseString],
140
                              processor: this.advanceDistortion },
141
      'timer-event-end' : { parsers: [parseString, parseString, parseString],
142
                            processor: this.advanceDistortion },
143
      // Ignored events.
144
      'profiler': null,
145 146 147
      'function-creation': null,
      'function-move': null,
      'function-delete': null,
148
      'heap-sample-item': null,
jkummerow's avatar
jkummerow committed
149
      'current-time': null,  // Handled specially, not parsed.
150 151 152
      // Obsolete row types.
      'code-allocate': null,
      'begin-code-region': null,
jkummerow's avatar
jkummerow committed
153
      'end-code-region': null },
154 155
      timedRange,
      pairwiseTimedRange);
156

157
  this.cppEntriesProvider_ = cppEntriesProvider;
158
  this.callGraphSize_ = callGraphSize;
159 160
  this.ignoreUnknown_ = ignoreUnknown;
  this.stateFilter_ = stateFilter;
161
  this.runtimeTimerFilter_ = runtimeTimerFilter;
162
  this.sourceMap = sourceMap;
163 164 165
  var ticks = this.ticks_ =
    { total: 0, unaccounted: 0, excluded: 0, gc: 0 };

166 167 168 169
  distortion = parseInt(distortion);
  // Convert picoseconds to nanoseconds.
  this.distortion_per_entry = isNaN(distortion) ? 0 : (distortion / 1000);
  this.distortion = 0;
170
  var rangelimits = range ? range.split(",") : [];
171 172 173 174 175 176
  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)

177
  V8Profile.prototype.handleUnknownCode = function(
178
      operation, addr, opt_stackPos) {
179
    var op = Profile.Operation;
180 181
    switch (operation) {
      case op.MOVE:
182
        printErr('Code move event for unknown code: 0x' + addr.toString(16));
183
        break;
184
      case op.DELETE:
185
        printErr('Code delete event for unknown code: 0x' + addr.toString(16));
186
        break;
187 188 189 190 191 192 193 194 195 196 197
      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;
    }
  };

198 199 200
  if (preprocessJson) {
    this.profile_ = new JsonProfile();
  } else {
201 202
    this.profile_ = new V8Profile(separateIc, separateBytecodes,
        separateBuiltins, separateStubs);
203
  }
204 205
  this.codeTypes_ = {};
  // Count each tick as a time unit.
206
  this.viewBuilder_ = new ViewBuilder(1);
207
  this.lastLogFileName_ = null;
208 209 210

  this.generation_ = 1;
  this.currentProducerProfile_ = null;
211
  this.onlySummary_ = onlySummary;
212
};
213
inherits(TickProcessor, LogReader);
214 215 216 217 218


TickProcessor.VmStates = {
  JS: 0,
  GC: 1,
219 220 221 222 223 224
  PARSER: 2,
  BYTECODE_COMPILER: 3,
  COMPILER: 4,
  OTHER: 5,
  EXTERNAL: 6,
  IDLE: 7,
225 226 227 228
};


TickProcessor.CodeTypes = {
229 230
  CPP: 0,
  SHARED_LIB: 1
231
};
232 233
// Otherwise, this is JS-related code. We are not adding it to
// codeTypes_ map because there can be zillions of them.
234 235


236
TickProcessor.CALL_PROFILE_CUTOFF_PCT = 1.0;
237

238
TickProcessor.CALL_GRAPH_SIZE = 5;
239

240 241 242 243
/**
 * @override
 */
TickProcessor.prototype.printError = function(str) {
244
  printErr(str);
245 246 247
};


248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
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) {
jkummerow's avatar
jkummerow committed
264
  return name !== "UNKNOWN" && !(name in this.codeTypes_);
265 266 267 268 269
};


TickProcessor.prototype.processLogFile = function(fileName) {
  this.lastLogFileName_ = fileName;
270 271 272 273
  var line;
  while (line = readline()) {
    this.processLogLine(line);
  }
274 275 276
};


277 278 279 280 281 282 283 284
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);
};


285
TickProcessor.prototype.processSharedLibrary = function(
286 287
    name, startAddr, endAddr, aslrSlide) {
  var entry = this.profile_.addLibrary(name, startAddr, endAddr, aslrSlide);
288 289 290 291
  this.setCodeType(entry.getName(), 'SHARED_LIB');

  var self = this;
  var libFuncs = this.cppEntriesProvider_.parseVmSymbols(
292
      name, startAddr, endAddr, aslrSlide, function(fName, fStart, fEnd) {
293 294 295 296 297 298 299
    self.profile_.addStaticCode(fName, fStart, fEnd);
    self.setCodeType(fName, 'CPP');
  });
};


TickProcessor.prototype.processCodeCreation = function(
300
    type, kind, timestamp, start, size, name, maybe_func) {
301 302 303
  if (maybe_func.length) {
    var funcAddr = parseInt(maybe_func[0]);
    var state = parseState(maybe_func[1]);
304
    this.profile_.addFuncCode(type, name, timestamp, start, size, funcAddr, state);
305
  } else {
306
    this.profile_.addCode(type, name, timestamp, start, size);
307
  }
308 309 310
};


311 312 313 314 315 316 317 318
TickProcessor.prototype.processCodeDeopt = function(
    timestamp, size, code, inliningId, scriptOffset, bailoutType,
    sourcePositionText, deoptReasonText) {
  this.profile_.deoptCode(timestamp, code, inliningId, scriptOffset,
      bailoutType, sourcePositionText, deoptReasonText);
};


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

323 324 325 326
TickProcessor.prototype.processCodeDelete = function(start) {
  this.profile_.deleteCode(start);
};

327 328 329 330 331 332 333
TickProcessor.prototype.processCodeSourceInfo = function(
    start, script, startPos, endPos, sourcePositions, inliningPositions,
    inlinedFunctions) {
  this.profile_.addSourcePositions(start, script, startPos,
    endPos, sourcePositions, inliningPositions, inlinedFunctions);
};

334
TickProcessor.prototype.processScriptSource = function(script, url, source) {
335
  this.profile_.addScriptSource(script, url, source);
336
};
337

338
TickProcessor.prototype.processFunctionMove = function(from, to) {
339
  this.profile_.moveFunc(from, to);
340 341 342
};


343
TickProcessor.prototype.includeTick = function(vmState) {
344 345 346 347 348 349
  if (this.stateFilter_ !== null) {
    return this.stateFilter_ == vmState;
  } else if (this.runtimeTimerFilter_ !== null) {
    return this.currentRuntimeTimer == this.runtimeTimerFilter_;
  }
  return true;
350 351
};

352 353 354 355
TickProcessor.prototype.processRuntimeTimerEvent = function(name) {
  this.currentRuntimeTimer = name;
}

356
TickProcessor.prototype.processTick = function(pc,
357
                                               ns_since_start,
358 359
                                               is_external_callback,
                                               tos_or_external_callback,
360 361
                                               vmState,
                                               stack) {
362 363 364 365 366
  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;
  }
367 368 369 370 371 372
  this.ticks_.total++;
  if (vmState == TickProcessor.VmStates.GC) this.ticks_.gc++;
  if (!this.includeTick(vmState)) {
    this.ticks_.excluded++;
    return;
  }
373
  if (is_external_callback) {
374 375
    // Don't use PC when in external callback code, as it can point
    // inside callback's code, and we will erroneously report
376 377
    // that a callback calls itself. Instead we use tos_or_external_callback,
    // as simply resetting PC will produce unaccounted ticks.
378 379 380 381 382 383
    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);
384
    if (!funcEntry || !funcEntry.isJSFunction || !funcEntry.isJSFunction()) {
385 386 387
      tos_or_external_callback = 0;
    }
  }
388

389 390 391
  this.profile_.recordTick(
      ns_since_start, vmState,
      this.processStack(pc, tos_or_external_callback, stack));
392 393 394
};


395 396 397 398 399
TickProcessor.prototype.advanceDistortion = function() {
  this.distortion += this.distortion_per_entry;
}


400 401
TickProcessor.prototype.processHeapSampleBegin = function(space, state, ticks) {
  if (space != 'Heap') return;
402
  this.currentProducerProfile_ = new CallTree();
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
};


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_++;
};


424
TickProcessor.prototype.printStatistics = function() {
425 426 427 428 429
  if (this.preprocessJson) {
    this.profile_.writeJson();
    return;
  }

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  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;

  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;
  }
447
  var printAllTicks = !this.onlySummary_;
448 449 450 451

  // Count library ticks
  var flatViewNodes = flatView.head.children;
  var self = this;
452

453
  var libraryTicks = 0;
454
  if(printAllTicks) this.printHeader('Shared libraries');
455
  this.printEntries(flatViewNodes, totalTicks, null,
456
      function(name) { return self.isSharedLibrary(name); },
457
      function(rec) { libraryTicks += rec.selfTime; }, printAllTicks);
458 459
  var nonLibraryTicks = totalTicks - libraryTicks;

460
  var jsTicks = 0;
461
  if(printAllTicks) this.printHeader('JavaScript');
462 463
  this.printEntries(flatViewNodes, totalTicks, nonLibraryTicks,
      function(name) { return self.isJsCode(name); },
464
      function(rec) { jsTicks += rec.selfTime; }, printAllTicks);
465

466
  var cppTicks = 0;
467
  if(printAllTicks) this.printHeader('C++');
468 469
  this.printEntries(flatViewNodes, totalTicks, nonLibraryTicks,
      function(name) { return self.isCppCode(name); },
470
      function(rec) { cppTicks += rec.selfTime; }, printAllTicks);
471 472 473 474 475 476 477 478 479 480

  this.printHeader('Summary');
  this.printLine('JavaScript', jsTicks, totalTicks, nonLibraryTicks);
  this.printLine('C++', cppTicks, totalTicks, nonLibraryTicks);
  this.printLine('GC', this.ticks_.gc, totalTicks, nonLibraryTicks);
  this.printLine('Shared libraries', libraryTicks, totalTicks, null);
  if (!this.ignoreUnknown_ && this.ticks_.unaccounted > 0) {
    this.printLine('Unaccounted', this.ticks_.unaccounted,
                   this.ticks_.total, null);
  }
481

482 483 484 485 486 487 488 489 490
  if(printAllTicks) {
    print('\n [C++ entry points]:');
    print('   ticks    cpp   total   name');
    var c_entry_functions = this.profile_.getCEntryProfile();
    var total_c_entry = c_entry_functions[0].ticks;
    for (var i = 1; i < c_entry_functions.length; i++) {
      c = c_entry_functions[i];
      this.printLine(c.name, c.ticks, total_c_entry, totalTicks);
    }
491

492 493 494 495 496 497 498 499 500 501 502
    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);
  }
503 504 505 506 507 508
};


function padLeft(s, len) {
  s = s.toString();
  if (s.length < len) {
509 510 511 512 513
    var padLength = len - s.length;
    if (!(padLength in padLeft)) {
      padLeft[padLength] = new Array(padLength + 1).join(' ');
    }
    s = padLeft[padLength] + s;
514 515 516 517 518 519 520 521 522 523 524
  }
  return s;
};


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


525 526 527 528 529 530 531 532 533 534 535 536
TickProcessor.prototype.printLine = function(
    entry, ticks, totalTicks, nonLibTicks) {
  var pct = ticks * 100 / totalTicks;
  var nonLibPct = nonLibTicks != null
      ? padLeft((ticks * 100 / nonLibTicks).toFixed(1), 5) + '%  '
      : '        ';
  print('  ' + padLeft(ticks, 5) + '  ' +
        padLeft(pct.toFixed(1), 5) + '%  ' +
        nonLibPct +
        entry);
}

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
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.processProfile = function(
    profile, filterP, func) {
  for (var i = 0, n = profile.length; i < n; ++i) {
    var rec = profile[i];
553
    if (!filterP(rec.internalFuncName)) {
554 555 556 557 558 559
      continue;
    }
    func(rec);
  }
};

560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
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;
};
592 593

TickProcessor.prototype.printEntries = function(
594
    profile, totalTicks, nonLibTicks, filterP, callback, printAllTicks) {
595
  var that = this;
596 597
  this.processProfile(profile, filterP, function (rec) {
    if (rec.selfTime == 0) return;
598
    callback(rec);
599
    var funcName = that.formatFunctionName(rec.internalFuncName);
600 601 602
    if(printAllTicks) {
      that.printLine(funcName, rec.selfTime, totalTicks, nonLibTicks);
    }
603 604 605 606 607 608 609 610 611 612 613
  });
};


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;
614
    var funcName = self.formatFunctionName(rec.internalFuncName);
615 616
    print('  ' + padLeft(rec.totalTime, 5) + '  ' +
          padLeft(rec.parentTotalPercent.toFixed(1), 5) + '%  ' +
617
          indentStr + funcName);
618
    // Limit backtrace depth.
619
    if (indent < 2 * self.callGraphSize_) {
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
      self.printHeavyProfile(rec.children, indent + 2);
    }
    // Delimit top-level functions.
    if (indent == 0) {
      print('');
    }
  });
};


function CppEntriesProvider() {
};


CppEntriesProvider.prototype.parseVmSymbols = function(
635
    libName, libStart, libEnd, libASLRSlide, processorFunc) {
636
  this.loadSymbols(libName);
637 638 639

  var prevEntry;

640
  function addEntry(funcInfo) {
641 642
    // Several functions can be mapped onto the same address. To avoid
    // creating zero-sized entries, skip such duplicates.
643
    // Also double-check that function belongs to the library address space.
644 645 646 647
    if (prevEntry && !prevEntry.end &&
        prevEntry.start < funcInfo.start &&
        prevEntry.start >= libStart && funcInfo.start <= libEnd) {
      processorFunc(prevEntry.name, prevEntry.start, funcInfo.start);
648
    }
649 650 651 652 653 654
    if (funcInfo.end &&
        (!prevEntry || prevEntry.start != funcInfo.start) &&
        funcInfo.start >= libStart && funcInfo.end <= libEnd) {
      processorFunc(funcInfo.name, funcInfo.start, funcInfo.end);
    }
    prevEntry = funcInfo;
655 656
  }

657 658 659
  while (true) {
    var funcInfo = this.parseNextLine();
    if (funcInfo === null) {
660
      continue;
661 662
    } else if (funcInfo === false) {
      break;
663
    }
664 665
    if (funcInfo.start < libStart - libASLRSlide &&
        funcInfo.start < libEnd - libStart) {
666
      funcInfo.start += libStart;
667 668
    } else {
      funcInfo.start += libASLRSlide;
669
    }
670 671 672 673
    if (funcInfo.size) {
      funcInfo.end = funcInfo.start + funcInfo.size;
    }
    addEntry(funcInfo);
674
  }
675
  addEntry({name: '', start: libEnd});
676 677 678 679 680 681 682
};


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


683 684
CppEntriesProvider.prototype.parseNextLine = function() {
  return false;
685 686 687
};


688
function UnixCppEntriesProvider(nmExec, targetRootFS) {
689 690
  this.symbols = [];
  this.parsePos = 0;
691
  this.nmExec = nmExec;
692
  this.targetRootFS = targetRootFS;
693
  this.FUNC_RE = /^([0-9a-fA-F]{8,16}) ([0-9a-fA-F]{8,16} )?[tTwW] (.*)$/;
694 695 696 697 698
};
inherits(UnixCppEntriesProvider, CppEntriesProvider);


UnixCppEntriesProvider.prototype.loadSymbols = function(libName) {
699
  this.parsePos = 0;
700
  libName = this.targetRootFS + libName;
701 702
  try {
    this.symbols = [
703 704
      os.system(this.nmExec, ['-C', '-n', '-S', libName], -1, -1),
      os.system(this.nmExec, ['-C', '-n', '-S', '-D', libName], -1, -1)
705 706 707
    ];
  } catch (e) {
    // If the library cannot be found on this system let's not panic.
708
    this.symbols = ['', ''];
709
  }
710 711 712
};


713 714 715 716 717 718 719 720 721 722 723 724 725
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;
726
  var fields = line.match(this.FUNC_RE);
727 728 729 730 731 732 733 734
  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;
735 736 737
};


738 739
function MacCppEntriesProvider(nmExec, targetRootFS) {
  UnixCppEntriesProvider.call(this, nmExec, targetRootFS);
740
  // Note an empty group. It is required, as UnixCppEntriesProvider expects 3 groups.
741
  this.FUNC_RE = /^([0-9a-fA-F]{8,16})() (.*)$/;
742 743 744 745 746 747
};
inherits(MacCppEntriesProvider, UnixCppEntriesProvider);


MacCppEntriesProvider.prototype.loadSymbols = function(libName) {
  this.parsePos = 0;
748
  libName = this.targetRootFS + libName;
749 750 751

  // It seems that in OS X `nm` thinks that `-f` is a format option, not a
  // "flat" display option flag.
752
  try {
753
    this.symbols = [os.system(this.nmExec, ['-n', libName], -1, -1), ''];
754 755 756 757 758 759 760
  } catch (e) {
    // If the library cannot be found on this system let's not panic.
    this.symbols = '';
  }
};


761 762
function WindowsCppEntriesProvider(_ignored_nmExec, targetRootFS) {
  this.targetRootFS = targetRootFS;
763 764
  this.symbols = '';
  this.parsePos = 0;
765 766 767 768
};
inherits(WindowsCppEntriesProvider, CppEntriesProvider);


769
WindowsCppEntriesProvider.FILENAME_RE = /^(.*)\.([^.]+)$/;
770 771 772


WindowsCppEntriesProvider.FUNC_RE =
773 774 775 776 777 778 779 780 781
    /^\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;
782 783 784


WindowsCppEntriesProvider.prototype.loadSymbols = function(libName) {
785
  libName = this.targetRootFS + libName;
786
  var fileNameFields = libName.match(WindowsCppEntriesProvider.FILENAME_RE);
787
  if (!fileNameFields) return;
788
  var mapFileName = fileNameFields[1] + '.map';
789 790 791 792 793 794 795
  this.moduleType_ = fileNameFields[2].toLowerCase();
  try {
    this.symbols = read(mapFileName);
  } catch (e) {
    // If .map file cannot be found let's not panic.
    this.symbols = '';
  }
796 797 798
};


799 800 801 802 803 804 805 806
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;
807 808 809 810 811 812 813 814 815 816 817 818

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

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
  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('::');
};


844 845 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 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 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 923 924 925 926 927 928 929
class ArgumentsProcessor extends BaseArgumentsProcessor {
  getArgsDispatch() {
    let dispatch = {
      '-j': ['stateFilter', TickProcessor.VmStates.JS,
          'Show only ticks from JS VM state'],
      '-g': ['stateFilter', TickProcessor.VmStates.GC,
          'Show only ticks from GC VM state'],
      '-p': ['stateFilter', TickProcessor.VmStates.PARSER,
          'Show only ticks from PARSER VM state'],
      '-b': ['stateFilter', TickProcessor.VmStates.BYTECODE_COMPILER,
          'Show only ticks from BYTECODE_COMPILER 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'],
      '--filter-runtime-timer': ['runtimeTimerFilter', null,
              'Show only ticks matching the given runtime timer scope'],
      '--call-graph-size': ['callGraphSize', TickProcessor.CALL_GRAPH_SIZE,
          'Set the call graph size'],
      '--ignore-unknown': ['ignoreUnknown', true,
          'Exclude ticks of unknown code entries from processing'],
      '--separate-ic': ['separateIc', parseBool,
          'Separate IC entries'],
      '--separate-bytecodes': ['separateBytecodes', parseBool,
          'Separate Bytecode entries'],
      '--separate-builtins': ['separateBuiltins', parseBool,
          'Separate Builtin entries'],
      '--separate-stubs': ['separateStubs', parseBool,
          'Separate Stub entries'],
      '--unix': ['platform', 'unix',
          'Specify that we are running on *nix platform'],
      '--windows': ['platform', 'windows',
          'Specify that we are running on Windows platform'],
      '--mac': ['platform', 'mac',
          'Specify that we are running on Mac OS X platform'],
      '--nm': ['nm', 'nm',
          'Specify the \'nm\' executable to use (e.g. --nm=/my_dir/nm)'],
      '--target': ['targetRootFS', '',
          'Specify the target root directory for cross environment'],
      '--range': ['range', 'auto,auto',
          'Specify the range limit as [start],[end]'],
      '--distortion': ['distortion', 0,
          'Specify the logging overhead in picoseconds'],
      '--source-map': ['sourceMap', null,
          'Specify the source map that should be used for output'],
      '--timed-range': ['timedRange', true,
          'Ignore ticks before first and after last Date.now() call'],
      '--pairwise-timed-range': ['pairwiseTimedRange', true,
          'Ignore ticks outside pairs of Date.now() calls'],
      '--only-summary': ['onlySummary', true,
          'Print only tick summary, exclude other information'],
      '--preprocess': ['preprocessJson', true,
          'Preprocess for consumption with web interface']
    };
    dispatch['--js'] = dispatch['-j'];
    dispatch['--gc'] = dispatch['-g'];
    dispatch['--compiler'] = dispatch['-c'];
    dispatch['--other'] = dispatch['-o'];
    dispatch['--external'] = dispatch['-e'];
    dispatch['--ptr'] = dispatch['--pairwise-timed-range'];
    return dispatch;
  }

  getDefaultResults() {
    return {
      logFileName: 'v8.log',
      platform: 'unix',
      stateFilter: null,
      callGraphSize: 5,
      ignoreUnknown: false,
      separateIc: true,
      separateBytecodes: false,
      separateBuiltins: true,
      separateStubs: true,
      preprocessJson: null,
      targetRootFS: '',
      nm: 'nm',
      range: 'auto,auto',
      distortion: 0,
      timedRange: false,
      pairwiseTimedRange: false,
      onlySummary: false,
      runtimeTimerFilter: null,
    };
930
  }
931
}