tickprocessor.mjs 33.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
// Copyright 2012 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.

import { LogReader, parseString, parseVarArgs } from "./logreader.mjs";
import { BaseArgumentsProcessor, parseBool } from "./arguments.mjs";
import { Profile, JsonProfile } from "./profile.mjs";
import { ViewBuilder } from "./profile_view.mjs";
32
import { WebInspector} from "./sourcemap.mjs";
33 34


35 36 37 38
class V8Profile extends Profile {
  static IC_RE =
      /^(LoadGlobalIC: )|(Handler: )|(?:CallIC|LoadIC|StoreIC)|(?:Builtin: (?:Keyed)?(?:Load|Store)IC_)/;
  static BYTECODES_RE = /^(BytecodeHandler: )/;
39
  static BASELINE_HANDLERS_RE = /^(Builtin: .*Baseline.*)/;
40 41
  static BUILTINS_RE = /^(Builtin: )/;
  static STUBS_RE = /^(Stub: )/;
42

43 44
  constructor(separateIc, separateBytecodes, separateBuiltins, separateStubs,
        separateBaselineHandlers) {
45
    super();
46
    const regexps = [];
47 48 49 50 51
    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) {
52
      this.skipThisFunction = function(name) {
53
        for (let i = 0; i < regexps.length; i++) {
54 55 56 57 58 59 60
          if (regexps[i].test(name)) return true;
        }
        return false;
      };
    }
  }
}
61

62
class CppEntriesProvider {
63 64 65 66
  constructor() {
    this._isEnabled = true;
  }

67 68 69 70
  inRange(funcInfo, start, end) {
    return funcInfo.start >= start && funcInfo.end <= end;
  }

71 72 73
  async parseVmSymbols(libName, libStart, libEnd, libASLRSlide, processorFunc) {
    if (!this._isEnabled) return;
    await this.loadSymbols(libName);
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128

    let lastUnknownSize;
    let lastAdded;

    let addEntry = (funcInfo) => {
      // Several functions can be mapped onto the same address. To avoid
      // creating zero-sized entries, skip such duplicates.
      // Also double-check that function belongs to the library address space.

      if (lastUnknownSize &&
        lastUnknownSize.start < funcInfo.start) {
        // Try to update lastUnknownSize based on new entries start position.
        lastUnknownSize.end = funcInfo.start;
        if ((!lastAdded ||
            !this.inRange(lastUnknownSize, lastAdded.start, lastAdded.end)) &&
            this.inRange(lastUnknownSize, libStart, libEnd)) {
          processorFunc(
              lastUnknownSize.name, lastUnknownSize.start, lastUnknownSize.end);
          lastAdded = lastUnknownSize;
        }
      }
      lastUnknownSize = undefined;

      if (funcInfo.end) {
        // Skip duplicates that have the same start address as the last added.
        if ((!lastAdded || lastAdded.start != funcInfo.start) &&
          this.inRange(funcInfo, libStart, libEnd)) {
          processorFunc(funcInfo.name, funcInfo.start, funcInfo.end);
          lastAdded = funcInfo;
        }
      } else {
        // If a funcInfo doesn't have an end, try to match it up with the next
        // entry.
        lastUnknownSize = funcInfo;
      }
    }

    while (true) {
      const funcInfo = this.parseNextLine();
      if (funcInfo === null) continue;
      if (funcInfo === false) break;
      if (funcInfo.start < libStart - libASLRSlide &&
        funcInfo.start < libEnd - libStart) {
        funcInfo.start += libStart;
      } else {
        funcInfo.start += libASLRSlide;
      }
      if (funcInfo.size) {
        funcInfo.end = funcInfo.start + funcInfo.size;
      }
      addEntry(funcInfo);
    }
    addEntry({ name: '', start: libEnd });
  }

129 130 131 132 133 134 135 136 137 138 139 140
  async loadSymbols(libName) {}

