• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2013 the V8 project authors. All rights reserved.
2// 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
28Array.prototype.top = function() {
29  if (this.length == 0) return undefined;
30  return this[this.length - 1];
31}
32
33
34function PlotScriptComposer(kResX, kResY, error_output) {
35  // Constants.
36  var kV8BinarySuffixes = ["/d8", "/libv8.so"];
37  var kStackFrames = 8;             // Stack frames to display in the plot.
38
39  var kTimerEventWidth = 0.33;      // Width of each timeline.
40  var kExecutionFrameWidth = 0.2;   // Width of the top stack frame line.
41  var kStackFrameWidth = 0.1;       // Width of the lower stack frame lines.
42  var kGapWidth = 0.05;             // Gap between stack frame lines.
43
44  var kY1Offset = 11;               // Offset for stack frame vs. event lines.
45  var kDeoptRow = 7;                // Row displaying deopts.
46  var kGetTimeHeight = 0.5;         // Height of marker displaying timed part.
47  var kMaxDeoptLength = 4;          // Draw size of the largest deopt.
48  var kPauseLabelPadding = 5;       // Padding for pause time labels.
49  var kNumPauseLabels = 7;          // Number of biggest pauses to label.
50  var kCodeKindLabelPadding = 100;  // Padding for code kind labels.
51
52  var kTickHalfDuration = 0.5;      // Duration of half a tick in ms.
53  var kMinRangeLength = 0.0005;     // Minimum length for an event in ms.
54
55  var kNumThreads = 2;              // Number of threads.
56  var kExecutionThreadId = 0;       // ID of main thread.
57
58  // Init values.
59  var num_timer_event = kY1Offset + 0.5;
60
61  // Data structures.
62  function TimerEvent(label, color, pause, thread_id) {
63    assert(thread_id >= 0 && thread_id < kNumThreads, "invalid thread id");
64    this.label = label;
65    this.color = color;
66    this.pause = pause;
67    this.ranges = [];
68    this.thread_id = thread_id;
69    this.index = ++num_timer_event;
70  }
71
72  function CodeKind(color, kinds) {
73    this.color = color;
74    this.in_execution = [];
75    this.stack_frames = [];
76    for (var i = 0; i < kStackFrames; i++) this.stack_frames.push([]);
77    this.kinds = kinds;
78  }
79
80  function Range(start, end) {
81    this.start = start;  // In milliseconds.
82    this.end = end;      // In milliseconds.
83  }
84
85  function Deopt(time, size) {
86    this.time = time;  // In milliseconds.
87    this.size = size;  // In bytes.
88  }
89
90  Range.prototype.duration = function() { return this.end - this.start; }
91
92  function Tick(tick) {
93    this.tick = tick;
94  }
95
96  var TimerEvents = {
97      'V8.Execute':
98        new TimerEvent("execution", "#000000", false, 0),
99      'V8.External':
100        new TimerEvent("external", "#3399FF", false, 0),
101      'V8.CompileFullCode':
102        new TimerEvent("compile unopt", "#CC0000",  true, 0),
103      'V8.RecompileSynchronous':
104        new TimerEvent("recompile sync", "#CC0044",  true, 0),
105      'V8.RecompileConcurrent':
106        new TimerEvent("recompile async", "#CC4499", false, 1),
107      'V8.CompileEvalMicroSeconds':
108        new TimerEvent("compile eval", "#CC4400",  true, 0),
109      'V8.ParseMicroSeconds':
110        new TimerEvent("parse", "#00CC00",  true, 0),
111      'V8.PreParseMicroSeconds':
112        new TimerEvent("preparse", "#44CC00",  true, 0),
113      'V8.ParseLazyMicroSeconds':
114        new TimerEvent("lazy parse", "#00CC44",  true, 0),
115      'V8.GCScavenger':
116        new TimerEvent("gc scavenge", "#0044CC",  true, 0),
117      'V8.GCCompactor':
118        new TimerEvent("gc compaction", "#4444CC",  true, 0),
119      'V8.GCContext':
120        new TimerEvent("gc context", "#4400CC",  true, 0),
121  };
122
123  var CodeKinds = {
124      'external ': new CodeKind("#3399FF", [-2]),
125      'runtime  ': new CodeKind("#000000", [-1]),
126      'full code': new CodeKind("#DD0000", [0]),
127      'opt code ': new CodeKind("#00EE00", [1]),
128      'code stub': new CodeKind("#FF00FF", [2]),
129      'built-in ': new CodeKind("#AA00AA", [3]),
130      'inl.cache': new CodeKind("#4444AA",
131                                [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]),
132      'reg.exp. ': new CodeKind("#0000FF", [15]),
133  };
134
135  var code_map = new CodeMap();
136  var execution_pauses = [];
137  var deopts = [];
138  var gettime = [];
139  var event_stack = [];
140  var last_time_stamp = [];
141  for (var i = 0; i < kNumThreads; i++) {
142    event_stack[i] = [];
143    last_time_stamp[i] = -1;
144  }
145
146  var range_start = undefined;
147  var range_end = undefined;
148  var obj_index = 0;
149  var pause_tolerance = 0.005;  // Milliseconds.
150  var distortion = 0;
151
152  // Utility functions.
153  function assert(something, message) {
154    if (!something) {
155      var error = new Error(message);
156      error_output(error.stack);
157    }
158  }
159
160  function FindCodeKind(kind) {
161    for (name in CodeKinds) {
162      if (CodeKinds[name].kinds.indexOf(kind) >= 0) {
163        return CodeKinds[name];
164      }
165    }
166  }
167
168  function TicksToRanges(ticks) {
169    var ranges = [];
170    for (var i = 0; i < ticks.length; i++) {
171      var tick = ticks[i].tick;
172      ranges.push(
173          new Range(tick - kTickHalfDuration, tick + kTickHalfDuration));
174    }
175    return ranges;
176  }
177
178  function MergeRanges(ranges) {
179    ranges.sort(function(a, b) {
180      return (a.start == b.start) ? a.end - b.end : a.start - b.start;
181    });
182    var result = [];
183    var j = 0;
184    for (var i = 0; i < ranges.length; i = j) {
185      var merge_start = ranges[i].start;
186      if (merge_start > range_end) break;  // Out of plot range.
187      var merge_end = ranges[i].end;
188      for (j = i + 1; j < ranges.length; j++) {
189        var next_range = ranges[j];
190        // Don't merge ranges if there is no overlap (incl. merge tolerance).
191        if (next_range.start > merge_end + pause_tolerance) break;
192        // Merge ranges.
193        if (next_range.end > merge_end) {  // Extend range end.
194          merge_end = next_range.end;
195        }
196      }
197      if (merge_end < range_start) continue;  // Out of plot range.
198      if (merge_end < merge_start) continue;  // Not an actual range.
199      result.push(new Range(merge_start, merge_end));
200    }
201    return result;
202  }
203
204  function RestrictRangesTo(ranges, start, end) {
205    var result = [];
206    for (var i = 0; i < ranges.length; i++) {
207      if (ranges[i].start <= end && ranges[i].end >= start) {
208        result.push(new Range(Math.max(ranges[i].start, start),
209                              Math.min(ranges[i].end, end)));
210      }
211    }
212    return result;
213  }
214
215  // Public methods.
216  this.collectData = function(input, distortion_per_entry) {
217
218    var last_timestamp = 0;
219
220    // Parse functions.
221    var parseTimeStamp = function(timestamp) {
222      int_timestamp = parseInt(timestamp);
223      assert(int_timestamp >= last_timestamp, "Inconsistent timestamps.");
224      last_timestamp = int_timestamp;
225      distortion += distortion_per_entry;
226      return int_timestamp / 1000 - distortion;
227    }
228
229    var processTimerEventStart = function(name, start) {
230      // Find out the thread id.
231      var new_event = TimerEvents[name];
232      if (new_event === undefined) return;
233      var thread_id = new_event.thread_id;
234
235      start = Math.max(last_time_stamp[thread_id] + kMinRangeLength, start);
236
237      // Last event on this thread is done with the start of this event.
238      var last_event = event_stack[thread_id].top();
239      if (last_event !== undefined) {
240        var new_range = new Range(last_time_stamp[thread_id], start);
241        last_event.ranges.push(new_range);
242      }
243      event_stack[thread_id].push(new_event);
244      last_time_stamp[thread_id] = start;
245    };
246
247    var processTimerEventEnd = function(name, end) {
248      // Find out about the thread_id.
249      var finished_event = TimerEvents[name];
250      var thread_id = finished_event.thread_id;
251      assert(finished_event === event_stack[thread_id].pop(),
252             "inconsistent event stack");
253
254      end = Math.max(last_time_stamp[thread_id] + kMinRangeLength, end);
255
256      var new_range = new Range(last_time_stamp[thread_id], end);
257      finished_event.ranges.push(new_range);
258      last_time_stamp[thread_id] = end;
259    };
260
261    var processCodeCreateEvent = function(type, kind, address, size, name) {
262      var code_entry = new CodeMap.CodeEntry(size, name);
263      code_entry.kind = kind;
264      code_map.addCode(address, code_entry);
265    };
266
267    var processCodeMoveEvent = function(from, to) {
268      code_map.moveCode(from, to);
269    };
270
271    var processCodeDeleteEvent = function(address) {
272      code_map.deleteCode(address);
273    };
274
275    var processCodeDeoptEvent = function(time, size) {
276      deopts.push(new Deopt(time, size));
277    }
278
279    var processCurrentTimeEvent = function(time) {
280      gettime.push(time);
281    }
282
283    var processSharedLibrary = function(name, start, end) {
284      var code_entry = new CodeMap.CodeEntry(end - start, name);
285      code_entry.kind = -3;  // External code kind.
286      for (var i = 0; i < kV8BinarySuffixes.length; i++) {
287        var suffix = kV8BinarySuffixes[i];
288        if (name.indexOf(suffix, name.length - suffix.length) >= 0) {
289          code_entry.kind = -1;  // V8 runtime code kind.
290          break;
291        }
292      }
293      code_map.addLibrary(start, code_entry);
294    };
295
296    var processTickEvent = function(
297        pc, timer, unused_x, unused_y, vmstate, stack) {
298      var tick = new Tick(timer);
299
300      var entry = code_map.findEntry(pc);
301      if (entry) FindCodeKind(entry.kind).in_execution.push(tick);
302
303      for (var i = 0; i < kStackFrames; i++) {
304        if (!stack[i]) break;
305        var entry = code_map.findEntry(stack[i]);
306        if (entry) FindCodeKind(entry.kind).stack_frames[i].push(tick);
307      }
308    };
309    // Collect data from log.
310    var logreader = new LogReader(
311      { 'timer-event-start': { parsers: [parseString, parseTimeStamp],
312                               processor: processTimerEventStart },
313        'timer-event-end':   { parsers: [parseString, parseTimeStamp],
314                               processor: processTimerEventEnd },
315        'shared-library': { parsers: [parseString, parseInt, parseInt],
316                            processor: processSharedLibrary },
317        'code-creation':  { parsers: [parseString, parseInt, parseInt,
318                                parseInt, parseString],
319                            processor: processCodeCreateEvent },
320        'code-move':      { parsers: [parseInt, parseInt],
321                            processor: processCodeMoveEvent },
322        'code-delete':    { parsers: [parseInt],
323                            processor: processCodeDeleteEvent },
324        'code-deopt':     { parsers: [parseTimeStamp, parseInt],
325                            processor: processCodeDeoptEvent },
326        'current-time':   { parsers: [parseTimeStamp],
327                            processor: processCurrentTimeEvent },
328        'tick':           { parsers: [parseInt, parseTimeStamp, parseString,
329                                parseString, parseInt, parseVarArgs],
330                            processor: processTickEvent }
331      });
332
333    var line;
334    while (line = input()) {
335      for (var s of line.split("\n")) logreader.processLogLine(s);
336    }
337
338    // Collect execution pauses.
339    for (name in TimerEvents) {
340      var event = TimerEvents[name];
341      if (!event.pause) continue;
342      var ranges = event.ranges;
343      for (var j = 0; j < ranges.length; j++) execution_pauses.push(ranges[j]);
344    }
345    execution_pauses = MergeRanges(execution_pauses);
346  };
347
348
349  this.findPlotRange = function(
350    range_start_override, range_end_override, result_callback) {
351    var start_found = (range_start_override || range_start_override == 0);
352    var end_found = (range_end_override || range_end_override == 0);
353    range_start = start_found ? range_start_override : Infinity;
354    range_end = end_found ? range_end_override : -Infinity;
355
356    if (!start_found || !end_found) {
357      for (name in TimerEvents) {
358        var ranges = TimerEvents[name].ranges;
359        for (var i = 0; i < ranges.length; i++) {
360          if (ranges[i].start < range_start && !start_found) {
361            range_start = ranges[i].start;
362          }
363          if (ranges[i].end > range_end && !end_found) {
364            range_end = ranges[i].end;
365          }
366        }
367      }
368
369      for (codekind in CodeKinds) {
370        var ticks = CodeKinds[codekind].in_execution;
371        for (var i = 0; i < ticks.length; i++) {
372          if (ticks[i].tick < range_start && !start_found) {
373            range_start = ticks[i].tick;
374          }
375          if (ticks[i].tick > range_end && !end_found) {
376            range_end = ticks[i].tick;
377          }
378        }
379      }
380    }
381    // Set pause tolerance to something appropriate for the plot resolution
382    // to make it easier for gnuplot.
383    pause_tolerance = (range_end - range_start) / kResX / 10;
384
385    if (typeof result_callback === 'function') {
386      result_callback(range_start, range_end);
387    }
388  };
389
390
391  this.assembleOutput = function(output) {
392    output("set yrange [0:" + (num_timer_event + 1) + "]");
393    output("set xlabel \"execution time in ms\"");
394    output("set xrange [" + range_start + ":" + range_end + "]");
395    output("set style fill pattern 2 bo 1");
396    output("set style rect fs solid 1 noborder");
397    output("set style line 1 lt 1 lw 1 lc rgb \"#000000\"");
398    output("set border 15 lw 0.2");  // Draw thin border box.
399    output("set style line 2 lt 1 lw 1 lc rgb \"#9944CC\"");
400    output("set xtics out nomirror");
401    output("unset key");
402
403    function DrawBarBase(color, start, end, top, bottom, transparency) {
404      obj_index++;
405      command = "set object " + obj_index + " rect";
406      command += " from " + start + ", " + top;
407      command += " to " + end + ", " + bottom;
408      command += " fc rgb \"" + color + "\"";
409      if (transparency) {
410        command += " fs transparent solid " + transparency;
411      }
412      output(command);
413    }
414
415    function DrawBar(row, color, start, end, width) {
416      DrawBarBase(color, start, end, row + width, row - width);
417    }
418
419    function DrawHalfBar(row, color, start, end, width) {
420      DrawBarBase(color, start, end, row, row - width);
421    }
422
423    var percentages = {};
424    var total = 0;
425    for (var name in TimerEvents) {
426      var event = TimerEvents[name];
427      var ranges = RestrictRangesTo(event.ranges, range_start, range_end);
428      var sum =
429        ranges.map(function(range) { return range.duration(); })
430            .reduce(function(a, b) { return a + b; }, 0);
431      percentages[name] = (sum / (range_end - range_start) * 100).toFixed(1);
432    }
433
434    // Plot deopts.
435    deopts.sort(function(a, b) { return b.size - a.size; });
436    var max_deopt_size = deopts.length > 0 ? deopts[0].size : Infinity;
437
438    for (var i = 0; i < deopts.length; i++) {
439      var deopt = deopts[i];
440      DrawHalfBar(kDeoptRow, "#9944CC", deopt.time,
441                  deopt.time + 10 * pause_tolerance,
442                  deopt.size / max_deopt_size * kMaxDeoptLength);
443    }
444
445    // Plot current time polls.
446    if (gettime.length > 1) {
447      var start = gettime[0];
448      var end = gettime.pop();
449      DrawBarBase("#0000BB", start, end, kGetTimeHeight, 0, 0.2);
450    }
451
452    // Name Y-axis.
453    var ytics = [];
454    for (name in TimerEvents) {
455      var index = TimerEvents[name].index;
456      var label = TimerEvents[name].label;
457      ytics.push('"' + label + ' (' + percentages[name] + '%%)" ' + index);
458    }
459    ytics.push('"code kind color coding" ' + kY1Offset);
460    ytics.push('"code kind in execution" ' + (kY1Offset - 1));
461    ytics.push('"top ' + kStackFrames + ' js stack frames"' + ' ' +
462               (kY1Offset - 2));
463    ytics.push('"pause times" 0');
464    ytics.push('"max deopt size: ' + (max_deopt_size / 1024).toFixed(1) +
465               ' kB" ' + kDeoptRow);
466    output("set ytics out nomirror (" + ytics.join(', ') + ")");
467
468    // Plot timeline.
469    for (var name in TimerEvents) {
470      var event = TimerEvents[name];
471      var ranges = MergeRanges(event.ranges);
472      for (var i = 0; i < ranges.length; i++) {
473        DrawBar(event.index, event.color,
474                ranges[i].start, ranges[i].end,
475                kTimerEventWidth);
476      }
477    }
478
479    // Plot code kind gathered from ticks.
480    for (var name in CodeKinds) {
481      var code_kind = CodeKinds[name];
482      var offset = kY1Offset - 1;
483      // Top most frame.
484      var row = MergeRanges(TicksToRanges(code_kind.in_execution));
485      for (var j = 0; j < row.length; j++) {
486        DrawBar(offset, code_kind.color,
487                row[j].start, row[j].end, kExecutionFrameWidth);
488      }
489      offset = offset - 2 * kExecutionFrameWidth - kGapWidth;
490      // Javascript frames.
491      for (var i = 0; i < kStackFrames; i++) {
492        offset = offset - 2 * kStackFrameWidth - kGapWidth;
493        row = MergeRanges(TicksToRanges(code_kind.stack_frames[i]));
494        for (var j = 0; j < row.length; j++) {
495          DrawBar(offset, code_kind.color,
496                  row[j].start, row[j].end, kStackFrameWidth);
497        }
498      }
499    }
500
501    // Add labels as legend for code kind colors.
502    var padding = kCodeKindLabelPadding * (range_end - range_start) / kResX;
503    var label_x = range_start;
504    var label_y = kY1Offset;
505    for (var name in CodeKinds) {
506      label_x += padding;
507      output("set label \"" + name + "\" at " + label_x + "," + label_y +
508             " textcolor rgb \"" + CodeKinds[name].color + "\"" +
509             " font \"Helvetica,9'\"");
510      obj_index++;
511    }
512
513    if (execution_pauses.length == 0) {
514      // Force plot and return without plotting execution pause impulses.
515      output("plot 1/0");
516      return;
517    }
518
519    // Label the longest pauses.
520    execution_pauses =
521        RestrictRangesTo(execution_pauses, range_start, range_end);
522    execution_pauses.sort(function(a, b) {
523      if (a.duration() == b.duration() && b.end == a.end)
524        return b.start - a.start;
525
526      return (a.duration() == b.duration())
527          ? b.end - a.end : b.duration() - a.duration();
528    });
529
530    var max_pause_time = execution_pauses.length > 0
531        ? execution_pauses[0].duration() : 0;
532    padding = kPauseLabelPadding * (range_end - range_start) / kResX;
533    var y_scale = kY1Offset / max_pause_time / 2;
534    for (var i = 0; i < execution_pauses.length && i < kNumPauseLabels; i++) {
535      var pause = execution_pauses[i];
536      var label_content = (pause.duration() | 0) + " ms";
537      var label_x = pause.end + padding;
538      var label_y = Math.max(1, (pause.duration() * y_scale));
539      output("set label \"" + label_content + "\" at " +
540             label_x + "," + label_y + " font \"Helvetica,7'\"");
541      obj_index++;
542    }
543
544    // Scale second Y-axis appropriately.
545    var y2range = max_pause_time * num_timer_event / kY1Offset * 2;
546    output("set y2range [0:" + y2range + "]");
547    // Plot graph with impulses as data set.
548    output("plot '-' using 1:2 axes x1y2 with impulses ls 1");
549    for (var i = 0; i < execution_pauses.length; i++) {
550      var pause = execution_pauses[i];
551      output(pause.end + " " + pause.duration());
552      obj_index++;
553    }
554    output("e");
555    return obj_index;
556  };
557}
558