profile.mjs 39.8 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
// Copyright 2009 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.

28
import { CodeMap, CodeEntry } from "./codemap.mjs";
29
import { ConsArray } from "./consarray.mjs";
30
import { WebInspector } from "./sourcemap.mjs";
31

32
// Used to associate log entries with source positions in scripts.
33 34
// TODO: move to separate modules
export class SourcePosition {
35 36 37 38 39 40 41
  script = null;
  line = -1;
  column = -1;
  entries = [];
  isFunction = false;
  originalPosition = undefined;

42 43 44 45 46
  constructor(script, line, column) {
    this.script = script;
    this.line = line;
    this.column = column;
  }
47

48 49 50
  addEntry(entry) {
    this.entries.push(entry);
  }
51 52

  toString() {
53
    return `${this.script.name}:${this.line}:${this.column}`;
54
  }
55 56 57 58 59 60 61 62 63 64 65

  get functionPosition() {
    // TODO(cbruni)
    return undefined;
  }

  get toolTipDict() {
    return {
      title: this.toString(),
      __this__: this,
      script: this.script,
66
      entries: this.entries,
67 68
    }
  }
69 70 71
}

export class Script {
72
  url;
73
  source = "";
74
  name;
75
  sourcePosition = undefined;
76 77
  // Map<line, Map<column, SourcePosition>>
  lineToColumn = new Map();
78
  _entries = [];
79
  _sourceMapState = "unknown";
80 81

  constructor(id) {
82
    this.id = id;
83 84 85
    this.sourcePositions = [];
  }

86 87 88
  update(url, source) {
    this.url = url;
    this.name = Script.getShortestUniqueName(url, this);
89 90 91
    this.source = source;
  }

92 93 94 95
  get length() {
    return this.source.length;
  }

96 97 98 99
  get entries() {
    return this._entries;
  }

100 101 102 103 104 105 106 107
  get startLine() {
    return this.sourcePosition?.line ?? 1;
  }

  get sourceMapState() {
    return this._sourceMapState;
  }

108
  findFunctionSourcePosition(sourcePosition) {
109
    // TODO(cbruni): implement
110 111 112
    return undefined;
  }

113 114 115
  addSourcePosition(line, column, entry) {
    let sourcePosition = this.lineToColumn.get(line)?.get(column);
    if (sourcePosition === undefined) {
116
      sourcePosition = new SourcePosition(this, line, column,)
117
      this._addSourcePosition(line, column, sourcePosition);
118
    }
119 120 121
    if (this.sourcePosition === undefined && entry.entry?.type === "Script") {
      // Mark the source position of scripts, for inline scripts which don't
      // start at line 1.
122 123
      this.sourcePosition = sourcePosition;
    }
124
    sourcePosition.addEntry(entry);
125
    this._entries.push(entry);
126 127 128
    return sourcePosition;
  }

129
  _addSourcePosition(line, column, sourcePosition) {
130 131 132 133 134 135 136 137 138 139
    let columnToSourcePosition;
    if (this.lineToColumn.has(line)) {
      columnToSourcePosition = this.lineToColumn.get(line);
    } else {
      columnToSourcePosition = new Map();
      this.lineToColumn.set(line, columnToSourcePosition);
    }
    this.sourcePositions.push(sourcePosition);
    columnToSourcePosition.set(column, sourcePosition);
  }
140

141
  toString() {
142
    return `Script(${this.id}): ${this.name}`;
143
  }
144

145 146 147 148 149 150 151
  get toolTipDict() {
    return {
      title: this.toString(),
      __this__: this,
      id: this.id,
      url: this.url,
      source: this.source,
152
      sourcePositions: this.sourcePositions
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    }
  }

  static getShortestUniqueName(url, script) {
    const parts = url.split('/');
    const filename = parts[parts.length -1];
    const dict = this._dict ?? (this._dict = new Map());
    const matchingScripts = dict.get(filename);
    if (matchingScripts == undefined) {
      dict.set(filename, [script]);
      return filename;
    }
    // TODO: find shortest unique substring
    // Update all matching scripts to have a unique filename again.
    for (let matchingScript of matchingScripts) {
      matchingScript.name = script.url
    }
    matchingScripts.push(script);
    return url;
172
  }
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188

  ensureSourceMapCalculated(sourceMapFetchPrefix=undefined) {
    if (this._sourceMapState !== "unknown") return;

    const sourceMapURLMatch =
        this.source.match(/\/\/# sourceMappingURL=(.*)\n/);
    if (!sourceMapURLMatch) {
      this._sourceMapState = "none";
      return;
    }

    this._sourceMapState = "loading";
    let sourceMapURL = sourceMapURLMatch[1];
    (async () => {
      try {
        let sourceMapPayload;
189
        const options = { timeout: 15 };
190
        try {
191
          sourceMapPayload = await fetch(sourceMapURL, options);
192 193 194 195 196 197
        } catch (e) {
          if (e instanceof TypeError && sourceMapFetchPrefix) {
            // Try again with fetch prefix.
            // TODO(leszeks): Remove the retry once the prefix is
            // configurable.
            sourceMapPayload =
198
                await fetch(sourceMapFetchPrefix + sourceMapURL, options);
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 224 225 226 227 228 229 230 231 232 233 234
          } else {
            throw e;
          }
        }
        sourceMapPayload = await sourceMapPayload.text();

        if (sourceMapPayload.startsWith(')]}')) {
          sourceMapPayload =
              sourceMapPayload.substring(sourceMapPayload.indexOf('\n'));
        }
        sourceMapPayload = JSON.parse(sourceMapPayload);
        const sourceMap =
            new WebInspector.SourceMap(sourceMapURL, sourceMapPayload);

        const startLine = this.startLine;
        for (const sourcePosition of this.sourcePositions) {
          const line = sourcePosition.line - startLine;
          const column = sourcePosition.column - 1;
          const mapping = sourceMap.findEntry(line, column);
          if (mapping) {
            sourcePosition.originalPosition = {
              source: new URL(mapping[2], sourceMapURL).href,
              line: mapping[3] + 1,
              column: mapping[4] + 1
            };
          } else {
            sourcePosition.originalPosition = {source: null, line:0, column:0};
          }
        }
        this._sourceMapState = "loaded";
      } catch (e) {
        console.error(e);
        this._sourceMapState = "failed";
      }
    })();
  }
235 236
}

237

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
const kOffsetPairRegex = /C([0-9]+)O([0-9]+)/g;
class SourcePositionTable {
  constructor(encodedTable) {
    this._offsets = [];
    while (true) {
      const regexResult = kOffsetPairRegex.exec(encodedTable);
      if (!regexResult) break;
      const codeOffset = parseInt(regexResult[1]);
      const scriptOffset = parseInt(regexResult[2]);
      if (isNaN(codeOffset) || isNaN(scriptOffset)) continue;
      this._offsets.push({code: codeOffset, script: scriptOffset});
    }
  }