  async loadSymbolsRemote(platform, libName) {
    this.parsePos = 0;
    const url = new URL("http://localhost:8000/v8/loadVMSymbols");
    url.searchParams.set('libName', libName);
    url.searchParams.set('platform', platform);
    this._setRemoteQueryParams(url.searchParams);
    let response;
    let json;
    try {
      response = await fetch(url);
141 142 143 144
      if (response.status == 404) {
        throw new Error(
          `Local symbol server returned 404: ${await response.text()}`);
      }
145 146 147 148 149
      json = await response.json();
      if (json.error) console.warn(json.error);
    } catch (e) {
      if (!response || response.status == 404) {
        // Assume that the local symbol server is not reachable.
150
        console.warn("Disabling remote symbol loading:", e);
151
        this._isEnabled = false;
152
        return;
153 154 155 156 157 158 159 160 161 162 163 164
      }
    }
    this._handleRemoteSymbolsResult(json);
  }

  _setRemoteQueryParams(searchParams) {
    // Subclass responsibility.
  }

  _handleRemoteSymbolsResult(json) {
    this.symbols = json.symbols;
  }
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

  parseNextLine() { return false }
}

export class LinuxCppEntriesProvider extends CppEntriesProvider {
  constructor(nmExec, objdumpExec, targetRootFS, apkEmbeddedLibrary) {
    super();
    this.symbols = [];
    // File offset of a symbol minus the virtual address of a symbol found in
    // the symbol table.
    this.fileOffsetMinusVma = 0;
    this.parsePos = 0;
    this.nmExec = nmExec;
    this.objdumpExec = objdumpExec;
    this.targetRootFS = targetRootFS;
    this.apkEmbeddedLibrary = apkEmbeddedLibrary;
    this.FUNC_RE = /^([0-9a-fA-F]{8,16}) ([0-9a-fA-F]{8,16} )?[tTwW] (.*)$/;
  }

184 185 186 187 188
  _setRemoteQueryParams(searchParams) {
    super._setRemoteQueryParams(searchParams);
    searchParams.set('targetRootFS', this.targetRootFS ?? "");
    searchParams.set('apkEmbeddedLibrary', this.apkEmbeddedLibrary);
  }
189

190 191 192 193 194 195
  _handleRemoteSymbolsResult(json) {
    super._handleRemoteSymbolsResult(json);
    this.fileOffsetMinusVma = json.fileOffsetMinusVma;
  }

  async loadSymbols(libName) {
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    this.parsePos = 0;
    if (this.apkEmbeddedLibrary && libName.endsWith('.apk')) {
      libName = this.apkEmbeddedLibrary;
    }
    if (this.targetRootFS) {
      libName = libName.substring(libName.lastIndexOf('/') + 1);
      libName = this.targetRootFS + libName;
    }
    try {
      this.symbols = [
        os.system(this.nmExec, ['-C', '-n', '-S', libName], -1, -1),
        os.system(this.nmExec, ['-C', '-n', '-S', '-D', libName], -1, -1)
      ];

      const objdumpOutput = os.system(this.objdumpExec, ['-h', libName], -1, -1);
      for (const line of objdumpOutput.split('\n')) {
        const [, sectionName, , vma, , fileOffset] = line.trim().split(/\s+/);
        if (sectionName === ".text") {
          this.fileOffsetMinusVma = parseInt(fileOffset, 16) - parseInt(vma, 16);
        }
      }
    } catch (e) {
      // If the library cannot be found on this system let's not panic.
      this.symbols = ['', ''];
    }
  }

  parseNextLine() {
224
    if (this.symbols.length == 0) return false;
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    const lineEndPos = this.symbols[0].indexOf('\n', this.parsePos);
    if (lineEndPos == -1) {
      this.symbols.shift();
      this.parsePos = 0;
      return this.parseNextLine();
    }

    const line = this.symbols[0].substring(this.parsePos, lineEndPos);
    this.parsePos = lineEndPos + 1;
    const fields = line.match(this.FUNC_RE);
    let funcInfo = null;
    if (fields) {
      funcInfo = { name: fields[3], start: parseInt(fields[1], 16) + this.fileOffsetMinusVma };
      if (fields[2]) {
        funcInfo.size = parseInt(fields[2], 16);
      }
    }
    return funcInfo;
  }
}

