summaryrefslogtreecommitdiff
path: root/deps/v8/tools/system-analyzer/processor.mjs
blob: 0634174aefb64674e22fe0b71a160928e5fcafc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
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
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import { MapLogEvent, Edge } from "./log/map.mjs";
import { IcLogEvent } from "./log/ic.mjs";
import { Timeline } from "./timeline.mjs";
import { LogReader, parseString, parseVarArgs } from "../logreader.mjs";
import { Profile } from "../profile.mjs";

// ===========================================================================


class Processor extends LogReader {
  #profile = new Profile();
  #mapTimeline = new Timeline();
  #icTimeline = new Timeline();
  #formatPCRegexp = /(.*):[0-9]+:[0-9]+$/;
  MAJOR_VERSION = 7;
  MINOR_VERSION = 6;
  constructor() {
    super();
    this.propertyICParser = [
      parseInt, parseInt, parseInt, parseInt, parseString, parseString,
      parseString, parseString, parseString, parseString
    ];
    this.dispatchTable_ = {
      __proto__: null,
      'code-creation': {
        parsers: [
          parseString, parseInt, parseInt, parseInt, parseInt, parseString,
          parseVarArgs
        ],
        processor: this.processCodeCreation
      },
      'v8-version': {
        parsers: [
          parseInt, parseInt,
        ],
        processor: this.processV8Version
      },
      'script-source': {
        parsers: [parseInt, parseString, parseString],
        processor: this.processScriptSource
      },
      'code-move':
        { parsers: [parseInt, parseInt], processor: this.processCodeMove },
      'code-delete': { parsers: [parseInt], processor: this.processCodeDelete },
      'sfi-move':
        { parsers: [parseInt, parseInt], processor: this.processFunctionMove },
      'map-create':
        { parsers: [parseInt, parseString], processor: this.processMapCreate },
      'map': {
        parsers: [
          parseString, parseInt, parseString, parseString, parseInt, parseInt,
          parseInt, parseString, parseString
        ],
        processor: this.processMap
      },
      'map-details': {
        parsers: [parseInt, parseString, parseString],
        processor: this.processMapDetails
      },
      'LoadGlobalIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'LoadGlobalIC')
      },
      'StoreGlobalIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'StoreGlobalIC')
      },
      'LoadIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'LoadIC')
      },
      'StoreIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'StoreIC')
      },
      'KeyedLoadIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'KeyedLoadIC')
      },
      'KeyedStoreIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'KeyedStoreIC')
      },
      'StoreInArrayLiteralIC': {
        parsers: this.propertyICParser,
        processor: this.processPropertyIC.bind(this, 'StoreInArrayLiteralIC')
      },
    };
  }

  printError(str) {
    console.error(str);
    throw str
  }

  processString(string) {
    let end = string.length;
    let current = 0;
    let next = 0;
    let line;
    let i = 0;
    let entry;
    try {
      while (current < end) {
        next = string.indexOf('\n', current);
        if (next === -1) break;
        i++;
        line = string.substring(current, next);
        current = next + 1;
        this.processLogLine(line);
      }
    } catch (e) {
      console.error('Error occurred during parsing, trying to continue: ' + e);
    }
    this.finalize();
  }

  processLogFile(fileName) {
    this.collectEntries = true;
    this.lastLogFileName_ = fileName;
    let i = 1;
    let line;
    try {
      while (line = readline()) {
        this.processLogLine(line);
        i++;
      }
    } catch (e) {
      console.error(
        'Error occurred during parsing line ' + i +
        ', trying to continue: ' + e);
    }
    this.finalize();
  }

  finalize() {
    // TODO(cbruni): print stats;
    this.#mapTimeline.transitions = new Map();
    let id = 0;
    this.#mapTimeline.forEach(map => {
      if (map.isRoot()) id = map.finalizeRootMap(id + 1);
      if (map.edge && map.edge.name) {
        let edge = map.edge;
        let list = this.#mapTimeline.transitions.get(edge.name);
        if (list === undefined) {
          this.#mapTimeline.transitions.set(edge.name, [edge]);
        } else {
          list.push(edge);
        }
      }
    });
  }

  /**
   * Parser for dynamic code optimization state.
   */
  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);
  }

  processCodeCreation(type, kind, timestamp, start, size, name, maybe_func) {
    if (maybe_func.length) {
      let funcAddr = parseInt(maybe_func[0]);
      let state = this.parseState(maybe_func[1]);
      this.#profile.addFuncCode(
        type, name, timestamp, start, size, funcAddr, state);
    } else {
      this.#profile.addCode(type, name, timestamp, start, size);
    }
  }


  processV8Version(majorVersion, minorVersion) {
    if (
      (majorVersion == this.MAJOR_VERSION && minorVersion <= this.MINOR_VERSION)
      || (majorVersion < this.MAJOR_VERSION)) {
      window.alert(
        `Unsupported version ${majorVersion}.${minorVersion}. \n` +
        `Please use the matching tool for given the V8 version.`);
    }
  }

  processScriptSource(scriptId, url, source) {
    this.#profile.addScriptSource(scriptId, url, source);
  }

  processCodeMove(from, to) {
    this.#profile.moveCode(from, to);
  }

  processCodeDelete(start) {
    this.#profile.deleteCode(start);
  }

  processFunctionMove(from, to) {
    this.#profile.moveFunc(from, to);
  }

  formatName(entry) {
    if (!entry) return '<unknown>';
    let name = entry.func.getName();
    let re = /(.*):[0-9]+:[0-9]+$/;
    let array = re.exec(name);
    if (!array) return name;
    return entry.getState() + array[1];
  }

  processPropertyIC(
    type, pc, time, line, column, old_state, new_state, map, key, modifier,
    slow_reason) {
    let fnName = this.functionName(pc);
    let parts = fnName.split(' ');
    let fileName = parts[1];
    let script = this.getScript(fileName);
    // TODO: Use SourcePosition here directly
    let entry = new IcLogEvent(
      type, fnName, time, line, column, key, old_state, new_state, map,
      slow_reason, script);
    if (script) {
      entry.sourcePosition = script.addSourcePosition(line, column, entry);
    }
    this.#icTimeline.push(entry);
  }

  functionName(pc) {
    let entry = this.#profile.findEntry(pc);
    return this.formatName(entry);
  }
  formatPC(pc, line, column) {
    let entry = this.#profile.findEntry(pc);
    if (!entry) return '<unknown>'
    if (entry.type === 'Builtin') {
      return entry.name;
    }
    let name = entry.func.getName();
    let array = this.#formatPCRegexp.exec(name);
    if (array === null) {
      entry = name;
    } else {
      entry = entry.getState() + array[1];
    }
    return entry + ':' + line + ':' + column;
  }

  processFileName(filePositionLine) {
    if (!(/\s/.test(filePositionLine))) return;
    filePositionLine = filePositionLine.split(' ');
    let file = filePositionLine[1].split(':')[0];
    return file;
  }

  processMap(type, time, from, to, pc, line, column, reason, name) {
    let time_ = parseInt(time);
    if (type === 'Deprecate') return this.deprecateMap(type, time_, from);
    let from_ = this.getExistingMap(from, time_);
    let to_ = this.getExistingMap(to, time_);
    // TODO: use SourcePosition directly.
    let edge = new Edge(type, name, reason, time, from_, to_);
    to_.filePosition = this.formatPC(pc, line, column);
    let fileName = this.processFileName(to_.filePosition);
    to_.script = this.getScript(fileName);
    if (to_.script) {
      to_.sourcePosition = to_.script.addSourcePosition(line, column, to_)
    }
    edge.finishSetup();
  }

  deprecateMap(type, time, id) {
    this.getExistingMap(id, time).deprecate();
  }

  processMapCreate(time, id) {
    // map-create events might override existing maps if the addresses get
    // recycled. Hence we do not check for existing maps.
    let map = this.createMap(id, time);
  }

  processMapDetails(time, id, string) {
    // TODO(cbruni): fix initial map logging.
    let map = this.getExistingMap(id, time);
    map.description = string;
  }

  createMap(id, time) {
    let map = new MapLogEvent(id, time);
    this.#mapTimeline.push(map);
    return map;
  }

  getExistingMap(id, time) {
    if (id === '0x000000000000') return undefined;
    let map = MapLogEvent.get(id, time);
    if (map === undefined) {
      console.error('No map details provided: id=' + id);
      // Manually patch in a map to continue running.
      return this.createMap(id, time);
    };
    return map;
  }

  getScript(url) {
    const script = this.#profile.getScript(url);
    // TODO create placeholder script for empty urls.
    if (script === undefined) {
      console.error(`Could not find script for url: '${url}'`)
    }
    return script;
  }

  get icTimeline() {
    return this.#icTimeline;
  }

  get mapTimeline() {
    return this.#mapTimeline;
  }

  get scripts() {
    return this.#profile.scripts_.filter(script => script !== undefined);
  }
}

Processor.kProperties = [
  'type',
  'category',
  'functionName',
  'filePosition',
  'state',
  'key',
  'map',
  'reason',
  'file'
];

export { Processor as default };