  getScriptOffset(codeOffset) {
    if (codeOffset < 0) {
      throw new Exception(`Invalid codeOffset=${codeOffset}, should be >= 0`);
    }
    for (let i = this.offsetTable.length - 1; i >= 0; i--) {
      const offset = this._offsets[i];
      if (offset.code <= codeOffset) {
        return offset.script;
      }
    }
    return this._offsets[0].script;
  }
}


267
class SourceInfo {
268 269 270 271 272 273 274
  script;
  start;
  end;
  positions;
  inlined;
  fns;
  disassemble;
275

276 277 278
  setSourcePositionInfo(
        script, startPos, endPos, sourcePositionTableData, inliningPositions,
        inlinedFunctions) {
279 280 281
    this.script = script;
    this.start = startPos;
    this.end = endPos;
282
    this.positions = sourcePositionTableData;
283 284
    this.inlined = inliningPositions;
    this.fns = inlinedFunctions;
285
    this.sourcePositionTable = new SourcePositionTable(sourcePositionTableData);
286
  }
287 288 289 290

  setDisassemble(code) {
    this.disassemble = code;
  }
291 292 293 294

  getSourceCode() {
    return this.script.source?.substring(this.start, this.end);
  }
295 296
}

297 298 299 300
const kProfileOperationMove = 0;
const kProfileOperationDelete = 1;
const kProfileOperationTick = 2;

301 302 303 304 305 306
/**
 * Creates a profile object for processing profiling-related events
 * and calculating function execution times.
 *
 * @constructor
 */
307 308 309 310
export class Profile {
  codeMap_ = new CodeMap();
  topDownTree_ = new CallTree();
  bottomUpTree_ = new CallTree();
311
  c_entries_ = {__proto__:null};
312 313
  scripts_ = [];
  urlToScript_ = new Map();
314
  warnings = new Set();
315

316 317 318 319 320 321 322 323
  serializeVMSymbols() {
    let result = this.codeMap_.getAllStaticEntriesWithAddresses();
    result.concat(this.codeMap_.getAllLibraryEntriesWithAddresses())
    return result.map(([startAddress, codeEntry]) => {
      return [codeEntry.getName(), startAddress, startAddress + codeEntry.size]
    });
  }

324 325
  /**
   * Returns whether a function with the specified name must be skipped.
326
   * Should be overridden by subclasses.
327 328 329 330 331 332
   *
   * @param {string} name Function name.
   */
  skipThisFunction(name) {
    return false;
  }
333

334 335 336 337 338 339 340
  /**
   * Enum for profiler operations that involve looking up existing
   * code entries.
   *
   * @enum {number}
   */
  static Operation = {
341 342 343
    MOVE: kProfileOperationMove,
    DELETE: kProfileOperationDelete,
    TICK: kProfileOperationTick
344
  }
345

346 347 348 349 350 351 352
  /**
   * Enum for code state regarding its dynamic optimization.
   *
   * @enum {number}
   */
  static CodeState = {
    COMPILED: 0,
353
    IGNITION: 1,
354 355
    SPARKPLUG: 2,
    MAGLEV: 4,
356
    TURBOFAN: 5,
357 358
  }

359 360 361 362 363
  static VMState = {
    JS: 0,
    GC: 1,
    PARSER: 2,
    BYTECODE_COMPILER: 3,
364
    // TODO(cbruni): add SPARKPLUG_COMPILER
365 366 367 368 369 370 371 372 373 374 375
    COMPILER: 4,
    OTHER: 5,
    EXTERNAL: 6,
    IDLE: 7,
  }