246 247 248 249 250 251
export class RemoteLinuxCppEntriesProvider extends LinuxCppEntriesProvider {
  async loadSymbols(libName) {
    return this.loadSymbolsRemote('linux', libName);
  }
}

252 253 254 255 256 257 258
export class MacOSCppEntriesProvider extends LinuxCppEntriesProvider {
  constructor(nmExec, objdumpExec, targetRootFS, apkEmbeddedLibrary) {
    super(nmExec, objdumpExec, targetRootFS, apkEmbeddedLibrary);
    // Note an empty group. It is required, as LinuxCppEntriesProvider expects 3 groups.
    this.FUNC_RE = /^([0-9a-fA-F]{8,16})() (.*)$/;
  }

259
  async loadSymbols(libName) {
260 261 262 263 264 265
    this.parsePos = 0;
    libName = this.targetRootFS + libName;

    // It seems that in OS X `nm` thinks that `-f` is a format option, not a
    // "flat" display option flag.
    try {
266 267 268
      this.symbols = [
        os.system(this.nmExec, ['--demangle', '-n', libName], -1, -1),
        ''];
269 270 271 272 273 274 275
    } catch (e) {
      // If the library cannot be found on this system let's not panic.
      this.symbols = '';
    }
  }
}

276 277 278 279 280 281
export class RemoteMacOSCppEntriesProvider extends LinuxCppEntriesProvider {
  async loadSymbols(libName) {
    return this.loadSymbolsRemote('macos', libName);
  }
}

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 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

export class WindowsCppEntriesProvider extends CppEntriesProvider {
  constructor(_ignored_nmExec, _ignored_objdumpExec, targetRootFS,
    _ignored_apkEmbeddedLibrary) {
    super();
    this.targetRootFS = targetRootFS;
    this.symbols = '';
    this.parsePos = 0;
  }

  static FILENAME_RE = /^(.*)\.([^.]+)$/;
  static FUNC_RE =
    /^\s+0001:[0-9a-fA-F]{8}\s+([_\?@$0-9a-zA-Z]+)\s+([0-9a-fA-F]{8}).*$/;
  static IMAGE_BASE_RE =
    /^\s+0000:00000000\s+___ImageBase\s+([0-9a-fA-F]{8}).*$/;
  // This is almost a constant on Windows.
  static EXE_IMAGE_BASE = 0x00400000;

  loadSymbols(libName) {
    libName = this.targetRootFS + libName;
    const fileNameFields = libName.match(WindowsCppEntriesProvider.FILENAME_RE);
    if (!fileNameFields) return;
    const mapFileName = `${fileNameFields[1]}.map`;
    this.moduleType_ = fileNameFields[2].toLowerCase();
    try {
      this.symbols = read(mapFileName);
    } catch (e) {
      // If .map file cannot be found let's not panic.
      this.symbols = '';
    }
  }

  parseNextLine() {
    const lineEndPos = this.symbols.indexOf('\r\n', this.parsePos);
    if (lineEndPos == -1) {
      return false;
    }

    const line = this.symbols.substring(this.parsePos, lineEndPos);
    this.parsePos = lineEndPos + 2;

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

    const 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...
   */
  unmangleName(name) {
    // Empty or non-mangled name.
    if (name.length < 1 || name.charAt(0) != '?') return name;
    const nameEndPos = name.indexOf('@@');
    const components = name.substring(1, nameEndPos).split('@');
    components.reverse();
    return components.join('::');
  }
}


export class ArgumentsProcessor extends BaseArgumentsProcessor {
  getArgsDispatch() {
    let dispatch = {
      __proto__:null,
      '-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'],
      '--separate-baseline-handlers': ['separateBaselineHandlers', parseBool,
        'Separate Baseline Handler entries'],
      '--linux': ['platform', 'linux',
        'Specify that we are running on *nix platform'],
      '--windows': ['platform', 'windows',
        'Specify that we are running on Windows platform'],
      '--mac': ['platform', 'macos',
        '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)'],
      '--objdump': ['objdump', 'objdump',
        'Specify the \'objdump\' executable to use (e.g. --objdump=/my_dir/objdump)'],
      '--target': ['targetRootFS', '',
        'Specify the target root directory for cross environment'],
      '--apk-embedded-library': ['apkEmbeddedLibrary', '',
        'Specify the path of the embedded library for Android traces'],
      '--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'],
      '--serialize-vm-symbols': ['serializeVMSymbols', true,
        'Print all C++ symbols and library addresses as JSON data'],
      '--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: 'linux',
      stateFilter: null,
      callGraphSize: 5,
      ignoreUnknown: false,
      separateIc: true,
      separateBytecodes: false,
      separateBuiltins: true,
      separateStubs: true,
      separateBaselineHandlers: false,
      preprocessJson: null,
      sourceMap: null,
      targetRootFS: '',
      nm: 'nm',
      objdump: 'objdump',
      range: 'auto,auto',
      distortion: 0,
      timedRange: false,
      pairwiseTimedRange: false,
      onlySummary: false,
      runtimeTimerFilter: null,
      serializeVMSymbols: false,
    };
  }
}

