blob: d54471795f6c17912f798a5b20e0acb6c95a4f0e [file] [log] [blame]
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001// Copyright 2012 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28
Steve Block1e0659c2011-05-24 12:43:12 +010029function inherits(childCtor, parentCtor) {
30 childCtor.prototype.__proto__ = parentCtor.prototype;
31};
32
33
34function V8Profile(separateIc) {
35 Profile.call(this);
Steve Blocka7e24c12009-10-30 11:49:00 +000036 if (!separateIc) {
Steve Block1e0659c2011-05-24 12:43:12 +010037 this.skipThisFunction = function(name) { return V8Profile.IC_RE.test(name); };
Steve Blocka7e24c12009-10-30 11:49:00 +000038 }
39};
Steve Block1e0659c2011-05-24 12:43:12 +010040inherits(V8Profile, Profile);
Steve Blocka7e24c12009-10-30 11:49:00 +000041
42
Steve Block1e0659c2011-05-24 12:43:12 +010043V8Profile.IC_RE =
Steve Blocka7e24c12009-10-30 11:49:00 +000044 /^(?:CallIC|LoadIC|StoreIC)|(?:Builtin: (?:Keyed)?(?:Call|Load|Store)IC_)/;
45
46
47/**
48 * A thin wrapper around shell's 'read' function showing a file name on error.
49 */
50function readFile(fileName) {
51 try {
52 return read(fileName);
53 } catch (e) {
54 print(fileName + ': ' + (e.message || e));
55 throw e;
56 }
57}
58
59
Ben Murdoche0cee9b2011-05-25 10:26:03 +010060/**
61 * Parser for dynamic code optimization state.
62 */
63function parseState(s) {
64 switch (s) {
65 case "": return Profile.CodeState.COMPILED;
66 case "~": return Profile.CodeState.OPTIMIZABLE;
67 case "*": return Profile.CodeState.OPTIMIZED;
68 }
69 throw new Error("unknown code state: " + s);
70}
71
72
Leon Clarkee46be812010-01-19 14:06:41 +000073function SnapshotLogProcessor() {
Steve Block1e0659c2011-05-24 12:43:12 +010074 LogReader.call(this, {
Leon Clarkee46be812010-01-19 14:06:41 +000075 'code-creation': {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000076 parsers: [null, parseInt, parseInt, parseInt, null, 'var-args'],
Ben Murdochb0fe1622011-05-05 13:52:32 +010077 processor: this.processCodeCreation },
78 'code-move': { parsers: [parseInt, parseInt],
79 processor: this.processCodeMove },
80 'code-delete': { parsers: [parseInt],
81 processor: this.processCodeDelete },
Andrei Popescu31002712010-02-23 13:46:05 +000082 'function-creation': null,
83 'function-move': null,
84 'function-delete': null,
Ben Murdoche0cee9b2011-05-25 10:26:03 +010085 'sfi-move': null,
Ben Murdochb0fe1622011-05-05 13:52:32 +010086 'snapshot-pos': { parsers: [parseInt, parseInt],
87 processor: this.processSnapshotPosition }});
Leon Clarkee46be812010-01-19 14:06:41 +000088
Steve Block1e0659c2011-05-24 12:43:12 +010089 V8Profile.prototype.handleUnknownCode = function(operation, addr) {
90 var op = Profile.Operation;
Leon Clarkee46be812010-01-19 14:06:41 +000091 switch (operation) {
92 case op.MOVE:
93 print('Snapshot: Code move event for unknown code: 0x' +
94 addr.toString(16));
95 break;
96 case op.DELETE:
97 print('Snapshot: Code delete event for unknown code: 0x' +
98 addr.toString(16));
99 break;
100 }
101 };
102
Steve Block1e0659c2011-05-24 12:43:12 +0100103 this.profile_ = new V8Profile();
Leon Clarkee46be812010-01-19 14:06:41 +0000104 this.serializedEntries_ = [];
105}
Steve Block1e0659c2011-05-24 12:43:12 +0100106inherits(SnapshotLogProcessor, LogReader);
Leon Clarkee46be812010-01-19 14:06:41 +0000107
108
109SnapshotLogProcessor.prototype.processCodeCreation = function(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000110 type, kind, start, size, name, maybe_func) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100111 if (maybe_func.length) {
112 var funcAddr = parseInt(maybe_func[0]);
113 var state = parseState(maybe_func[1]);
114 this.profile_.addFuncCode(type, name, start, size, funcAddr, state);
115 } else {
116 this.profile_.addCode(type, name, start, size);
117 }
Leon Clarkee46be812010-01-19 14:06:41 +0000118};
119
120
121SnapshotLogProcessor.prototype.processCodeMove = function(from, to) {
122 this.profile_.moveCode(from, to);
123};
124
125
126SnapshotLogProcessor.prototype.processCodeDelete = function(start) {
127 this.profile_.deleteCode(start);
128};
129
130
131SnapshotLogProcessor.prototype.processSnapshotPosition = function(addr, pos) {
132 this.serializedEntries_[pos] = this.profile_.findEntry(addr);
133};
134
135
136SnapshotLogProcessor.prototype.processLogFile = function(fileName) {
137 var contents = readFile(fileName);
138 this.processLogChunk(contents);
139};
140
141
142SnapshotLogProcessor.prototype.getSerializedEntryName = function(pos) {
143 var entry = this.serializedEntries_[pos];
144 return entry ? entry.getRawName() : null;
Steve Blocka7e24c12009-10-30 11:49:00 +0000145};
146
147
148function TickProcessor(
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100149 cppEntriesProvider,
150 separateIc,
151 callGraphSize,
152 ignoreUnknown,
153 stateFilter,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000154 snapshotLogProcessor,
155 distortion,
156 range,
157 sourceMap) {
Steve Block1e0659c2011-05-24 12:43:12 +0100158 LogReader.call(this, {
Steve Blocka7e24c12009-10-30 11:49:00 +0000159 'shared-library': { parsers: [null, parseInt, parseInt],
160 processor: this.processSharedLibrary },
161 'code-creation': {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000162 parsers: [null, parseInt, parseInt, parseInt, null, 'var-args'],
Ben Murdochb0fe1622011-05-05 13:52:32 +0100163 processor: this.processCodeCreation },
164 'code-move': { parsers: [parseInt, parseInt],
165 processor: this.processCodeMove },
166 'code-delete': { parsers: [parseInt],
167 processor: this.processCodeDelete },
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100168 'sfi-move': { parsers: [parseInt, parseInt],
Ben Murdochb0fe1622011-05-05 13:52:32 +0100169 processor: this.processFunctionMove },
Ben Murdochb0fe1622011-05-05 13:52:32 +0100170 'snapshot-pos': { parsers: [parseInt, parseInt],
171 processor: this.processSnapshotPosition },
Steve Block44f0eee2011-05-26 01:26:41 +0100172 'tick': {
173 parsers: [parseInt, parseInt, parseInt,
174 parseInt, parseInt, 'var-args'],
Ben Murdochb0fe1622011-05-05 13:52:32 +0100175 processor: this.processTick },
Steve Block3ce2e202009-11-05 08:53:23 +0000176 'heap-sample-begin': { parsers: [null, null, parseInt],
177 processor: this.processHeapSampleBegin },
178 'heap-sample-end': { parsers: [null, null],
179 processor: this.processHeapSampleEnd },
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000180 'timer-event-start' : { parsers: [null, null, null],
181 processor: this.advanceDistortion },
182 'timer-event-end' : { parsers: [null, null, null],
183 processor: this.advanceDistortion },
Steve Block3ce2e202009-11-05 08:53:23 +0000184 // Ignored events.
Steve Blocka7e24c12009-10-30 11:49:00 +0000185 'profiler': null,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100186 'function-creation': null,
187 'function-move': null,
188 'function-delete': null,
Steve Block3ce2e202009-11-05 08:53:23 +0000189 'heap-sample-item': null,
Steve Blocka7e24c12009-10-30 11:49:00 +0000190 // Obsolete row types.
191 'code-allocate': null,
192 'begin-code-region': null,
193 'end-code-region': null });
194
195 this.cppEntriesProvider_ = cppEntriesProvider;
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100196 this.callGraphSize_ = callGraphSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000197 this.ignoreUnknown_ = ignoreUnknown;
198 this.stateFilter_ = stateFilter;
Leon Clarkee46be812010-01-19 14:06:41 +0000199 this.snapshotLogProcessor_ = snapshotLogProcessor;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000200 this.sourceMap = sourceMap;
Leon Clarkee46be812010-01-19 14:06:41 +0000201 this.deserializedEntriesNames_ = [];
Steve Blocka7e24c12009-10-30 11:49:00 +0000202 var ticks = this.ticks_ =
203 { total: 0, unaccounted: 0, excluded: 0, gc: 0 };
204
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000205 distortion = parseInt(distortion);
206 // Convert picoseconds to nanoseconds.
207 this.distortion_per_entry = isNaN(distortion) ? 0 : (distortion / 1000);
208 this.distortion = 0;
209 var rangelimits = range ? range.split(",") : [];
210 var range_start = parseInt(rangelimits[0]);
211 var range_end = parseInt(rangelimits[1]);
212 // Convert milliseconds to nanoseconds.
213 this.range_start = isNaN(range_start) ? -Infinity : (range_start * 1000);
214 this.range_end = isNaN(range_end) ? Infinity : (range_end * 1000)
215
Steve Block1e0659c2011-05-24 12:43:12 +0100216 V8Profile.prototype.handleUnknownCode = function(
Steve Blocka7e24c12009-10-30 11:49:00 +0000217 operation, addr, opt_stackPos) {
Steve Block1e0659c2011-05-24 12:43:12 +0100218 var op = Profile.Operation;
Steve Blocka7e24c12009-10-30 11:49:00 +0000219 switch (operation) {
220 case op.MOVE:
221 print('Code move event for unknown code: 0x' + addr.toString(16));
222 break;
223 case op.DELETE:
224 print('Code delete event for unknown code: 0x' + addr.toString(16));
225 break;
226 case op.TICK:
227 // Only unknown PCs (the first frame) are reported as unaccounted,
228 // otherwise tick balance will be corrupted (this behavior is compatible
229 // with the original tickprocessor.py script.)
230 if (opt_stackPos == 0) {
231 ticks.unaccounted++;
232 }
233 break;
234 }
235 };
236
Steve Block1e0659c2011-05-24 12:43:12 +0100237 this.profile_ = new V8Profile(separateIc);
Steve Blocka7e24c12009-10-30 11:49:00 +0000238 this.codeTypes_ = {};
239 // Count each tick as a time unit.
Steve Block1e0659c2011-05-24 12:43:12 +0100240 this.viewBuilder_ = new ViewBuilder(1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000241 this.lastLogFileName_ = null;
Steve Block3ce2e202009-11-05 08:53:23 +0000242
243 this.generation_ = 1;
244 this.currentProducerProfile_ = null;
Steve Blocka7e24c12009-10-30 11:49:00 +0000245};
Steve Block1e0659c2011-05-24 12:43:12 +0100246inherits(TickProcessor, LogReader);
Steve Blocka7e24c12009-10-30 11:49:00 +0000247
248
249TickProcessor.VmStates = {
250 JS: 0,
251 GC: 1,
252 COMPILER: 2,
253 OTHER: 3,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000254 EXTERNAL: 4,
255 IDLE: 5
Steve Blocka7e24c12009-10-30 11:49:00 +0000256};
257
258
259TickProcessor.CodeTypes = {
260 CPP: 0,
261 SHARED_LIB: 1
262};
263// Otherwise, this is JS-related code. We are not adding it to
264// codeTypes_ map because there can be zillions of them.
265
266
267TickProcessor.CALL_PROFILE_CUTOFF_PCT = 2.0;
268
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100269TickProcessor.CALL_GRAPH_SIZE = 5;
Steve Blocka7e24c12009-10-30 11:49:00 +0000270
271/**
272 * @override
273 */
274TickProcessor.prototype.printError = function(str) {
275 print(str);
276};
277
278
279TickProcessor.prototype.setCodeType = function(name, type) {
280 this.codeTypes_[name] = TickProcessor.CodeTypes[type];
281};
282
283
284TickProcessor.prototype.isSharedLibrary = function(name) {
285 return this.codeTypes_[name] == TickProcessor.CodeTypes.SHARED_LIB;
286};
287
288
289TickProcessor.prototype.isCppCode = function(name) {
290 return this.codeTypes_[name] == TickProcessor.CodeTypes.CPP;
291};
292
293
294TickProcessor.prototype.isJsCode = function(name) {
295 return !(name in this.codeTypes_);
296};
297
298
299TickProcessor.prototype.processLogFile = function(fileName) {
300 this.lastLogFileName_ = fileName;
Andrei Popescu31002712010-02-23 13:46:05 +0000301 var line;
302 while (line = readline()) {
303 this.processLogLine(line);
304 }
305};
306
307
308TickProcessor.prototype.processLogFileInTest = function(fileName) {
309 // Hack file name to avoid dealing with platform specifics.
310 this.lastLogFileName_ = 'v8.log';
Steve Blocka7e24c12009-10-30 11:49:00 +0000311 var contents = readFile(fileName);
312 this.processLogChunk(contents);
313};
314
315
316TickProcessor.prototype.processSharedLibrary = function(
317 name, startAddr, endAddr) {
318 var entry = this.profile_.addLibrary(name, startAddr, endAddr);
319 this.setCodeType(entry.getName(), 'SHARED_LIB');
320
321 var self = this;
322 var libFuncs = this.cppEntriesProvider_.parseVmSymbols(
323 name, startAddr, endAddr, function(fName, fStart, fEnd) {
324 self.profile_.addStaticCode(fName, fStart, fEnd);
325 self.setCodeType(fName, 'CPP');
326 });
327};
328
329
330TickProcessor.prototype.processCodeCreation = function(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000331 type, kind, start, size, name, maybe_func) {
Leon Clarkee46be812010-01-19 14:06:41 +0000332 name = this.deserializedEntriesNames_[start] || name;
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100333 if (maybe_func.length) {
334 var funcAddr = parseInt(maybe_func[0]);
335 var state = parseState(maybe_func[1]);
336 this.profile_.addFuncCode(type, name, start, size, funcAddr, state);
337 } else {
338 this.profile_.addCode(type, name, start, size);
339 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000340};
341
342
343TickProcessor.prototype.processCodeMove = function(from, to) {
344 this.profile_.moveCode(from, to);
345};
346
347
348TickProcessor.prototype.processCodeDelete = function(start) {
349 this.profile_.deleteCode(start);
350};
351
352
Leon Clarked91b9f72010-01-27 17:25:45 +0000353TickProcessor.prototype.processFunctionMove = function(from, to) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100354 this.profile_.moveFunc(from, to);
Leon Clarked91b9f72010-01-27 17:25:45 +0000355};
356
357
Leon Clarkee46be812010-01-19 14:06:41 +0000358TickProcessor.prototype.processSnapshotPosition = function(addr, pos) {
359 if (this.snapshotLogProcessor_) {
360 this.deserializedEntriesNames_[addr] =
361 this.snapshotLogProcessor_.getSerializedEntryName(pos);
362 }
363};
364
365
Steve Blocka7e24c12009-10-30 11:49:00 +0000366TickProcessor.prototype.includeTick = function(vmState) {
367 return this.stateFilter_ == null || this.stateFilter_ == vmState;
368};
369
Steve Block44f0eee2011-05-26 01:26:41 +0100370TickProcessor.prototype.processTick = function(pc,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000371 ns_since_start,
Steve Block44f0eee2011-05-26 01:26:41 +0100372 is_external_callback,
373 tos_or_external_callback,
374 vmState,
375 stack) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000376 this.distortion += this.distortion_per_entry;
377 ns_since_start -= this.distortion;
378 if (ns_since_start < this.range_start || ns_since_start > this.range_end) {
379 return;
380 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000381 this.ticks_.total++;
382 if (vmState == TickProcessor.VmStates.GC) this.ticks_.gc++;
383 if (!this.includeTick(vmState)) {
384 this.ticks_.excluded++;
385 return;
386 }
Steve Block44f0eee2011-05-26 01:26:41 +0100387 if (is_external_callback) {
388 // Don't use PC when in external callback code, as it can point
389 // inside callback's code, and we will erroneously report
Ben Murdoch8b112d22011-06-08 16:22:53 +0100390 // that a callback calls itself. Instead we use tos_or_external_callback,
391 // as simply resetting PC will produce unaccounted ticks.
392 pc = tos_or_external_callback;
393 tos_or_external_callback = 0;
Steve Block44f0eee2011-05-26 01:26:41 +0100394 } else if (tos_or_external_callback) {
395 // Find out, if top of stack was pointing inside a JS function
396 // meaning that we have encountered a frameless invocation.
397 var funcEntry = this.profile_.findEntry(tos_or_external_callback);
Leon Clarked91b9f72010-01-27 17:25:45 +0000398 if (!funcEntry || !funcEntry.isJSFunction || !funcEntry.isJSFunction()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100399 tos_or_external_callback = 0;
Leon Clarked91b9f72010-01-27 17:25:45 +0000400 }
401 }
402
Steve Block44f0eee2011-05-26 01:26:41 +0100403 this.profile_.recordTick(this.processStack(pc, tos_or_external_callback, stack));
Steve Blocka7e24c12009-10-30 11:49:00 +0000404};
405
406
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000407TickProcessor.prototype.advanceDistortion = function() {
408 this.distortion += this.distortion_per_entry;
409}
410
411
Steve Block3ce2e202009-11-05 08:53:23 +0000412TickProcessor.prototype.processHeapSampleBegin = function(space, state, ticks) {
413 if (space != 'Heap') return;
Steve Block1e0659c2011-05-24 12:43:12 +0100414 this.currentProducerProfile_ = new CallTree();
Steve Block3ce2e202009-11-05 08:53:23 +0000415};
416
417
418TickProcessor.prototype.processHeapSampleEnd = function(space, state) {
419 if (space != 'Heap' || !this.currentProducerProfile_) return;
420
421 print('Generation ' + this.generation_ + ':');
422 var tree = this.currentProducerProfile_;
423 tree.computeTotalWeights();
424 var producersView = this.viewBuilder_.buildView(tree);
425 // Sort by total time, desc, then by name, desc.
426 producersView.sort(function(rec1, rec2) {
427 return rec2.totalTime - rec1.totalTime ||
428 (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1); });
429 this.printHeavyProfile(producersView.head.children);
430
431 this.currentProducerProfile_ = null;
432 this.generation_++;
433};
434
435
Steve Blocka7e24c12009-10-30 11:49:00 +0000436TickProcessor.prototype.printStatistics = function() {
437 print('Statistical profiling result from ' + this.lastLogFileName_ +
438 ', (' + this.ticks_.total +
439 ' ticks, ' + this.ticks_.unaccounted + ' unaccounted, ' +
440 this.ticks_.excluded + ' excluded).');
441
442 if (this.ticks_.total == 0) return;
443
Steve Blocka7e24c12009-10-30 11:49:00 +0000444 var flatProfile = this.profile_.getFlatProfile();
445 var flatView = this.viewBuilder_.buildView(flatProfile);
446 // Sort by self time, desc, then by name, desc.
447 flatView.sort(function(rec1, rec2) {
448 return rec2.selfTime - rec1.selfTime ||
449 (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1); });
450 var totalTicks = this.ticks_.total;
451 if (this.ignoreUnknown_) {
452 totalTicks -= this.ticks_.unaccounted;
453 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000454
455 // Count library ticks
456 var flatViewNodes = flatView.head.children;
457 var self = this;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000458
Steve Blocka7e24c12009-10-30 11:49:00 +0000459 var libraryTicks = 0;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000460 this.printHeader('Shared libraries');
461 this.printEntries(flatViewNodes, totalTicks, null,
Steve Blocka7e24c12009-10-30 11:49:00 +0000462 function(name) { return self.isSharedLibrary(name); },
463 function(rec) { libraryTicks += rec.selfTime; });
464 var nonLibraryTicks = totalTicks - libraryTicks;
465
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000466 var jsTicks = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000467 this.printHeader('JavaScript');
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000468 this.printEntries(flatViewNodes, totalTicks, nonLibraryTicks,
469 function(name) { return self.isJsCode(name); },
470 function(rec) { jsTicks += rec.selfTime; });
Steve Blocka7e24c12009-10-30 11:49:00 +0000471
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000472 var cppTicks = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000473 this.printHeader('C++');
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000474 this.printEntries(flatViewNodes, totalTicks, nonLibraryTicks,
475 function(name) { return self.isCppCode(name); },
476 function(rec) { cppTicks += rec.selfTime; });
Steve Blocka7e24c12009-10-30 11:49:00 +0000477
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000478 this.printHeader('Summary');
479 this.printLine('JavaScript', jsTicks, totalTicks, nonLibraryTicks);
480 this.printLine('C++', cppTicks, totalTicks, nonLibraryTicks);
481 this.printLine('GC', this.ticks_.gc, totalTicks, nonLibraryTicks);
482 this.printLine('Shared libraries', libraryTicks, totalTicks, null);
483 if (!this.ignoreUnknown_ && this.ticks_.unaccounted > 0) {
484 this.printLine('Unaccounted', this.ticks_.unaccounted,
485 this.ticks_.total, null);
486 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000487
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400488 print('\n [C++ entry points]:');
489 print(' ticks cpp total name');
490 var c_entry_functions = this.profile_.getCEntryProfile();
491 var total_c_entry = c_entry_functions[0].ticks;
492 for (var i = 1; i < c_entry_functions.length; i++) {
493 c = c_entry_functions[i];
494 this.printLine(c.name, c.ticks, total_c_entry, totalTicks);
495 }
496
Steve Blocka7e24c12009-10-30 11:49:00 +0000497 this.printHeavyProfHeader();
498 var heavyProfile = this.profile_.getBottomUpProfile();
499 var heavyView = this.viewBuilder_.buildView(heavyProfile);
500 // To show the same percentages as in the flat profile.
501 heavyView.head.totalTime = totalTicks;
502 // Sort by total time, desc, then by name, desc.
503 heavyView.sort(function(rec1, rec2) {
504 return rec2.totalTime - rec1.totalTime ||
505 (rec2.internalFuncName < rec1.internalFuncName ? -1 : 1); });
506 this.printHeavyProfile(heavyView.head.children);
507};
508
509
510function padLeft(s, len) {
511 s = s.toString();
512 if (s.length < len) {
513 var padLength = len - s.length;
514 if (!(padLength in padLeft)) {
515 padLeft[padLength] = new Array(padLength + 1).join(' ');
516 }
517 s = padLeft[padLength] + s;
518 }
519 return s;
520};
521
522
523TickProcessor.prototype.printHeader = function(headerTitle) {
524 print('\n [' + headerTitle + ']:');
525 print(' ticks total nonlib name');
526};
527
528
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000529TickProcessor.prototype.printLine = function(
530 entry, ticks, totalTicks, nonLibTicks) {
531 var pct = ticks * 100 / totalTicks;
532 var nonLibPct = nonLibTicks != null
533 ? padLeft((ticks * 100 / nonLibTicks).toFixed(1), 5) + '% '
534 : ' ';
535 print(' ' + padLeft(ticks, 5) + ' ' +
536 padLeft(pct.toFixed(1), 5) + '% ' +
537 nonLibPct +
538 entry);
539}
540
Steve Blocka7e24c12009-10-30 11:49:00 +0000541TickProcessor.prototype.printHeavyProfHeader = function() {
542 print('\n [Bottom up (heavy) profile]:');
543 print(' Note: percentage shows a share of a particular caller in the ' +
544 'total\n' +
545 ' amount of its parent calls.');
546 print(' Callers occupying less than ' +
547 TickProcessor.CALL_PROFILE_CUTOFF_PCT.toFixed(1) +
548 '% are not shown.\n');
549 print(' ticks parent name');
550};
551
552
Steve Blocka7e24c12009-10-30 11:49:00 +0000553TickProcessor.prototype.processProfile = function(
554 profile, filterP, func) {
555 for (var i = 0, n = profile.length; i < n; ++i) {
556 var rec = profile[i];
557 if (!filterP(rec.internalFuncName)) {
558 continue;
559 }
560 func(rec);
561 }
562};
563
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000564TickProcessor.prototype.getLineAndColumn = function(name) {
565 var re = /:([0-9]+):([0-9]+)$/;
566 var array = re.exec(name);
567 if (!array) {
568 return null;
569 }
570 return {line: array[1], column: array[2]};
571}
572
573TickProcessor.prototype.hasSourceMap = function() {
574 return this.sourceMap != null;
575};
576
577
578TickProcessor.prototype.formatFunctionName = function(funcName) {
579 if (!this.hasSourceMap()) {
580 return funcName;
581 }
582 var lc = this.getLineAndColumn(funcName);
583 if (lc == null) {
584 return funcName;
585 }
586 // in source maps lines and columns are zero based
587 var lineNumber = lc.line - 1;
588 var column = lc.column - 1;
589 var entry = this.sourceMap.findEntry(lineNumber, column);
590 var sourceFile = entry[2];
591 var sourceLine = entry[3] + 1;
592 var sourceColumn = entry[4] + 1;
593
594 return sourceFile + ':' + sourceLine + ':' + sourceColumn + ' -> ' + funcName;
595};
Steve Blocka7e24c12009-10-30 11:49:00 +0000596
597TickProcessor.prototype.printEntries = function(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000598 profile, totalTicks, nonLibTicks, filterP, callback) {
599 var that = this;
Steve Blocka7e24c12009-10-30 11:49:00 +0000600 this.processProfile(profile, filterP, function (rec) {
601 if (rec.selfTime == 0) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000602 callback(rec);
603 var funcName = that.formatFunctionName(rec.internalFuncName);
604 that.printLine(funcName, rec.selfTime, totalTicks, nonLibTicks);
Steve Blocka7e24c12009-10-30 11:49:00 +0000605 });
606};
607
608
609TickProcessor.prototype.printHeavyProfile = function(profile, opt_indent) {
610 var self = this;
611 var indent = opt_indent || 0;
612 var indentStr = padLeft('', indent);
613 this.processProfile(profile, function() { return true; }, function (rec) {
614 // Cut off too infrequent callers.
615 if (rec.parentTotalPercent < TickProcessor.CALL_PROFILE_CUTOFF_PCT) return;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000616 var funcName = self.formatFunctionName(rec.internalFuncName);
Steve Blocka7e24c12009-10-30 11:49:00 +0000617 print(' ' + padLeft(rec.totalTime, 5) + ' ' +
618 padLeft(rec.parentTotalPercent.toFixed(1), 5) + '% ' +
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000619 indentStr + funcName);
Steve Blocka7e24c12009-10-30 11:49:00 +0000620 // Limit backtrace depth.
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100621 if (indent < 2 * self.callGraphSize_) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000622 self.printHeavyProfile(rec.children, indent + 2);
623 }
624 // Delimit top-level functions.
625 if (indent == 0) {
626 print('');
627 }
628 });
629};
630
631
632function CppEntriesProvider() {
633};
634
635
636CppEntriesProvider.prototype.parseVmSymbols = function(
637 libName, libStart, libEnd, processorFunc) {
638 this.loadSymbols(libName);
639
640 var prevEntry;
641
642 function addEntry(funcInfo) {
643 // Several functions can be mapped onto the same address. To avoid
644 // creating zero-sized entries, skip such duplicates.
645 // Also double-check that function belongs to the library address space.
646 if (prevEntry && !prevEntry.end &&
647 prevEntry.start < funcInfo.start &&
648 prevEntry.start >= libStart && funcInfo.start <= libEnd) {
649 processorFunc(prevEntry.name, prevEntry.start, funcInfo.start);
650 }
651 if (funcInfo.end &&
652 (!prevEntry || prevEntry.start != funcInfo.start) &&
653 funcInfo.start >= libStart && funcInfo.end <= libEnd) {
654 processorFunc(funcInfo.name, funcInfo.start, funcInfo.end);
655 }
656 prevEntry = funcInfo;
657 }
658
659 while (true) {
660 var funcInfo = this.parseNextLine();
661 if (funcInfo === null) {
662 continue;
663 } else if (funcInfo === false) {
664 break;
665 }
666 if (funcInfo.start < libStart && funcInfo.start < libEnd - libStart) {
667 funcInfo.start += libStart;
668 }
669 if (funcInfo.size) {
670 funcInfo.end = funcInfo.start + funcInfo.size;
671 }
672 addEntry(funcInfo);
673 }
674 addEntry({name: '', start: libEnd});
675};
676
677
678CppEntriesProvider.prototype.loadSymbols = function(libName) {
679};
680
681
682CppEntriesProvider.prototype.parseNextLine = function() {
683 return false;
684};
685
686
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000687function UnixCppEntriesProvider(nmExec, targetRootFS) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000688 this.symbols = [];
689 this.parsePos = 0;
690 this.nmExec = nmExec;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000691 this.targetRootFS = targetRootFS;
Steve Blocka7e24c12009-10-30 11:49:00 +0000692 this.FUNC_RE = /^([0-9a-fA-F]{8,16}) ([0-9a-fA-F]{8,16} )?[tTwW] (.*)$/;
693};
694inherits(UnixCppEntriesProvider, CppEntriesProvider);
695
696
697UnixCppEntriesProvider.prototype.loadSymbols = function(libName) {
698 this.parsePos = 0;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000699 libName = this.targetRootFS + libName;
Steve Blocka7e24c12009-10-30 11:49:00 +0000700 try {
701 this.symbols = [
702 os.system(this.nmExec, ['-C', '-n', '-S', libName], -1, -1),
703 os.system(this.nmExec, ['-C', '-n', '-S', '-D', libName], -1, -1)
704 ];
705 } catch (e) {
706 // If the library cannot be found on this system let's not panic.
707 this.symbols = ['', ''];
708 }
709};
710
711
712UnixCppEntriesProvider.prototype.parseNextLine = function() {
713 if (this.symbols.length == 0) {
714 return false;
715 }
716 var lineEndPos = this.symbols[0].indexOf('\n', this.parsePos);
717 if (lineEndPos == -1) {
718 this.symbols.shift();
719 this.parsePos = 0;
720 return this.parseNextLine();
721 }
722
723 var line = this.symbols[0].substring(this.parsePos, lineEndPos);
724 this.parsePos = lineEndPos + 1;
725 var fields = line.match(this.FUNC_RE);
726 var funcInfo = null;
727 if (fields) {
728 funcInfo = { name: fields[3], start: parseInt(fields[1], 16) };
729 if (fields[2]) {
730 funcInfo.size = parseInt(fields[2], 16);
731 }
732 }
733 return funcInfo;
734};
735
736
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000737function MacCppEntriesProvider(nmExec, targetRootFS) {
738 UnixCppEntriesProvider.call(this, nmExec, targetRootFS);
Steve Blocka7e24c12009-10-30 11:49:00 +0000739 // Note an empty group. It is required, as UnixCppEntriesProvider expects 3 groups.
740 this.FUNC_RE = /^([0-9a-fA-F]{8,16}) ()[iItT] (.*)$/;
741};
742inherits(MacCppEntriesProvider, UnixCppEntriesProvider);
743
744
745MacCppEntriesProvider.prototype.loadSymbols = function(libName) {
746 this.parsePos = 0;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000747 libName = this.targetRootFS + libName;
Steve Blocka7e24c12009-10-30 11:49:00 +0000748 try {
749 this.symbols = [os.system(this.nmExec, ['-n', '-f', libName], -1, -1), ''];
750 } catch (e) {
751 // If the library cannot be found on this system let's not panic.
752 this.symbols = '';
753 }
754};
755
756
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000757function WindowsCppEntriesProvider(_ignored_nmExec, targetRootFS) {
758 this.targetRootFS = targetRootFS;
Steve Blocka7e24c12009-10-30 11:49:00 +0000759 this.symbols = '';
760 this.parsePos = 0;
761};
762inherits(WindowsCppEntriesProvider, CppEntriesProvider);
763
764
765WindowsCppEntriesProvider.FILENAME_RE = /^(.*)\.([^.]+)$/;
766
767
768WindowsCppEntriesProvider.FUNC_RE =
769 /^\s+0001:[0-9a-fA-F]{8}\s+([_\?@$0-9a-zA-Z]+)\s+([0-9a-fA-F]{8}).*$/;
770
771
772WindowsCppEntriesProvider.IMAGE_BASE_RE =
773 /^\s+0000:00000000\s+___ImageBase\s+([0-9a-fA-F]{8}).*$/;
774
775
776// This is almost a constant on Windows.
777WindowsCppEntriesProvider.EXE_IMAGE_BASE = 0x00400000;
778
779
780WindowsCppEntriesProvider.prototype.loadSymbols = function(libName) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000781 libName = this.targetRootFS + libName;
Steve Blocka7e24c12009-10-30 11:49:00 +0000782 var fileNameFields = libName.match(WindowsCppEntriesProvider.FILENAME_RE);
783 if (!fileNameFields) return;
784 var mapFileName = fileNameFields[1] + '.map';
785 this.moduleType_ = fileNameFields[2].toLowerCase();
786 try {
787 this.symbols = read(mapFileName);
788 } catch (e) {
789 // If .map file cannot be found let's not panic.
790 this.symbols = '';
791 }
792};
793
794
795WindowsCppEntriesProvider.prototype.parseNextLine = function() {
796 var lineEndPos = this.symbols.indexOf('\r\n', this.parsePos);
797 if (lineEndPos == -1) {
798 return false;
799 }
800
801 var line = this.symbols.substring(this.parsePos, lineEndPos);
802 this.parsePos = lineEndPos + 2;
803
804 // Image base entry is above all other symbols, so we can just
805 // terminate parsing.
806 var imageBaseFields = line.match(WindowsCppEntriesProvider.IMAGE_BASE_RE);
807 if (imageBaseFields) {
808 var imageBase = parseInt(imageBaseFields[1], 16);
809 if ((this.moduleType_ == 'exe') !=
810 (imageBase == WindowsCppEntriesProvider.EXE_IMAGE_BASE)) {
811 return false;
812 }
813 }
814
815 var fields = line.match(WindowsCppEntriesProvider.FUNC_RE);
816 return fields ?
817 { name: this.unmangleName(fields[1]), start: parseInt(fields[2], 16) } :
818 null;
819};
820
821
822/**
823 * Performs very simple unmangling of C++ names.
824 *
825 * Does not handle arguments and template arguments. The mangled names have
826 * the form:
827 *
828 * ?LookupInDescriptor@JSObject@internal@v8@@...arguments info...
829 */
830WindowsCppEntriesProvider.prototype.unmangleName = function(name) {
831 // Empty or non-mangled name.
832 if (name.length < 1 || name.charAt(0) != '?') return name;
833 var nameEndPos = name.indexOf('@@');
834 var components = name.substring(1, nameEndPos).split('@');
835 components.reverse();
836 return components.join('::');
837};
838
839
840function ArgumentsProcessor(args) {
841 this.args_ = args;
842 this.result_ = ArgumentsProcessor.DEFAULTS;
843
844 this.argsDispatch_ = {
845 '-j': ['stateFilter', TickProcessor.VmStates.JS,
846 'Show only ticks from JS VM state'],
847 '-g': ['stateFilter', TickProcessor.VmStates.GC,
848 'Show only ticks from GC VM state'],
849 '-c': ['stateFilter', TickProcessor.VmStates.COMPILER,
850 'Show only ticks from COMPILER VM state'],
851 '-o': ['stateFilter', TickProcessor.VmStates.OTHER,
852 'Show only ticks from OTHER VM state'],
853 '-e': ['stateFilter', TickProcessor.VmStates.EXTERNAL,
854 'Show only ticks from EXTERNAL VM state'],
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100855 '--call-graph-size': ['callGraphSize', TickProcessor.CALL_GRAPH_SIZE,
856 'Set the call graph size'],
Steve Blocka7e24c12009-10-30 11:49:00 +0000857 '--ignore-unknown': ['ignoreUnknown', true,
858 'Exclude ticks of unknown code entries from processing'],
859 '--separate-ic': ['separateIc', true,
860 'Separate IC entries'],
861 '--unix': ['platform', 'unix',
862 'Specify that we are running on *nix platform'],
863 '--windows': ['platform', 'windows',
864 'Specify that we are running on Windows platform'],
865 '--mac': ['platform', 'mac',
866 'Specify that we are running on Mac OS X platform'],
867 '--nm': ['nm', 'nm',
Leon Clarkee46be812010-01-19 14:06:41 +0000868 'Specify the \'nm\' executable to use (e.g. --nm=/my_dir/nm)'],
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000869 '--target': ['targetRootFS', '',
870 'Specify the target root directory for cross environment'],
Leon Clarkee46be812010-01-19 14:06:41 +0000871 '--snapshot-log': ['snapshotLogFileName', 'snapshot.log',
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000872 'Specify snapshot log file to use (e.g. --snapshot-log=snapshot.log)'],
873 '--range': ['range', 'auto,auto',
874 'Specify the range limit as [start],[end]'],
875 '--distortion': ['distortion', 0,
876 'Specify the logging overhead in picoseconds'],
877 '--source-map': ['sourceMap', null,
878 'Specify the source map that should be used for output']
Steve Blocka7e24c12009-10-30 11:49:00 +0000879 };
880 this.argsDispatch_['--js'] = this.argsDispatch_['-j'];
881 this.argsDispatch_['--gc'] = this.argsDispatch_['-g'];
882 this.argsDispatch_['--compiler'] = this.argsDispatch_['-c'];
883 this.argsDispatch_['--other'] = this.argsDispatch_['-o'];
884 this.argsDispatch_['--external'] = this.argsDispatch_['-e'];
885};
886
887
888ArgumentsProcessor.DEFAULTS = {
889 logFileName: 'v8.log',
Leon Clarkee46be812010-01-19 14:06:41 +0000890 snapshotLogFileName: null,
Steve Blocka7e24c12009-10-30 11:49:00 +0000891 platform: 'unix',
892 stateFilter: null,
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100893 callGraphSize: 5,
Steve Blocka7e24c12009-10-30 11:49:00 +0000894 ignoreUnknown: false,
895 separateIc: false,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000896 targetRootFS: '',
897 nm: 'nm',
898 range: 'auto,auto',
899 distortion: 0
Steve Blocka7e24c12009-10-30 11:49:00 +0000900};
901
902
903ArgumentsProcessor.prototype.parse = function() {
904 while (this.args_.length) {
905 var arg = this.args_[0];
906 if (arg.charAt(0) != '-') {
907 break;
908 }
909 this.args_.shift();
910 var userValue = null;
911 var eqPos = arg.indexOf('=');
912 if (eqPos != -1) {
913 userValue = arg.substr(eqPos + 1);
914 arg = arg.substr(0, eqPos);
915 }
916 if (arg in this.argsDispatch_) {
917 var dispatch = this.argsDispatch_[arg];
918 this.result_[dispatch[0]] = userValue == null ? dispatch[1] : userValue;
919 } else {
920 return false;
921 }
922 }
923
924 if (this.args_.length >= 1) {
925 this.result_.logFileName = this.args_.shift();
926 }
927 return true;
928};
929
930
931ArgumentsProcessor.prototype.result = function() {
932 return this.result_;
933};
934
935
936ArgumentsProcessor.prototype.printUsageAndExit = function() {
937
938 function padRight(s, len) {
939 s = s.toString();
940 if (s.length < len) {
941 s = s + (new Array(len - s.length + 1).join(' '));
942 }
943 return s;
944 }
945
946 print('Cmdline args: [options] [log-file-name]\n' +
947 'Default log file name is "' +
948 ArgumentsProcessor.DEFAULTS.logFileName + '".\n');
949 print('Options:');
950 for (var arg in this.argsDispatch_) {
951 var synonims = [arg];
952 var dispatch = this.argsDispatch_[arg];
953 for (var synArg in this.argsDispatch_) {
954 if (arg !== synArg && dispatch === this.argsDispatch_[synArg]) {
955 synonims.push(synArg);
956 delete this.argsDispatch_[synArg];
957 }
958 }
959 print(' ' + padRight(synonims.join(', '), 20) + dispatch[2]);
960 }
961 quit(2);
962};