  static CodeType = {
    CPP: 0,
    SHARED_LIB: 1
  }

376 377 378 379 380 381 382 383 384
  /**
   * Parser for dynamic code optimization state.
   */
  static parseState(s) {
    switch (s) {
      case '':
        return this.CodeState.COMPILED;
      case '~':
        return this.CodeState.IGNITION;
385
      case '^':
386 387 388
        return this.CodeState.SPARKPLUG;
      case '+':
        return this.CodeState.MAGLEV;
389 390 391 392
      case '*':
        return this.CodeState.TURBOFAN;
    }
    throw new Error(`unknown code state: ${s}`);
393
  }
394

395 396 397 398 399
  static getKindFromState(state) {
    if (state === this.CodeState.COMPILED) {
      return "Builtin";
    } else if (state === this.CodeState.IGNITION) {
      return "Unopt";
400 401 402 403
    } else if (state === this.CodeState.SPARKPLUG) {
      return "Sparkplug";
    } else if (state === this.CodeState.MAGLEV) {
      return "Maglev";
404 405 406 407 408 409
    } else if (state === this.CodeState.TURBOFAN) {
      return "Opt";
    }
    throw new Error(`unknown code state: ${state}`);
  }

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
  static vmStateString(state) {
    switch (state) {
      case this.VMState.JS:
        return 'JS';
      case this.VMState.GC:
        return 'GC';
      case this.VMState.PARSER:
        return 'Parse';
      case this.VMState.BYTECODE_COMPILER:
        return 'Compile Bytecode';
      case this.VMState.COMPILER:
        return 'Compile';
      case this.VMState.OTHER:
        return 'Other';
      case this.VMState.EXTERNAL:
        return 'External';
      case this.VMState.IDLE:
        return 'Idle';
    }
    return 'unknown';
  }

432 433
  /**
   * Called whenever the specified operation has failed finding a function
434
   * containing the specified address. Should be overridden by subclasses.
435 436 437 438 439 440 441 442 443
   * See the Profile.Operation enum for the list of
   * possible operations.
   *
   * @param {number} operation Operation.
   * @param {number} addr Address of the unknown code.
   * @param {number} opt_stackPos If an unknown address is encountered
   *     during stack strace processing, specifies a position of the frame
   *     containing the address.
   */
444
  handleUnknownCode(operation, addr, opt_stackPos) { }
445 446 447 448 449 450 451 452 453

  /**
   * Registers a library.
   *
   * @param {string} name Code entry name.
   * @param {number} startAddr Starting address.
   * @param {number} endAddr Ending address.
   */
  addLibrary(name, startAddr, endAddr) {
454
    const entry = new CodeEntry(endAddr - startAddr, name, 'SHARED_LIB');
455 456 457
    this.codeMap_.addLibrary(startAddr, entry);
    return entry;
  }
458

459 460 461 462 463 464 465 466
  /**
   * Registers statically compiled code entry.
   *
   * @param {string} name Code entry name.
   * @param {number} startAddr Starting address.
   * @param {number} endAddr Ending address.
   */
  addStaticCode(name, startAddr, endAddr) {
467
    const entry = new CodeEntry(endAddr - startAddr, name, 'CPP');
468 469 470
    this.codeMap_.addStaticCode(startAddr, entry);
    return entry;
  }
471

472 473 474 475 476 477 478 479 480
  /**
   * Registers dynamic (JIT-compiled) code entry.
   *
   * @param {string} type Code entry type.
   * @param {string} name Code entry name.
   * @param {number} start Starting address.
   * @param {number} size Code entry size.
   */
  addCode(type, name, timestamp, start, size) {
481
    const entry = new DynamicCodeEntry(size, type, name);
482 483 484
    this.codeMap_.addCode(start, entry);
    return entry;
  }
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
  /**
   * Registers dynamic (JIT-compiled) code entry or entries that overlap with
   * static entries (like builtins).
   *
   * @param {string} type Code entry type.
   * @param {string} name Code entry name.
   * @param {number} start Starting address.
   * @param {number} size Code entry size.
   */
  addAnyCode(type, name, timestamp, start, size) {
    const entry = new DynamicCodeEntry(size, type, name);
    this.codeMap_.addAnyCode(start, entry);
    return entry;
  }

501 502 503 504 505 506 507 508 509 510 511 512 513
  /**
   * Registers dynamic (JIT-compiled) code entry.
   *
   * @param {string} type Code entry type.
   * @param {string} name Code entry name.
   * @param {number} start Starting address.
   * @param {number} size Code entry size.
   * @param {number} funcAddr Shared function object address.
   * @param {Profile.CodeState} state Optimization state.
   */
  addFuncCode(type, name, timestamp, start, size, funcAddr, state) {
    // As code and functions are in the same address space,
    // it is safe to put them in a single code map.
514
    let func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
515
    if (func === null) {
516 517 518 519 520 521
      func = new FunctionEntry(name);
      this.codeMap_.addCode(funcAddr, func);
    } else if (func.name !== name) {
      // Function object has been overwritten with a new one.
      func.name = name;
    }
522
    let entry = this.codeMap_.findDynamicEntryByStartAddress(start);
523
    if (entry !== null) {
524 525 526 527 528 529 530 531
      if (entry.size === size && entry.func === func) {
        // Entry state has changed.
        entry.state = state;
      } else {
        this.codeMap_.deleteCode(start);
        entry = null;
      }
    }
532
    if (entry === null) {
533 534 535 536 537
      entry = new DynamicFuncCodeEntry(size, type, func, state);
      this.codeMap_.addCode(start, entry);
    }
    return entry;
  }
538

539 540 541 542 543 544 545 546 547 548
  /**
   * Reports about moving of a dynamic code entry.
   *
   * @param {number} from Current code entry address.
   * @param {number} to New code entry address.
   */
  moveCode(from, to) {
    try {
      this.codeMap_.moveCode(from, to);
    } catch (e) {
549
      this.handleUnknownCode(kProfileOperationMove, from);
550 551
    }
  }
552

553
  deoptCode(timestamp, code, inliningId, scriptOffset, bailoutType,
554
    sourcePositionText, deoptReasonText) {
555
  }
556 557 558 559 560 561 562 563