461

462
export class TickProcessor extends LogReader {
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
  static EntriesProvider = {
    'linux': LinuxCppEntriesProvider,
    'windows': WindowsCppEntriesProvider,
    'macos': MacOSCppEntriesProvider
  };

  static fromParams(params, entriesProvider) {
    if (entriesProvider == undefined) {
      entriesProvider = new this.EntriesProvider[params.platform](
          params.nm, params.objdump, params.targetRootFS,
          params.apkEmbeddedLibrary);
    }
    return new TickProcessor(
      entriesProvider,
      params.separateIc,
      params.separateBytecodes,
      params.separateBuiltins,
      params.separateStubs,
      params.separateBaselineHandlers,
      params.callGraphSize,
      params.ignoreUnknown,
      params.stateFilter,
      params.distortion,
      params.range,
      params.sourceMap,
      params.timedRange,
      params.pairwiseTimedRange,
      params.onlySummary,
      params.runtimeTimerFilter,
      params.preprocessJson);
  }

495
  constructor(
496 497 498 499 500
    cppEntriesProvider,
    separateIc,
    separateBytecodes,
    separateBuiltins,
    separateStubs,
501
    separateBaselineHandlers,
502 503 504 505 506 507 508 509 510 511 512
    callGraphSize,
    ignoreUnknown,
    stateFilter,
    distortion,
    range,
    sourceMap,
    timedRange,
    pairwiseTimedRange,
    onlySummary,
    runtimeTimerFilter,
    preprocessJson) {
513
    super({},
514 515
      timedRange,
      pairwiseTimedRange);
516 517 518 519 520
    this.dispatchTable_ = {
      'shared-library': {
        parsers: [parseString, parseInt, parseInt, parseInt],
        processor: this.processSharedLibrary
      },
521
      'code-creation': {
522 523 524 525
        parsers: [parseString, parseInt, parseInt, parseInt, parseInt,
          parseString, parseVarArgs],
        processor: this.processCodeCreation
      },
526
      'code-deopt': {
527 528 529 530 531 532 533 534 535 536 537 538
        parsers: [parseInt, parseInt, parseInt, parseInt, parseInt,
          parseString, parseString, parseString],
        processor: this.processCodeDeopt
      },
      'code-move': {
        parsers: [parseInt, parseInt,],
        processor: this.processCodeMove
      },
      'code-delete': {
        parsers: [parseInt],
        processor: this.processCodeDelete
      },
539
      'code-source-info': {
540 541 542 543
        parsers: [parseInt, parseInt, parseInt, parseInt, parseString,
          parseString, parseString],
        processor: this.processCodeSourceInfo
      },
544
      'script-source': {
545 546 547 548 549 550 551
        parsers: [parseInt, parseString, parseString],
        processor: this.processScriptSource
      },
      'sfi-move': {
        parsers: [parseInt, parseInt],
        processor: this.processFunctionMove
      },
552 553
      'active-runtime-timer': {
        parsers: [parseString],
554 555
        processor: this.processRuntimeTimerEvent
      },
556
      'tick': {
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
        parsers: [parseInt, parseInt, parseInt,
          parseInt, parseInt, parseVarArgs],
        processor: this.processTick
      },
      'heap-sample-begin': {
        parsers: [parseString, parseString, parseInt],
        processor: this.processHeapSampleBegin
      },
      'heap-sample-end': {
        parsers: [parseString, parseString],
        processor: this.processHeapSampleEnd
      },
      'timer-event-start': {
        parsers: [parseString, parseString, parseString],
        processor: this.advanceDistortion
      },
      'timer-event-end': {
        parsers: [parseString, parseString, parseString],
        processor: this.advanceDistortion
      },
577 578 579 580 581 582 583 584 585 586
      // Ignored events.
      'profiler': null,
      'function-creation': null,
      'function-move': null,
      'function-delete': null,
      'heap-sample-item': null,
      'current-time': null,  // Handled specially, not parsed.
      // Obsolete row types.
      'code-allocate': null,
      'begin-code-region': null,
587 588
      'end-code-region': null
    };
589

590 591 592 593 594 595
    this.preprocessJson = preprocessJson;
    this.cppEntriesProvider_ = cppEntriesProvider;
    this.callGraphSize_ = callGraphSize;
    this.ignoreUnknown_ = ignoreUnknown;
    this.stateFilter_ = stateFilter;
    this.runtimeTimerFilter_ = runtimeTimerFilter;
596
    this.sourceMap = this.loadSourceMap(sourceMap);
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    const ticks = this.ticks_ =
      { total: 0, unaccounted: 0, excluded: 0, gc: 0 };

    distortion = parseInt(distortion);
    // Convert picoseconds to nanoseconds.
    this.distortion_per_entry = isNaN(distortion) ? 0 : (distortion / 1000);
    this.distortion = 0;
    const rangelimits = range ? range.split(",") : [];
    const range_start = parseInt(rangelimits[0]);
    const 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)

