blob: 08259e7025d28de2e4ba6142c2da840d6a830bcd [file] [log] [blame]
Hector Dearman20b3c1c2018-01-15 15:34:03 +00001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <inttypes.h>
18
19#include <stdio.h>
Hector Dearman85ef5362018-03-27 14:48:47 +010020#include <sys/ioctl.h>
21#include <unistd.h>
22
Hector Dearman20b3c1c2018-01-15 15:34:03 +000023#include <algorithm>
24#include <fstream>
25#include <iostream>
26#include <istream>
Hector Dearman85ef5362018-03-27 14:48:47 +010027#include <limits>
Hector Dearman20b3c1c2018-01-15 15:34:03 +000028#include <map>
29#include <memory>
30#include <ostream>
31#include <sstream>
32#include <string>
33#include <utility>
34
35#include <google/protobuf/compiler/importer.h>
36#include <google/protobuf/dynamic_message.h>
37#include <google/protobuf/io/zero_copy_stream_impl.h>
38#include <google/protobuf/text_format.h>
39#include <google/protobuf/util/field_comparator.h>
40#include <google/protobuf/util/message_differencer.h>
41
42#include "perfetto/base/logging.h"
Primiano Tucci20b760c2018-01-19 12:36:12 +000043#include "perfetto/trace/trace.pb.h"
44#include "perfetto/trace/trace_packet.pb.h"
Hector Dearman85ef5362018-03-27 14:48:47 +010045#include "tools/trace_to_text/ftrace_event_formatter.h"
Hector Dearman20b3c1c2018-01-15 15:34:03 +000046
47namespace perfetto {
48namespace {
49
50const char kTraceHeader[] = R"({
51 "traceEvents": [],
52)";
53
54const char kTraceFooter[] = R"(\n",
55 "controllerTraceDataKey": "systraceController"
56})";
57
58const char kFtraceHeader[] =
59 ""
60 " \"systemTraceEvents\": \""
61 "# tracer: nop\\n"
62 "#\\n"
63 "# entries-in-buffer/entries-written: 30624/30624 #P:4\\n"
64 "#\\n"
65 "# _-----=> irqs-off\\n"
66 "# / _----=> need-resched\\n"
67 "# | / _---=> hardirq/softirq\\n"
68 "# || / _--=> preempt-depth\\n"
69 "# ||| / delay\\n"
70 "# TASK-PID TGID CPU# |||| TIMESTAMP FUNCTION\\n"
71 "# | | | | |||| | |\\n";
72
Hector Dearman85ef5362018-03-27 14:48:47 +010073constexpr const char* inodeFileTypeArray[] = {"UNKNOWN", "FILE", "DIRECTORY"};
74
Hector Dearman20b3c1c2018-01-15 15:34:03 +000075using google::protobuf::Descriptor;
76using google::protobuf::DynamicMessageFactory;
77using google::protobuf::FileDescriptor;
78using google::protobuf::Message;
79using google::protobuf::TextFormat;
80using google::protobuf::compiler::DiskSourceTree;
81using google::protobuf::compiler::Importer;
82using google::protobuf::compiler::MultiFileErrorCollector;
83using google::protobuf::io::OstreamOutputStream;
Anna Zappone6e4e0382018-02-27 11:15:30 +000084
Anna Zappone6e4e0382018-02-27 11:15:30 +000085using protos::FtraceEvent;
86using protos::FtraceEventBundle;
Anna Zappone27ac99c2018-03-06 14:25:35 +000087using protos::InodeFileMap;
Anna Zappone6e4e0382018-02-27 11:15:30 +000088using protos::PrintFtraceEvent;
89using protos::ProcessTree;
90using protos::Trace;
91using protos::TracePacket;
Anna Zappone27ac99c2018-03-06 14:25:35 +000092using Entry = protos::InodeFileMap::Entry;
Isabelle Taylord404ea12018-02-19 17:28:01 +000093using Process = protos::ProcessTree::Process;
94
95// TODO(hjd): Add tests.
Hector Dearman20b3c1c2018-01-15 15:34:03 +000096
Hector Dearman85ef5362018-03-27 14:48:47 +010097size_t GetWidth() {
98 if (!isatty(STDOUT_FILENO))
99 return 80;
100 struct winsize win_size;
101 ioctl(STDOUT_FILENO, TIOCGWINSZ, &win_size);
102 return win_size.ws_col;
103}
104
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000105class MFE : public MultiFileErrorCollector {
106 virtual void AddError(const std::string& filename,
107 int line,
108 int column,
109 const std::string& message) {
110 PERFETTO_ELOG("Error %s %d:%d: %s", filename.c_str(), line, column,
111 message.c_str());
112 }
113
114 virtual void AddWarning(const std::string& filename,
115 int line,
116 int column,
117 const std::string& message) {
118 PERFETTO_ELOG("Error %s %d:%d: %s", filename.c_str(), line, column,
119 message.c_str());
120 }
121};
122
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000123uint64_t TimestampToSeconds(uint64_t timestamp) {
124 return timestamp / 1000000000ul;
125}
126
127uint64_t TimestampToMicroseconds(uint64_t timestamp) {
128 return (timestamp / 1000) % 1000000ul;
129}
130
Hector Dearman7f37dc82018-01-25 12:25:40 +0000131std::string FormatPrefix(uint64_t timestamp, uint64_t cpu) {
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000132 char line[2048];
133 uint64_t seconds = TimestampToSeconds(timestamp);
134 uint64_t useconds = TimestampToMicroseconds(timestamp);
135 sprintf(line,
136 "<idle>-0 (-----) [%03" PRIu64 "] d..3 %" PRIu64 ".%.6" PRIu64
Hector Dearman7f37dc82018-01-25 12:25:40 +0000137 ": ",
138 cpu, seconds, useconds);
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000139 return std::string(line);
140}
141
Isabelle Taylord404ea12018-02-19 17:28:01 +0000142// TODO(taylori): Confirm correct format for this.
Anna Zappone2166b712018-03-16 11:30:29 +0000143// Calling this breaks loading into chrome://tracing
Isabelle Taylord404ea12018-02-19 17:28:01 +0000144std::string FormatProcess(const Process& process) {
145 char line[2048];
Isabelle Taylore3504972018-02-26 10:27:51 +0000146 sprintf(line, "process: pid=%d ppid=%d cmdline=", process.pid(),
147 process.ppid());
Isabelle Taylord404ea12018-02-19 17:28:01 +0000148 std::string output = std::string(line);
Isabelle Taylore3504972018-02-26 10:27:51 +0000149 for (auto field : process.cmdline()) {
150 char cmd[2048];
151 sprintf(cmd, "%s ", field.c_str());
152 output += std::string(cmd);
153 }
154 output += "\\n";
Isabelle Taylord404ea12018-02-19 17:28:01 +0000155 for (auto thread : process.threads()) {
156 char thread_line[2048];
157 sprintf(thread_line, "thread: tid=%d name=%s\\n", thread.tid(),
158 thread.name().c_str());
159 output += thread_line;
160 }
161 return output;
162}
163
Anna Zappone2166b712018-03-16 11:30:29 +0000164// Calling this breaks loading into chrome://tracing
Anna Zappone27ac99c2018-03-06 14:25:35 +0000165std::string FormatInodeFileMap(const Entry& entry) {
166 char line[2048];
167 sprintf(line, "inode_file_map: ino=%llu type=%s path=", entry.inode_number(),
168 inodeFileTypeArray[entry.type()]);
169 std::string output = std::string(line);
170 for (auto field : entry.paths()) {
171 char path[2048];
172 sprintf(path, "%s", field.c_str());
173 output += std::string(path);
174 }
175 return output;
176}
177
Hector Dearman85ef5362018-03-27 14:48:47 +0100178void ForEachPacketInTrace(
179 std::istream* input,
180 const std::function<void(const protos::TracePacket&)>& f) {
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100181 size_t bytes_processed = 0;
182 // The trace stream can be very large. We cannot just pass it in one go to
183 // libprotobuf as that will refuse to parse messages > 64MB. However we know
184 // that a trace is merely a sequence of TracePackets. Here we just manually
185 // tokenize the repeated TracePacket messages and parse them individually
186 // using libprotobuf.
187 for (;;) {
188 fprintf(stderr, "Processing trace: %8zu KB\r", bytes_processed / 1024);
189 fflush(stderr);
190 // A TracePacket consists in one byte stating its field id and type ...
191 char preamble;
192 input->get(preamble);
193 if (!input->good())
194 break;
195 bytes_processed++;
196 PERFETTO_DCHECK(preamble == 0x0a); // Field ID:1, type:length delimited.
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000197
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100198 // ... a varint stating its size ...
199 uint32_t field_size = 0;
200 uint32_t shift = 0;
201 for (;;) {
202 char c = 0;
203 input->get(c);
204 field_size |= static_cast<uint32_t>(c & 0x7f) << shift;
205 shift += 7;
206 bytes_processed++;
207 if (!(c & 0x80))
208 break;
209 }
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000210
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100211 // ... and the actual TracePacket itself.
212 std::unique_ptr<char[]> buf(new char[field_size]);
213 input->read(buf.get(), field_size);
214 bytes_processed += field_size;
215
216 protos::TracePacket packet;
217 PERFETTO_CHECK(packet.ParseFromArray(buf.get(), field_size));
Anna Zappone27ac99c2018-03-06 14:25:35 +0000218
Hector Dearman85ef5362018-03-27 14:48:47 +0100219 f(packet);
220 }
221}
222
223int TraceToSystrace(std::istream* input, std::ostream* output) {
224 std::multimap<uint64_t, std::string> sorted;
225
226 ForEachPacketInTrace(input, [&sorted](const protos::TracePacket& packet) {
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000227 if (!packet.has_ftrace_events())
Hector Dearman85ef5362018-03-27 14:48:47 +0100228 return;
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000229
230 const FtraceEventBundle& bundle = packet.ftrace_events();
231 for (const FtraceEvent& event : bundle.event()) {
Hector Dearman85ef5362018-03-27 14:48:47 +0100232 std::string line =
233 FormatFtraceEvent(event.timestamp(), bundle.cpu(), event);
234 if (line == "")
Hector Dearman7f37dc82018-01-25 12:25:40 +0000235 continue;
Hector Dearman85ef5362018-03-27 14:48:47 +0100236 sorted.emplace(event.timestamp(), line);
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000237 }
Hector Dearman85ef5362018-03-27 14:48:47 +0100238 });
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000239
240 *output << kTraceHeader;
241 *output << kFtraceHeader;
242
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100243 fprintf(stderr, "\n");
244 size_t total_events = sorted.size();
245 size_t written_events = 0;
246 for (auto it = sorted.begin(); it != sorted.end(); it++) {
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000247 *output << it->second;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100248 if (written_events++ % 100 == 0) {
249 fprintf(stderr, "Writing trace: %.2f %%\r",
250 written_events * 100.0 / total_events);
251 fflush(stderr);
252 }
253 }
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000254
255 *output << kTraceFooter;
256
257 return 0;
258}
259
Hector Dearman85ef5362018-03-27 14:48:47 +0100260int TraceToText(std::istream* input, std::ostream* output) {
261 DiskSourceTree dst;
262 dst.MapPath("perfetto", "protos/perfetto");
263 MFE mfe;
264 Importer importer(&dst, &mfe);
265 const FileDescriptor* parsed_file =
266 importer.Import("perfetto/trace/trace.proto");
267
268 DynamicMessageFactory dmf;
269 const Descriptor* trace_descriptor = parsed_file->message_type(0);
270 const Message* msg_root = dmf.GetPrototype(trace_descriptor);
271 Message* msg = msg_root->New();
272
273 if (!msg->ParseFromIstream(input)) {
274 PERFETTO_ELOG("Could not parse input.");
275 return 1;
276 }
277 OstreamOutputStream zero_copy_output(output);
278 TextFormat::Print(*msg, &zero_copy_output);
279 return 0;
280}
281
282int TraceToSummary(std::istream* input, std::ostream* output) {
283 uint64_t start = std::numeric_limits<uint64_t>::max();
284 uint64_t end = 0;
285 std::multiset<uint64_t> ftrace_timestamps;
Isabelle Taylord496ea52018-03-28 11:59:59 +0100286 std::set<pid_t> tids_in_tree;
287 std::set<pid_t> tids_in_events;
Hector Dearman85ef5362018-03-27 14:48:47 +0100288
Isabelle Taylord496ea52018-03-28 11:59:59 +0100289 ForEachPacketInTrace(
290 input, [&start, &end, &ftrace_timestamps, &tids_in_tree,
291 &tids_in_events](const protos::TracePacket& packet) {
Hector Dearman85ef5362018-03-27 14:48:47 +0100292
Isabelle Taylord496ea52018-03-28 11:59:59 +0100293 if (packet.has_process_tree()) {
294 const ProcessTree& tree = packet.process_tree();
295 for (Process process : tree.processes()) {
296 for (ProcessTree::Thread thread : process.threads()) {
297 tids_in_tree.insert(thread.tid());
298 }
299 }
300 }
Hector Dearman85ef5362018-03-27 14:48:47 +0100301
Isabelle Taylord496ea52018-03-28 11:59:59 +0100302 if (!packet.has_ftrace_events())
303 return;
304
305 const FtraceEventBundle& bundle = packet.ftrace_events();
306
307 for (const FtraceEvent& event : bundle.event()) {
308 if (event.pid()) {
309 tids_in_events.insert(event.pid());
310 }
311 if (event.timestamp()) {
312 start = std::min<uint64_t>(start, event.timestamp());
313 end = std::max<uint64_t>(end, event.timestamp());
314 ftrace_timestamps.insert(event.timestamp());
315 }
316 }
317 });
Hector Dearman85ef5362018-03-27 14:48:47 +0100318
319 fprintf(stderr, "\n");
320
321 char line[2048];
322 sprintf(line, "Duration: %" PRIu64 "ms\n", (end - start) / (1000 * 1000));
323 *output << std::string(line);
324
325 constexpr char kFtraceTrackName[] = "ftrace ";
326 size_t width = GetWidth();
327 size_t bucket_count = width - strlen(kFtraceTrackName);
328 size_t bucket_size = (end - start) / bucket_count;
329 size_t max = 0;
330 std::vector<size_t> buckets(bucket_count);
331 for (size_t i = 0; i < bucket_count; i++) {
332 auto low = ftrace_timestamps.lower_bound(i * bucket_size + start);
333 auto high = ftrace_timestamps.upper_bound((i + 1) * bucket_size + start);
334 buckets[i] = std::distance(low, high);
335 max = std::max(max, buckets[i]);
336 }
337
338 std::vector<std::string> out =
339 std::vector<std::string>({" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇"});
340 *output << kFtraceTrackName;
341 for (size_t i = 0; i < bucket_count; i++) {
342 sprintf(
343 line, "%s",
344 out[std::min(buckets[i] / (max / out.size()), out.size() - 1)].c_str());
345 *output << std::string(line);
346 }
Isabelle Taylord496ea52018-03-28 11:59:59 +0100347 *output << "\n\n";
348
349 *output << "----------------Process Tree Stats----------------\n";
350
351 char tid[2048];
352 sprintf(tid, "Unique thread ids in process tree: %" PRIu64 "\n",
353 tids_in_tree.size());
354 *output << std::string(tid);
355
356 char tid_event[2048];
357 sprintf(tid_event, "Unique thread ids in ftrace events: %" PRIu64 "\n",
358 tids_in_events.size());
359 *output << std::string(tid_event);
360
361 std::set<pid_t> intersect;
362 set_intersection(tids_in_tree.begin(), tids_in_tree.end(),
363 tids_in_events.begin(), tids_in_events.end(),
364 std::inserter(intersect, intersect.begin()));
365
366 char matching[2048];
367 sprintf(matching,
368 "Thread ids with process info: %" PRIu64 "/%" PRIu64 " -> %" PRIu64
369 "%%\n\n",
370 intersect.size(), tids_in_events.size(),
371 (intersect.size() * 100) / tids_in_events.size());
372 *output << std::string(matching);
373
Hector Dearman85ef5362018-03-27 14:48:47 +0100374 return 0;
375}
376
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000377} // namespace
378} // namespace perfetto
379
380namespace {
381
382int Usage(int argc, char** argv) {
Hector Dearman85ef5362018-03-27 14:48:47 +0100383 printf("Usage: %s [systrace|text|summary] < trace.proto > trace.txt\n",
384 argv[0]);
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000385 return 1;
386}
387
388} // namespace
389
390int main(int argc, char** argv) {
391 if (argc != 2)
392 return Usage(argc, argv);
393
394 std::string format(argv[1]);
395
Hector Dearman85ef5362018-03-27 14:48:47 +0100396 bool is_systrace = format == "systrace";
397 bool is_text = format == "text";
398 bool is_summary = format == "summary";
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000399
Hector Dearman85ef5362018-03-27 14:48:47 +0100400 if (is_systrace)
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000401 return perfetto::TraceToSystrace(&std::cin, &std::cout);
Hector Dearman85ef5362018-03-27 14:48:47 +0100402 if (is_text)
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000403 return perfetto::TraceToText(&std::cin, &std::cout);
Hector Dearman85ef5362018-03-27 14:48:47 +0100404 if (is_summary)
405 return perfetto::TraceToSummary(&std::cin, &std::cout);
406 return Usage(argc, argv);
Hector Dearman20b3c1c2018-01-15 15:34:03 +0000407}