  /**
   * Reports about deletion of a dynamic code entry.
   *
   * @param {number} start Starting address.
   */
  deleteCode(start) {
    try {
564
      this.codeMap_.deleteCode(start);
565
    } catch (e) {
566
      this.handleUnknownCode(kProfileOperationDelete, start);
567 568 569
    }
  }

570 571 572
  /**
   * Adds source positions for given code.
   */
573
  addSourcePositions(start, scriptId, startPos, endPos, sourcePositionTable,
574
        inliningPositions, inlinedFunctions) {
575 576
    const script = this.getOrCreateScript(scriptId);
    const entry = this.codeMap_.findDynamicEntryByStartAddress(start);
577
    if (entry === null) return;
578 579 580 581 582 583
    // Resolve the inlined functions list.
    if (inlinedFunctions.length > 0) {
      inlinedFunctions = inlinedFunctions.substring(1).split("S");
      for (let i = 0; i < inlinedFunctions.length; i++) {
        const funcAddr = parseInt(inlinedFunctions[i]);
        const func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
584
        if (func === null || func.funcId === undefined) {
585
          // TODO: fix
586
          this.warnings.add(`Could not find function ${inlinedFunctions[i]}`);
587 588 589 590 591 592 593 594 595
          inlinedFunctions[i] = null;
        } else {
          inlinedFunctions[i] = func.funcId;
        }
      }
    } else {
      inlinedFunctions = [];
    }

596
    this.getOrCreateSourceInfo(entry).setSourcePositionInfo(
597 598
      script, startPos, endPos, sourcePositionTable, inliningPositions,
      inlinedFunctions);
599 600
  }

601 602
  addDisassemble(start, kind, disassemble) {
    const entry = this.codeMap_.findDynamicEntryByStartAddress(start);
603 604 605
    if (entry !== null) {
      this.getOrCreateSourceInfo(entry).setDisassemble(disassemble);
    }
606
    return entry;
607 608 609 610 611 612
  }

  getOrCreateSourceInfo(entry) {
    return entry.source ?? (entry.source = new SourceInfo());
  }

613
  addScriptSource(id, url, source) {
614 615
    const script = this.getOrCreateScript(id);
    script.update(url, source);
616
    this.urlToScript_.set(url, script);
617 618
  }

619 620
  getOrCreateScript(id) {
    let script = this.scripts_[id];
621
    if (script === undefined) {
622 623 624 625 626 627
      script = new Script(id);
      this.scripts_[id] = script;
    }
    return script;
  }

628 629
  getScript(url) {
    return this.urlToScript_.get(url);
630 631
  }

632 633 634 635 636 637 638 639 640 641 642
  /**
   * Reports about moving of a dynamic code entry.
   *
   * @param {number} from Current code entry address.
   * @param {number} to New code entry address.
   */
  moveFunc(from, to) {
    if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
      this.codeMap_.moveCode(from, to);
    }
  }
643

644 645 646 647 648 649 650 651
  /**
   * Retrieves a code entry by an address.
   *
   * @param {number} addr Entry address.
   */
  findEntry(addr) {
    return this.codeMap_.findEntry(addr);
  }
652

653 654 655 656
  /**
   * Records a tick event. Stack must contain a sequence of
   * addresses starting with the program counter value.
   *
657
   * @param {number[]} stack Stack sample.
658 659
   */
  recordTick(time_ns, vmState, stack) {
660 661 662 663
    const {nameStack, entryStack} = this.resolveAndFilterFuncs_(stack);
    this.bottomUpTree_.addPath(nameStack);
    nameStack.reverse();
    this.topDownTree_.addPath(nameStack);
664
    return entryStack;
665
  }
666

667 668 669 670
  /**
   * Translates addresses into function names and filters unneeded
   * functions.
   *
671
   * @param {number[]} stack Stack sample.
672 673
   */
  resolveAndFilterFuncs_(stack) {
674 675
    const nameStack = [];
    const entryStack = [];
676 677 678
    let last_seen_c_function = '';
    let look_for_first_c_function = false;
    for (let i = 0; i < stack.length; ++i) {
679 680
      const pc = stack[i];
      const entry = this.codeMap_.findEntry(pc);
681
      if (entry !== null) {
682
        entryStack.push(entry);
683
        const name = entry.getName();
684 685 686 687 688 689 690
        if (i === 0 && (entry.type === 'CPP' || entry.type === 'SHARED_LIB')) {
          look_for_first_c_function = true;
        }
        if (look_for_first_c_function && entry.type === 'CPP') {
          last_seen_c_function = name;
        }
        if (!this.skipThisFunction(name)) {
691
          nameStack.push(name);
692 693
        }
      } else {
694
        this.handleUnknownCode(kProfileOperationTick, pc, i);
695 696
        if (i === 0) nameStack.push("UNKNOWN");
        entryStack.push(pc);
697
      }
698
      if (look_for_first_c_function && i > 0 &&
699 700
          (entry === null || entry.type !== 'CPP')
          && last_seen_c_function !== '') {
701 702 703 704 705
        if (this.c_entries_[last_seen_c_function] === undefined) {
          this.c_entries_[last_seen_c_function] = 0;
        }
        this.c_entries_[last_seen_c_function]++;
        look_for_first_c_function = false;  // Found it, we're done.
706 707
      }
    }
708
    return {nameStack, entryStack};
709 710
  }

711 712 713 714 715 716 717 718
  /**
   * Performs a BF traversal of the top down call graph.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  traverseTopDownTree(f) {
    this.topDownTree_.traverse(f);
  }
719

720 721 722 723 724 725 726 727
  /**
   * Performs a BF traversal of the bottom up call graph.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  traverseBottomUpTree(f) {
    this.bottomUpTree_.traverse(f);
  }
728

729 730 731 732 733 734 735 736 737
  /**
   * Calculates a top down profile for a node with the specified label.
   * If no name specified, returns the whole top down calls tree.
   *
   * @param {string} opt_label Node label.
   */
  getTopDownProfile(opt_label) {
    return this.getTreeProfile_(this.topDownTree_, opt_label);
  }
738

739 740 741 742 743 744 745 746
  /**
   * Calculates a bottom up profile for a node with the specified label.
   * If no name specified, returns the whole bottom up calls tree.
   *
   * @param {string} opt_label Node label.
   */
  getBottomUpProfile(opt_label) {
    return this.getTreeProfile_(this.bottomUpTree_, opt_label);
747 748
  }

749 750 751 752 753 754 755 756 757 758 759
  /**
   * Helper function for calculating a tree profile.
   *
   * @param {Profile.CallTree} tree Call tree.
   * @param {string} opt_label Node label.
   */
  getTreeProfile_(tree, opt_label) {
    if (!opt_label) {
      tree.computeTotalWeights();
      return tree;
    } else {
760
      const subTree = tree.cloneSubtree(opt_label);
761 762 763 764
      subTree.computeTotalWeights();
      return subTree;
    }
  }
765

766 767 768 769 770 771 772
  /**
   * Calculates a flat profile of callees starting from a node with
   * the specified label. If no name specified, starts from the root.
   *
   * @param {string} opt_label Starting node label.
   */
  getFlatProfile(opt_label) {
773 774
    const counters = new CallTree();
    const rootLabel = opt_label || CallTree.ROOT_NODE_LABEL;
775
    const precs = {__proto__:null};
776
    precs[rootLabel] = 0;
777
    const root = counters.findOrAddChild(rootLabel);
778 779 780 781 782 783 784

    this.topDownTree_.computeTotalWeights();
    this.topDownTree_.traverseInDepth(
      function onEnter(node) {
        if (!(node.label in precs)) {
          precs[node.label] = 0;
        }
785
        const nodeLabelIsRootLabel = node.label == rootLabel;
786 787 788 789 790
        if (nodeLabelIsRootLabel || precs[rootLabel] > 0) {
          if (precs[rootLabel] == 0) {
            root.selfWeight += node.selfWeight;
            root.totalWeight += node.totalWeight;
          } else {
791
            const rec = root.findOrAddChild(node.label);
792 793 794 795
            rec.selfWeight += node.selfWeight;
            if (nodeLabelIsRootLabel || precs[node.label] == 0) {
              rec.totalWeight += node.totalWeight;
            }
796
          }
797
          precs[node.label]++;
798
        }
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
      },
      function onExit(node) {
        if (node.label == rootLabel || precs[rootLabel] > 0) {
          precs[node.label]--;
        }
      },
      null);

    if (!opt_label) {
      // If we have created a flat profile for the whole program, we don't
      // need an explicit root in it. Thus, replace the counters tree
      // root with the node corresponding to the whole program.
      counters.root_ = root;
    } else {
      // Propagate weights so percents can be calculated correctly.
      counters.getRoot().selfWeight = root.selfWeight;
      counters.getRoot().totalWeight = root.totalWeight;
    }
    return counters;
818 819
  }

820
  getCEntryProfile() {
821 822 823 824
    const result = [new CEntryNode("TOTAL", 0)];
    let total_ticks = 0;
    for (let f in this.c_entries_) {
      const ticks = this.c_entries_[f];
825 826 827 828
      total_ticks += ticks;
      result.push(new CEntryNode(f, ticks));
    }
    result[0].ticks = total_ticks;  // Sorting will keep this at index 0.
829
    result.sort((n1, n2) => n2.ticks - n1.ticks || (n2.name < n1.name ? -1 : 1));
830
    return result;
831 832 833
  }


834 835 836 837
  /**
   * Cleans up function entries that are not referenced by code entries.
   */
  cleanUpFuncEntries() {
838 839 840
    const referencedFuncEntries = [];
    const entries = this.codeMap_.getAllDynamicEntriesWithAddresses();
    for (let i = 0, l = entries.length; i < l; ++i) {
841 842 843
      if (entries[i][1].constructor === FunctionEntry) {
        entries[i][1].used = false;
      }
844
    }
845
    for (let i = 0, l = entries.length; i < l; ++i) {
846 847 848
      if ("func" in entries[i][1]) {
        entries[i][1].func.used = true;
      }
849
    }
850
    for (let i = 0, l = entries.length; i < l; ++i) {
851 852 853 854
      if (entries[i][1].constructor === FunctionEntry &&
        !entries[i][1].used) {
        this.codeMap_.deleteCode(entries[i][0]);
      }
855 856
    }
  }
857 858 859 860 861 862 863 864
}