    V8Profile.prototype.handleUnknownCode = function (
612
      operation, addr, opt_stackPos) {
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
      const op = Profile.Operation;
      switch (operation) {
        case op.MOVE:
          printErr(`Code move event for unknown code: 0x${addr.toString(16)}`);
          break;
        case op.DELETE:
          printErr(`Code delete event for unknown code: 0x${addr.toString(16)}`);
          break;
        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;
      }
    };
631

632 633 634 635
    if (preprocessJson) {
      this.profile_ = new JsonProfile();
    } else {
      this.profile_ = new V8Profile(separateIc, separateBytecodes,
636
        separateBuiltins, separateStubs, separateBaselineHandlers);
637 638 639 640 641 642 643 644 645 646 647
    }
    this.codeTypes_ = {};
    // Count each tick as a time unit.
    this.viewBuilder_ = new ViewBuilder(1);
    this.lastLogFileName_ = null;

    this.generation_ = 1;
    this.currentProducerProfile_ = null;
    this.onlySummary_ = onlySummary;
  }

648 649 650 651
  loadSourceMap(sourceMap) {
    if (!sourceMap) return null;
    // Overwrite the load function to load scripts synchronously.
    WebInspector.SourceMap.load = (sourceMapURL) => {
652
      const content = d8.file.read(sourceMapURL);
653 654 655 656 657 658
      const sourceMapObject = JSON.parse(content);
      return new SourceMap(sourceMapURL, sourceMapObject);
    };
    return WebInspector.SourceMap.load(sourceMap);
  }

659 660 661 662 663
  static VmStates = {
    JS: 0,
    GC: 1,
    PARSER: 2,
    BYTECODE_COMPILER: 3,
664
    // TODO(cbruni): add BASELINE_COMPILER
665 666 667 668 669
    COMPILER: 4,
    OTHER: 5,
    EXTERNAL: 6,
    IDLE: 7,
  };
670

671 672 673 674 675 676
  static CodeTypes = {
    CPP: 0,
    SHARED_LIB: 1
  };
  // Otherwise, this is JS-related code. We are not adding it to
  // codeTypes_ map because there can be zillions of them.
677