class CEntryNode {
  constructor(name, ticks) {
    this.name = name;
    this.ticks = ticks;
  }
}
865 866 867 868 869 870 871 872 873 874


/**
 * Creates a dynamic code entry.
 *
 * @param {number} size Code size.
 * @param {string} type Code type.
 * @param {string} name Function name.
 * @constructor
 */
875 876 877 878
class DynamicCodeEntry extends CodeEntry {
  constructor(size, type, name) {
    super(size, name, type);
  }
879

880 881 882
  getName() {
    return this.type + ': ' + this.name;
  }
883

884 885 886 887 888 889
  /**
   * Returns raw node name (without type decoration).
   */
  getRawName() {
    return this.name;
  }
890

891 892 893
  isJSFunction() {
    return false;
  }
894

895 896 897 898
  toString() {
    return this.getName() + ': ' + this.size.toString(16);
  }
}
899 900 901 902 903 904 905


/**
 * Creates a dynamic code entry.
 *
 * @param {number} size Code size.
 * @param {string} type Code type.
906
 * @param {FunctionEntry} func Shared function entry.
907 908 909
 * @param {Profile.CodeState} state Code optimization state.
 * @constructor
 */
910 911 912 913
class DynamicFuncCodeEntry extends CodeEntry {
  constructor(size, type, func, state) {
    super(size, '', type);
    this.func = func;
914
    func.addDynamicCode(this);
915 916
    this.state = state;
  }
917

918 919 920 921
  get functionName() {
    return this.func.functionName;
  }

922 923 924 925
  getSourceCode() {
    return this.source?.getSourceCode();
  }

926
  static STATE_PREFIX = ["", "~", "^", "-", "+", "*"];
927 928 929
  getState() {
    return DynamicFuncCodeEntry.STATE_PREFIX[this.state];
  }
930

931
  getName() {
932
    const name = this.func.getName();
933 934
    return this.type + ': ' + this.getState() + name;
  }
935

936 937 938 939 940 941
  /**
   * Returns raw node name (without type decoration).
   */
  getRawName() {
    return this.func.getName();
  }
942

943 944 945
  isJSFunction() {
    return true;
  }
946

947 948 949 950
  toString() {
    return this.getName() + ': ' + this.size.toString(16);
  }
}
951 952 953 954 955 956 957

/**
 * Creates a shared function object entry.
 *
 * @param {string} name Function name.
 * @constructor
 */
958
class FunctionEntry extends CodeEntry {
959

960
  // Contains the list of generated code for this function.
961
  /** @type {Set<DynamicCodeEntry>} */
962 963
  _codeEntries = new Set();

964 965
  constructor(name) {
    super(0, name);
966 967
    const index = name.lastIndexOf(' ');
    this.functionName = 1 <= index ? name.substring(0, index) : '<anonymous>';
968
  }
969

970 971 972 973 974 975 976 977 978 979 980 981
  addDynamicCode(code) {
    if (code.func != this) {
      throw new Error("Adding dynamic code to wrong function");
    }
    this._codeEntries.add(code);
  }

  getSourceCode() {
    // All code entries should map to the same source positions.
    return this._codeEntries.values().next().value.getSourceCode();
  }

982 983 984 985
  get codeEntries() {
    return this._codeEntries;
  }

986 987 988 989
  /**
   * Returns node name.
   */
  getName() {
990
    let name = this.name;
991
    if (name.length == 0) {
992
      return '<anonymous>';
993 994
    } else if (name.charAt(0) == ' ') {
      // An anonymous function with location: " aaa.js:10".
995
      return `<anonymous>${name}`;
996 997 998 999
    }
    return name;
  }
}
1000 1001 1002 1003 1004 1005

/**
 * Constructs a call graph.
 *
 * @constructor
 */
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
class CallTree {
  root_ = new CallTreeNode(CallTree.ROOT_NODE_LABEL);
  totalsComputed_ = false;

  /**
   * The label of the root node.
   */
  static ROOT_NODE_LABEL = '';

  /**
   * Returns the tree root.
   */
  getRoot() {
    return this.root_;
1020 1021
  }

1022 1023 1024
  /**
   * Adds the specified call path, constructing nodes as necessary.
   *
1025
   * @param {string[]} path Call path.
1026 1027
   */
  addPath(path) {
1028
    if (path.length == 0) return;
1029 1030
    let curr = this.root_;
    for (let i = 0; i < path.length; ++i) {
1031 1032 1033 1034
      curr = curr.findOrAddChild(path[i]);
    }
    curr.selfWeight++;
    this.totalsComputed_ = false;
1035 1036
  }

1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
  /**
   * Finds an immediate child of the specified parent with the specified
   * label, creates a child node if necessary. If a parent node isn't
   * specified, uses tree root.
   *
   * @param {string} label Child node label.
   */
  findOrAddChild(label) {
    return this.root_.findOrAddChild(label);
  }
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  /**
   * Creates a subtree by cloning and merging all subtrees rooted at nodes
   * with a given label. E.g. cloning the following call tree on label 'A'
   * will give the following result:
   *
   *           <A>--<B>                                     <B>
   *          /                                            /
   *     <root>             == clone on 'A' ==>  <root>--<A>
   *          \                                            \
   *           <C>--<A>--<D>                                <D>
   *
   * And <A>'s selfWeight will be the sum of selfWeights of <A>'s from the
   * source call tree.
   *
   * @param {string} label The label of the new root node.
   */
  cloneSubtree(label) {
1065
    const subTree = new CallTree();
1066 1067 1068 1069
    this.traverse((node, parent) => {
      if (!parent && node.label != label) {
        return null;
      }
1070
      const child = (parent ? parent : subTree).findOrAddChild(node.label);
1071 1072
      child.selfWeight += node.selfWeight;
      return child;
1073
    });
1074
    return subTree;
1075 1076
  }

1077 1078 1079 1080 1081 1082 1083 1084
  /**
   * Computes total weights in the call graph.
   */
  computeTotalWeights() {
    if (this.totalsComputed_) return;
    this.root_.computeTotalWeight();
    this.totalsComputed_ = true;
  }
1085

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  /**
   * Traverses the call graph in preorder. This function can be used for
   * building optionally modified tree clones. This is the boilerplate code
   * for this scenario:
   *
   * callTree.traverse(function(node, parentClone) {
   *   var nodeClone = cloneNode(node);
   *   if (parentClone)
   *     parentClone.addChild(nodeClone);
   *   return nodeClone;
   * });
   *
   * @param {function(CallTreeNode, *)} f Visitor function.
   *    The second parameter is the result of calling 'f' on the parent node.
   */
  traverse(f) {
1102
    const pairsToProcess = new ConsArray();
1103 1104
    pairsToProcess.concat([{ node: this.root_, param: null }]);
    while (!pairsToProcess.atEnd()) {
1105 1106 1107 1108
      const pair = pairsToProcess.next();
      const node = pair.node;
      const newParam = f(node, pair.param);
      const morePairsToProcess = [];
1109 1110 1111 1112 1113
      node.forEachChild((child) => {
        morePairsToProcess.push({ node: child, param: newParam });
      });
      pairsToProcess.concat(morePairsToProcess);
    }
1114
  }
1115 1116 1117 1118 1119 1120 1121 1122 1123

  /**
   * Performs an indepth call graph traversal.
   *
   * @param {function(CallTreeNode)} enter A function called
   *     prior to visiting node's children.
   * @param {function(CallTreeNode)} exit A function called
   *     after visiting node's children.
   */
1124
  traverseInDepth(enter, exit) {
1125 1126 1127 1128 1129 1130 1131 1132
    function traverse(node) {
      enter(node);
      node.forEachChild(traverse);
      exit(node);
    }
    traverse(this.root_);
  }
}
1133 1134 1135 1136 1137 1138