678 679
  static CALL_PROFILE_CUTOFF_PCT = 1.0;
  static CALL_GRAPH_SIZE = 5;
680

681 682 683 684 685
  /**
   * @override
   */
  printError(str) {
    printErr(str);
686 687
  }

688 689 690
  setCodeType(name, type) {
    this.codeTypes_[name] = TickProcessor.CodeTypes[type];
  }
691

692 693 694
  isSharedLibrary(name) {
    return this.codeTypes_[name] == TickProcessor.CodeTypes.SHARED_LIB;
  }
695

696 697 698
  isCppCode(name) {
    return this.codeTypes_[name] == TickProcessor.CodeTypes.CPP;
  }
699

700 701 702
  isJsCode(name) {
    return name !== "UNKNOWN" && !(name in this.codeTypes_);
  }
703

704
  async processLogFile(fileName) {
705 706 707
    this.lastLogFileName_ = fileName;
    let line;
    while (line = readline()) {
708
      await this.processLogLine(line);
709 710
    }
  }
711

712
  async processLogFileInTest(fileName) {
713 714
    // Hack file name to avoid dealing with platform specifics.
    this.lastLogFileName_ = 'v8.log';
715
    const contents = d8.file.read(fileName);
716
    await this.processLogChunk(contents);
717
  }
718

719 720 721
  processSharedLibrary(name, startAddr, endAddr, aslrSlide) {
    const entry = this.profile_.addLibrary(name, startAddr, endAddr, aslrSlide);
    this.setCodeType(entry.getName(), 'SHARED_LIB');
722
    this.cppEntriesProvider_.parseVmSymbols(
723 724 725 726
      name, startAddr, endAddr, aslrSlide, (fName, fStart, fEnd) => {
        this.profile_.addStaticCode(fName, fStart, fEnd);
        this.setCodeType(fName, 'CPP');
      });
727 728
  }

729
  processCodeCreation(type, kind, timestamp, start, size, name, maybe_func) {
730
    if (type != 'RegExp' && maybe_func.length) {
731 732 733 734 735 736 737
      const funcAddr = parseInt(maybe_func[0]);
      const state = Profile.parseState(maybe_func[1]);
      this.profile_.addFuncCode(type, name, timestamp, start, size, funcAddr, state);
    } else {
      this.profile_.addCode(type, name, timestamp, start, size);
    }
  }
738

739 740 741 742
  processCodeDeopt(
      timestamp, size, code, inliningId, scriptOffset, bailoutType,
      sourcePositionText, deoptReasonText) {
    this.profile_.deoptCode(timestamp, code, inliningId, scriptOffset,
743
      bailoutType, sourcePositionText, deoptReasonText);
744
  }
745

746 747 748
  processCodeMove(from, to) {
    this.profile_.moveCode(from, to);
  }
749

750 751 752
  processCodeDelete(start) {
    this.profile_.deleteCode(start);
  }
753

754 755 756 757 758 759
  processCodeSourceInfo(
      start, script, startPos, endPos, sourcePositions, inliningPositions,
      inlinedFunctions) {
    this.profile_.addSourcePositions(start, script, startPos,
      endPos, sourcePositions, inliningPositions, inlinedFunctions);
  }
760

761 762 763
  processScriptSource(script, url, source) {
    this.profile_.addScriptSource(script, url, source);
  }
764

765 766 767
  processFunctionMove(from, to) {
    this.profile_.moveFunc(from, to);
  }
768

769 770 771 772 773 774 775
  includeTick(vmState) {
    if (this.stateFilter_ !== null) {
      return this.stateFilter_ == vmState;
    } else if (this.runtimeTimerFilter_ !== null) {
      return this.currentRuntimeTimer == this.runtimeTimerFilter_;
    }
    return true;
776 777
  }

778 779 780
  processRuntimeTimerEvent(name) {
    this.currentRuntimeTimer = name;
  }