/**
 * Constructs a call graph node.
 *
 * @param {string} label Node label.
1139
 * @param {CallTreeNode} opt_parent Node parent.
1140
 */
1141
class CallTreeNode {
1142 1143

  constructor(label, opt_parent) {
1144 1145 1146 1147 1148 1149
    // Node self weight (how many times this node was the last node in
    // a call path).
    this.selfWeight = 0;
    // Node total weight (includes weights of all children).
    this.totalWeight = 0;
    this. children = { __proto__:null };
1150 1151 1152
    this.label = label;
    this.parent = opt_parent;
  }
1153 1154


1155 1156 1157 1158 1159 1160
  /**
   * Adds a child node.
   *
   * @param {string} label Child node label.
   */
  addChild(label) {
1161
    const child = new CallTreeNode(label, this);
1162 1163 1164
    this.children[label] = child;
    return child;
  }
1165

1166 1167 1168 1169
  /**
   * Computes node's total weight.
   */
  computeTotalWeight() {
1170
    let totalWeight = this.selfWeight;
1171 1172 1173 1174
    this.forEachChild(function (child) {
      totalWeight += child.computeTotalWeight();
    });
    return this.totalWeight = totalWeight;
1175
  }
1176

1177 1178 1179 1180
  /**
   * Returns all node's children as an array.
   */
  exportChildren() {
1181
    const result = [];
1182 1183 1184
    this.forEachChild(function (node) { result.push(node); });
    return result;
  }
1185

1186 1187 1188 1189 1190 1191
  /**
   * Finds an immediate child with the specified label.
   *
   * @param {string} label Child node label.
   */
  findChild(label) {
1192 1193
    const found = this.children[label];
    return found === undefined ? null : found;
1194 1195
  }

1196 1197 1198 1199 1200 1201 1202
  /**
   * Finds an immediate child with the specified label, creates a child
   * node if necessary.
   *
   * @param {string} label Child node label.
   */
  findOrAddChild(label) {
1203 1204 1205
    const found = this.findChild(label)
    if (found === null) return this.addChild(label);
    return found;
1206
  }
1207

1208 1209 1210 1211 1212 1213
  /**
   * Calls the specified function for every child.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  forEachChild(f) {
1214
    for (let c in this.children) {
1215 1216
      f(this.children[c]);
    }
1217 1218
  }

1219 1220 1221 1222 1223 1224
  /**
   * Walks up from the current node up to the call tree root.
   *
   * @param {function(CallTreeNode)} f Visitor function.
   */
  walkUpToRoot(f) {
1225
    for (let curr = this; curr !== null; curr = curr.parent) {
1226 1227 1228
      f(curr);
    }
  }
1229

1230 1231 1232
  /**
   * Tries to find a node with the specified path.
   *
1233
   * @param {string[]} labels The path.
1234 1235 1236
   * @param {function(CallTreeNode)} opt_f Visitor function.
   */
  descendToChild(labels, opt_f) {
1237 1238 1239
    let curr = this;
    for (let pos = 0; pos < labels.length && curr != null; pos++) {
      const child = curr.findChild(labels[pos]);
1240 1241 1242 1243
      if (opt_f) {
        opt_f(child, pos);
      }
      curr = child;
1244
    }
1245
    return curr;
1246
  }
1247
}
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258

export function JsonProfile() {
  this.codeMap_ = new CodeMap();
  this.codeEntries_ = [];
  this.functionEntries_ = [];
  this.ticks_ = [];
  this.scripts_ = [];
}

JsonProfile.prototype.addLibrary = function (
  name, startAddr, endAddr) {
1259
  const entry = new CodeEntry(
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    endAddr - startAddr, name, 'SHARED_LIB');
  this.codeMap_.addLibrary(startAddr, entry);

  entry.codeId = this.codeEntries_.length;
  this.codeEntries_.push({ name: entry.name, type: entry.type });
  return entry;
};

JsonProfile.prototype.addStaticCode = function (
  name, startAddr, endAddr) {
1270
  const entry = new CodeEntry(
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
    endAddr - startAddr, name, 'CPP');
  this.codeMap_.addStaticCode(startAddr, entry);

  entry.codeId = this.codeEntries_.length;
  this.codeEntries_.push({ name: entry.name, type: entry.type });
  return entry;
};

JsonProfile.prototype.addCode = function (
  kind, name, timestamp, start, size) {
  let codeId = this.codeEntries_.length;
  // Find out if we have a static code entry for the code. If yes, we will
  // make sure it is written to the JSON file just once.
  let staticEntry = this.codeMap_.findAddress(start);
  if (staticEntry && staticEntry.entry.type === 'CPP') {
    codeId = staticEntry.entry.codeId;
  }

1289
  const entry = new CodeEntry(size, name, 'CODE');
1290 1291 1292 1293 1294 1295 1296
  this.codeMap_.addCode(start, entry);

  entry.codeId = codeId;
  this.codeEntries_[codeId] = {
    name: entry.name,
    timestamp: timestamp,
    type: entry.type,
1297
    kind: kind,
1298 1299 1300 1301 1302 1303 1304 1305 1306
  };

  return entry;
};

JsonProfile.prototype.addFuncCode = function (
  kind, name, timestamp, start, size, funcAddr, state) {
  // As code and functions are in the same address space,
  // it is safe to put them in a single code map.
1307
  let func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
1308
  if (!func) {
1309
    func = new CodeEntry(0, name, 'SFI');
1310 1311 1312
    this.codeMap_.addCode(funcAddr, func);

    func.funcId = this.functionEntries_.length;
1313
    this.functionEntries_.push({ name, codes: [] });
1314 1315 1316 1317 1318
  } else if (func.name !== name) {
    // Function object has been overwritten with a new one.
    func.name = name;

    func.funcId = this.functionEntries_.length;
1319
    this.functionEntries_.push({ name, codes: [] });
1320 1321
  }
  // TODO(jarin): Insert the code object into the SFI's code list.
1322
  let entry = this.codeMap_.findDynamicEntryByStartAddress(start);
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
  if (entry) {
    if (entry.size === size && entry.func === func) {
      // Entry state has changed.
      entry.state = state;
    } else {
      this.codeMap_.deleteCode(start);
      entry = null;
    }
  }
  if (!entry) {
1333
    entry = new CodeEntry(size, name, 'JS');
1334 1335 1336 1337 1338 1339
    this.codeMap_.addCode(start, entry);

    entry.codeId = this.codeEntries_.length;

    this.functionEntries_[func.funcId].codes.push(entry.codeId);

1340
    kind = Profile.getKindFromState(state);
1341 1342 1343 1344 1345 1346

    this.codeEntries_.push({
      name: entry.name,
      type: entry.type,
      kind: kind,
      func: func.funcId,
1347
      tm: timestamp,
1348 1349 1350 1351 1352 1353 1354 1355 1356
    });
  }
  return entry;
};

JsonProfile.prototype.moveCode = function (from, to) {
  try {
    this.codeMap_.moveCode(from, to);
  } catch (e) {
1357
    printErr(`Move: unknown source ${from}`);
1358 1359 1360 1361 1362 1363
  }
};

JsonProfile.prototype.addSourcePositions = function (
  start, script, startPos, endPos, sourcePositions, inliningPositions,
  inlinedFunctions) {
1364
  const entry = this.codeMap_.findDynamicEntryByStartAddress(start);
1365
  if (!entry) return;
1366
  const codeId = entry.codeId;
1367 1368 1369 1370

  // Resolve the inlined functions list.
  if (inlinedFunctions.length > 0) {
    inlinedFunctions = inlinedFunctions.substring(1).split("S");
1371 1372 1373
    for (let i = 0; i < inlinedFunctions.length; i++) {
      const funcAddr = parseInt(inlinedFunctions[i]);
      const func = this.codeMap_.findDynamicEntryByStartAddress(funcAddr);
1374
      if (!func || func.funcId === undefined) {
1375
        printErr(`Could not find function ${inlinedFunctions[i]}`);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
        inlinedFunctions[i] = null;
      } else {
        inlinedFunctions[i] = func.funcId;
      }
    }
  } else {
    inlinedFunctions = [];
  }

  this.codeEntries_[entry.codeId].source = {
    script: script,
    start: startPos,
    end: endPos,
    positions: sourcePositions,
    inlined: inliningPositions,
    fns: inlinedFunctions
  };
};

JsonProfile.prototype.addScriptSource = function (id, url, source) {
1396 1397 1398
  const script = new Script(id);
  script.update(url, source);
  this.scripts_[id] = script;
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
};

JsonProfile.prototype.deoptCode = function (
  timestamp, code, inliningId, scriptOffset, bailoutType,
  sourcePositionText, deoptReasonText) {
  let entry = this.codeMap_.findDynamicEntryByStartAddress(code);
  if (entry) {
    let codeId = entry.codeId;
    if (!this.codeEntries_[codeId].deopt) {
      // Only add the deopt if there was no deopt before.
      // The subsequent deoptimizations should be lazy deopts for
      // other on-stack activations.
      this.codeEntries_[codeId].deopt = {
        tm: timestamp,
        inliningId: inliningId,
        scriptOffset: scriptOffset,
        posText: sourcePositionText,
        reason: deoptReasonText,
1417
        bailoutType: bailoutType,
1418 1419 1420 1421 1422 1423 1424 1425 1426
      };
    }
  }
};

JsonProfile.prototype.deleteCode = function (start) {
  try {
    this.codeMap_.deleteCode(start);
  } catch (e) {
1427
    printErr(`Delete: unknown address ${start}`);
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
  }
};

JsonProfile.prototype.moveFunc = function (from, to) {
  if (this.codeMap_.findDynamicEntryByStartAddress(from)) {
    this.codeMap_.moveCode(from, to);
  }
};

JsonProfile.prototype.findEntry = function (addr) {
  return this.codeMap_.findEntry(addr);
};

JsonProfile.prototype.recordTick = function (time_ns, vmState, stack) {
  // TODO(jarin) Resolve the frame-less case (when top of stack is
  // known code).
1444 1445 1446
  const processedStack = [];
  for (let i = 0; i < stack.length; i++) {
    const resolved = this.codeMap_.findAddress(stack[i]);
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    if (resolved) {
      processedStack.push(resolved.entry.codeId, resolved.offset);
    } else {
      processedStack.push(-1, stack[i]);
    }
  }
  this.ticks_.push({ tm: time_ns, vm: vmState, s: processedStack });
};

function writeJson(s) {
  write(JSON.stringify(s, null, 2));
}

JsonProfile.prototype.writeJson = function () {
  // Write out the JSON in a partially manual way to avoid creating too-large
  // strings in one JSON.stringify call when there are a lot of ticks.
  write('{\n')

  write('  "code": ');
  writeJson(this.codeEntries_);
  write(',\n');

  write('  "functions": ');
  writeJson(this.functionEntries_);
  write(',\n');

  write('  "ticks": [\n');
1474
  for (let i = 0; i < this.ticks_.length; i++) {
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
    write('    ');
    writeJson(this.ticks_[i]);
    if (i < this.ticks_.length - 1) {
      write(',\n');
    } else {
      write('\n');
    }
  }
  write('  ],\n');

  write('  "scripts": ');
  writeJson(this.scripts_);

  write('}\n');
};