781

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  processTick(pc,
    ns_since_start,
    is_external_callback,
    tos_or_external_callback,
    vmState,
    stack) {
    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;
    }
    this.ticks_.total++;
    if (vmState == TickProcessor.VmStates.GC) this.ticks_.gc++;
    if (!this.includeTick(vmState)) {
      this.ticks_.excluded++;
      return;
    }
    if (is_external_callback) {
      // Don't use PC when in external callback code, as it can point
      // inside callback's code, and we will erroneously report
      // that a callback calls itself. Instead we use tos_or_external_callback,
      // as simply resetting PC will produce unaccounted ticks.
      pc = tos_or_external_callback;
805
      tos_or_external_callback = 0;
806 807 808 809 810 811 812
    } 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.
      const funcEntry = this.profile_.findEntry(tos_or_external_callback);
      if (!funcEntry || !funcEntry.isJSFunction || !funcEntry.isJSFunction()) {
        tos_or_external_callback = 0;
      }
813 814
    }

815
    this.profile_.recordTick(
816 817
      ns_since_start, vmState,
      this.processStack(pc, tos_or_external_callback, stack));
818
  }
819

820 821 822
  advanceDistortion() {
    this.distortion += this.distortion_per_entry;
  }
823

824 825 826 827
  processHeapSampleBegin(space, state, ticks) {
    if (space != 'Heap') return;
    this.currentProducerProfile_ = new CallTree();
  }
828

829 830
  processHeapSampleEnd(space, state) {
    if (space != 'Heap' || !this.currentProducerProfile_) return;
831

832 833 834 835 836 837
    print(`Generation ${this.generation_}:`);
    const tree = this.currentProducerProfile_;
    tree.computeTotalWeights();
    const producersView = this.viewBuilder_.buildView(tree);
    // Sort by total time, desc, then by name, desc.
    producersView.sort((rec1, rec2) =>
838
      rec2.totalTime - rec1.totalTime ||
839 840
      (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1));
    this.printHeavyProfile(producersView.head.children);
841

842 843
    this.currentProducerProfile_ = null;
    this.generation_++;
844 845
  }

846 847 848 849 850
  printVMSymbols() {
    console.log(
      JSON.stringify(this.profile_.serializeVMSymbols()));
  }

851 852 853 854 855 856 857 858 859
  printStatistics() {
    if (this.preprocessJson) {
      this.profile_.writeJson();
      return;
    }

    print(`Statistical profiling result from ${this.lastLogFileName_}` +
      `, (${this.ticks_.total} ticks, ${this.ticks_.unaccounted} unaccounted, ` +
      `${this.ticks_.excluded} excluded).`);
860

861

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

864 865 866 867
    const flatProfile = this.profile_.getFlatProfile();
    const flatView = this.viewBuilder_.buildView(flatProfile);
    // Sort by self time, desc, then by name, desc.
    flatView.sort((rec1, rec2) =>
868
      rec2.selfTime - rec1.selfTime ||
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
      (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1));
    let totalTicks = this.ticks_.total;
    if (this.ignoreUnknown_) {
      totalTicks -= this.ticks_.unaccounted;
    }
    const printAllTicks = !this.onlySummary_;

    // Count library ticks
    const flatViewNodes = flatView.head.children;

    let libraryTicks = 0;
    if (printAllTicks) this.printHeader('Shared libraries');
    this.printEntries(flatViewNodes, totalTicks, null,
      name => this.isSharedLibrary(name),
      (rec) => { libraryTicks += rec.selfTime; }, printAllTicks);
    const nonLibraryTicks = totalTicks - libraryTicks;

    let jsTicks = 0;
    if (printAllTicks) this.printHeader('JavaScript');
    this.printEntries(flatViewNodes, totalTicks, nonLibraryTicks,
      name => this.isJsCode(name),
      (rec) => { jsTicks += rec.selfTime; }, printAllTicks);

    let cppTicks = 0;
    if (printAllTicks) this.printHeader('C++');
    this.printEntries(flatViewNodes, totalTicks, nonLibraryTicks,
      name => this.isCppCode(name),
      (rec) => { cppTicks += rec.selfTime; }, printAllTicks);

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

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    if (printAllTicks) {
      print('\n [C++ entry points]:');
      print('   ticks    cpp   total   name');
      const c_entry_functions = this.profile_.getCEntryProfile();
      const total_c_entry = c_entry_functions[0].ticks;
      for (let i = 1; i < c_entry_functions.length; i++) {
        const c = c_entry_functions[i];
        this.printLine(c.name, c.ticks, total_c_entry, totalTicks);
      }

      this.printHeavyProfHeader();
      const heavyProfile = this.profile_.getBottomUpProfile();
      const 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((rec1, rec2) =>
925 926 927
        rec2.totalTime - rec1.totalTime ||
        (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1));
      this.printHeavyProfile(heavyView.head.children);
928 929 930
    }
  }

931 932 933
  printHeader(headerTitle) {
    print(`\n [${headerTitle}]:`);
    print('   ticks  total  nonlib   name');
934
  }
935

936 937 938 939 940 941 942 943
  printLine(
    entry, ticks, totalTicks, nonLibTicks) {
    const pct = ticks * 100 / totalTicks;
    const nonLibPct = nonLibTicks != null
      ? `${(ticks * 100 / nonLibTicks).toFixed(1).toString().padStart(5)}%  `
      : '        ';
    print(`${`  ${ticks.toString().padStart(5)}  ` +
      pct.toFixed(1).toString().padStart(5)}%  ${nonLibPct}${entry}`);
944 945
  }

946 947 948 949 950 951 952
  printHeavyProfHeader() {
    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');
953
  }
954

955 956 957 958 959 960 961
  processProfile(profile, filterP, func) {
    for (let i = 0, n = profile.length; i < n; ++i) {
      const rec = profile[i];
      if (!filterP(rec.internalFuncName)) {
        continue;
      }
      func(rec);
962
    }
963 964
  }

965 966 967 968 969
  getLineAndColumn(name) {
    const re = /:([0-9]+):([0-9]+)$/;
    const array = re.exec(name);
    if (!array) {
      return null;
970
    }
971 972
    return { line: array[1], column: array[2] };
  }
973

974 975 976
  hasSourceMap() {
    return this.sourceMap != null;
  }
977

978 979 980
  formatFunctionName(funcName) {
    if (!this.hasSourceMap()) {
      return funcName;
981
    }
982 983 984 985 986 987 988 989 990 991 992
    const lc = this.getLineAndColumn(funcName);
    if (lc == null) {
      return funcName;
    }
    // in source maps lines and columns are zero based
    const lineNumber = lc.line - 1;
    const column = lc.column - 1;
    const entry = this.sourceMap.findEntry(lineNumber, column);
    const sourceFile = entry[2];
    const sourceLine = entry[3] + 1;
    const sourceColumn = entry[4] + 1;
993

994
    return `${sourceFile}:${sourceLine}:${sourceColumn} -> ${funcName}`;
995
  }
996

997 998 999 1000 1001 1002 1003 1004 1005 1006
  printEntries(
        profile, totalTicks, nonLibTicks, filterP, callback, printAllTicks) {
    this.processProfile(profile, filterP, (rec) => {
      if (rec.selfTime == 0) return;
      callback(rec);
      const funcName = this.formatFunctionName(rec.internalFuncName);
      if (printAllTicks) {
        this.printLine(funcName, rec.selfTime, totalTicks, nonLibTicks);
      }
    });
1007 1008
  }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
  printHeavyProfile(profile, opt_indent) {
    const indent = opt_indent || 0;
    const indentStr = ''.padStart(indent);
    this.processProfile(profile, () => true, (rec) => {
      // Cut off too infrequent callers.
      if (rec.parentTotalPercent < TickProcessor.CALL_PROFILE_CUTOFF_PCT) return;
      const funcName = this.formatFunctionName(rec.internalFuncName);
      print(`${`  ${rec.totalTime.toString().padStart(5)}  ` +
        rec.parentTotalPercent.toFixed(1).toString().padStart(5)}%  ${indentStr}${funcName}`);
      // Limit backtrace depth.
      if (indent < 2 * this.callGraphSize_) {
        this.printHeavyProfile(rec.children, indent + 2);
      }
      // Delimit top-level functions.
      if (indent == 0) print('');
    });
1025 1026
  }
}