blob: cb6a17e063bf9b682c0a15a66b2cb8ea0705efb2 [file] [log] [blame]
Primiano Tucci5968caf2018-08-06 10:31:46 +01001/*
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 */
Primiano Tucci0f3872d2020-06-02 22:44:28 +010016#include <errno.h>
Primiano Tucci7e330292018-08-24 19:10:52 +020017#include <fcntl.h>
Lalit Maganti21160e82018-10-16 09:40:29 +010018#include <inttypes.h>
Lalit Maganti26f69bd2019-04-29 18:23:47 +010019#include <stdio.h>
Primiano Tucci7e330292018-08-24 19:10:52 +020020#include <sys/stat.h>
Primiano Tucci5968caf2018-08-06 10:31:46 +010021
22#include <functional>
Lalit Maganti21160e82018-10-16 09:40:29 +010023#include <iostream>
Lalit Maganti7c959782019-04-02 16:54:12 +010024#include <vector>
Primiano Tucci5968caf2018-08-06 10:31:46 +010025
Lalit Magantica4d5142019-05-28 13:25:47 +010026#include <google/protobuf/compiler/parser.h>
Lalit Maganti812ef672019-05-28 13:28:02 +010027#include <google/protobuf/dynamic_message.h>
Lalit Magantica4d5142019-05-28 13:25:47 +010028#include <google/protobuf/io/zero_copy_stream_impl.h>
Lalit Maganti812ef672019-05-28 13:28:02 +010029#include <google/protobuf/text_format.h>
Lalit Magantica4d5142019-05-28 13:25:47 +010030
Primiano Tucci24647142018-08-13 21:18:24 +020031#include "perfetto/base/build_config.h"
Primiano Tucci5968caf2018-08-06 10:31:46 +010032#include "perfetto/base/logging.h"
Eric Seckler83dcc8c2019-08-21 12:18:43 +010033#include "perfetto/base/time.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010034#include "perfetto/ext/base/file_utils.h"
35#include "perfetto/ext/base/scoped_file.h"
36#include "perfetto/ext/base/string_splitter.h"
Lalit Maganti7e2d2d32020-03-20 21:55:11 +000037#include "perfetto/ext/base/string_utils.h"
Primiano Tucciec590132020-11-16 14:16:44 +010038#include "perfetto/ext/base/version.h"
Florian Mayer9a683092020-12-23 18:30:00 +000039
Eric Seckler8f70bbf2019-10-09 09:37:43 +010040#include "perfetto/trace_processor/read_trace.h"
Ioannis Ilkoseff38f52018-10-29 10:37:55 +000041#include "perfetto/trace_processor/trace_processor.h"
Deepanjan Royf4da5092020-07-15 17:59:04 -040042#include "src/trace_processor/metrics/chrome/all_chrome_metrics.descriptor.h"
Lalit Maganti812ef672019-05-28 13:28:02 +010043#include "src/trace_processor/metrics/metrics.descriptor.h"
Lalit Maganti3d9bbff2020-04-15 13:40:58 +010044#include "src/trace_processor/util/proto_to_json.h"
Lalit Maganti2ae24642020-04-16 13:14:17 +010045#include "src/trace_processor/util/status_macros.h"
Primiano Tucci5968caf2018-08-06 10:31:46 +010046
Primiano Tuccia36cccc2019-10-27 13:15:04 +010047#if PERFETTO_BUILDFLAG(PERFETTO_TP_HTTPD)
48#include "src/trace_processor/rpc/httpd.h"
49#endif
Florian Mayer9a683092020-12-23 18:30:00 +000050#include "src/profiling/deobfuscator.h"
Andres Medinad6a8d3c2020-11-04 17:12:49 -080051#include "src/profiling/symbolizer/local_symbolizer.h"
Florian Mayer6cc8b1d2019-12-18 16:37:32 +000052#include "src/profiling/symbolizer/symbolize_database.h"
53#include "src/profiling/symbolizer/symbolizer.h"
Florian Mayer6cc8b1d2019-12-18 16:37:32 +000054
Primiano Tucci24647142018-08-13 21:18:24 +020055#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
56 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
Primiano Tucci15f5e872020-07-27 23:08:05 +020057 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
Primiano Tucci24647142018-08-13 21:18:24 +020058#define PERFETTO_HAS_SIGNAL_H() 1
59#else
60#define PERFETTO_HAS_SIGNAL_H() 0
61#endif
62
Primiano Tucci02c11762019-08-30 00:57:59 +020063#if PERFETTO_BUILDFLAG(PERFETTO_TP_LINENOISE)
Hector Dearmane44ad452018-09-21 11:51:57 +010064#include <linenoise.h>
Hector Dearman36adc822018-10-02 11:35:08 +010065#include <pwd.h>
66#include <sys/types.h>
Primiano Tucci75ae50e2019-08-28 13:09:55 +020067#endif
68
Primiano Tucci24647142018-08-13 21:18:24 +020069#if PERFETTO_HAS_SIGNAL_H()
70#include <signal.h>
71#endif
72
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +010073#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
Primiano Tuccie775ede2020-12-08 17:06:28 +010074#include <io.h>
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +010075#define ftruncate _chsize
76#else
Lalit Magantif9d80302019-06-19 12:48:25 +010077#include <dirent.h>
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +010078#include <getopt.h>
79#endif
80
Primiano Tucciab293f52020-12-08 11:46:52 +010081#if PERFETTO_BUILDFLAG(PERFETTO_TP_LINENOISE) && \
82 !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
83#include <unistd.h> // For getuid() in GetConfigPath().
84#endif
85
Lalit Maganti1ebebf12018-10-15 17:24:04 +010086namespace perfetto {
87namespace trace_processor {
Primiano Tucci5968caf2018-08-06 10:31:46 +010088
89namespace {
Primiano Tucci24647142018-08-13 21:18:24 +020090TraceProcessor* g_tp;
91
Primiano Tucci02c11762019-08-30 00:57:59 +020092#if PERFETTO_BUILDFLAG(PERFETTO_TP_LINENOISE)
Hector Dearmane44ad452018-09-21 11:51:57 +010093
Hector Dearman36adc822018-10-02 11:35:08 +010094bool EnsureDir(const std::string& path) {
Primiano Tuccib730b112020-12-01 14:56:11 +010095 return base::Mkdir(path) || errno == EEXIST;
Hector Dearman36adc822018-10-02 11:35:08 +010096}
97
98bool EnsureFile(const std::string& path) {
Primiano Tuccif675dc22018-10-18 00:17:26 +020099 return base::OpenFile(path, O_RDONLY | O_CREAT, 0644).get() != -1;
Hector Dearman36adc822018-10-02 11:35:08 +0100100}
101
102std::string GetConfigPath() {
103 const char* homedir = getenv("HOME");
Primiano Tucciab293f52020-12-08 11:46:52 +0100104#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
105 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
106 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
Hector Dearman36adc822018-10-02 11:35:08 +0100107 if (homedir == nullptr)
108 homedir = getpwuid(getuid())->pw_dir;
Primiano Tucciab293f52020-12-08 11:46:52 +0100109#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
110 if (homedir == nullptr)
111 homedir = getenv("USERPROFILE");
112#endif
Hector Dearman36adc822018-10-02 11:35:08 +0100113 if (homedir == nullptr)
114 return "";
115 return std::string(homedir) + "/.config";
116}
117
118std::string GetPerfettoPath() {
119 std::string config = GetConfigPath();
120 if (config == "")
121 return "";
122 return config + "/perfetto";
123}
124
125std::string GetHistoryPath() {
126 std::string perfetto = GetPerfettoPath();
127 if (perfetto == "")
128 return "";
129 return perfetto + "/.trace_processor_shell_history";
130}
131
Hector Dearmane44ad452018-09-21 11:51:57 +0100132void SetupLineEditor() {
133 linenoiseSetMultiLine(true);
134 linenoiseHistorySetMaxLen(1000);
Hector Dearman36adc822018-10-02 11:35:08 +0100135
136 bool success = GetHistoryPath() != "";
137 success = success && EnsureDir(GetConfigPath());
138 success = success && EnsureDir(GetPerfettoPath());
139 success = success && EnsureFile(GetHistoryPath());
140 success = success && linenoiseHistoryLoad(GetHistoryPath().c_str()) != -1;
141 if (!success) {
142 PERFETTO_PLOG("Could not load history from %s", GetHistoryPath().c_str());
143 }
Primiano Tucci5968caf2018-08-06 10:31:46 +0100144}
145
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000146struct LineDeleter {
147 void operator()(char* p) const {
148 linenoiseHistoryAdd(p);
149 linenoiseHistorySave(GetHistoryPath().c_str());
150 linenoiseFree(p);
151 }
152};
Hector Dearmane44ad452018-09-21 11:51:57 +0100153
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000154using ScopedLine = std::unique_ptr<char, LineDeleter>;
155
156ScopedLine GetLine(const char* prompt) {
Primiano Tucci0f3872d2020-06-02 22:44:28 +0100157 errno = 0;
158 auto line = ScopedLine(linenoise(prompt));
159 // linenoise returns a nullptr both for CTRL-C and CTRL-D, however in the
160 // former case it sets errno to EAGAIN.
161 // If the user press CTRL-C return "" instead of nullptr. We don't want the
162 // main loop to quit in that case as that is inconsistent with the behavior
163 // "CTRL-C interrupts the current query" and frustrating when hitting that
164 // a split second after the query is done.
165 if (!line && errno == EAGAIN)
166 return ScopedLine(strdup(""));
167 return line;
Hector Dearmane44ad452018-09-21 11:51:57 +0100168}
169
170#else
171
172void SetupLineEditor() {}
173
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000174using ScopedLine = std::unique_ptr<char>;
Hector Dearmane44ad452018-09-21 11:51:57 +0100175
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000176ScopedLine GetLine(const char* prompt) {
Hector Dearmane44ad452018-09-21 11:51:57 +0100177 printf("\r%80s\r%s", "", prompt);
178 fflush(stdout);
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000179 ScopedLine line(new char[1024]);
Lalit Maganti3be20912019-12-18 13:48:45 +0000180 if (!fgets(line.get(), 1024 - 1, stdin))
Hector Dearmane44ad452018-09-21 11:51:57 +0100181 return nullptr;
Lalit Maganti3be20912019-12-18 13:48:45 +0000182 if (strlen(line.get()) > 0)
183 line.get()[strlen(line.get()) - 1] = 0;
Hector Dearmane44ad452018-09-21 11:51:57 +0100184 return line;
185}
186
Primiano Tucci02c11762019-08-30 00:57:59 +0200187#endif // PERFETTO_TP_LINENOISE
Hector Dearmane44ad452018-09-21 11:51:57 +0100188
Lalit Maganti2ae24642020-04-16 13:14:17 +0100189util::Status PrintStats() {
Lalit Maganti49ae9012019-04-03 16:10:39 +0100190 auto it = g_tp->ExecuteQuery(
191 "SELECT name, idx, source, value from stats "
Ioannis Ilkos5e79b8a2019-05-23 18:09:54 +0100192 "where severity IN ('error', 'data_loss') and value > 0");
Lalit Maganti49ae9012019-04-03 16:10:39 +0100193
194 bool first = true;
195 for (uint32_t rows = 0; it.Next(); rows++) {
196 if (first) {
197 fprintf(stderr, "Error stats for this trace:\n");
198
199 for (uint32_t i = 0; i < it.ColumnCount(); i++)
Eric Secklera4f75b72019-12-09 12:08:06 +0000200 fprintf(stderr, "%40s ", it.GetColumnName(i).c_str());
Lalit Maganti49ae9012019-04-03 16:10:39 +0100201 fprintf(stderr, "\n");
202
203 for (uint32_t i = 0; i < it.ColumnCount(); i++)
204 fprintf(stderr, "%40s ", "----------------------------------------");
205 fprintf(stderr, "\n");
206
207 first = false;
208 }
209
210 for (uint32_t c = 0; c < it.ColumnCount(); c++) {
211 auto value = it.Get(c);
212 switch (value.type) {
213 case SqlValue::Type::kNull:
214 fprintf(stderr, "%-40.40s", "[NULL]");
215 break;
216 case SqlValue::Type::kDouble:
217 fprintf(stderr, "%40f", value.double_value);
218 break;
219 case SqlValue::Type::kLong:
220 fprintf(stderr, "%40" PRIi64, value.long_value);
221 break;
222 case SqlValue::Type::kString:
223 fprintf(stderr, "%-40.40s", value.string_value);
224 break;
Lalit Maganti62211072019-05-10 14:09:58 +0100225 case SqlValue::Type::kBytes:
226 printf("%-40.40s", "<raw bytes>");
227 break;
Lalit Maganti49ae9012019-04-03 16:10:39 +0100228 }
229 fprintf(stderr, " ");
230 }
231 fprintf(stderr, "\n");
232 }
233
Lalit Maganti1f067182019-05-09 14:50:05 +0100234 util::Status status = it.Status();
235 if (!status.ok()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100236 return util::ErrStatus("Error while iterating stats (%s)",
237 status.c_message());
Lalit Maganti49ae9012019-04-03 16:10:39 +0100238 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100239 return util::OkStatus();
Lalit Maganti49ae9012019-04-03 16:10:39 +0100240}
241
Lalit Maganti2ae24642020-04-16 13:14:17 +0100242util::Status ExportTraceToDatabase(const std::string& output_name) {
Sami Kyostila33668942018-11-13 16:33:32 +0000243 PERFETTO_CHECK(output_name.find("'") == std::string::npos);
244 {
245 base::ScopedFile fd(base::OpenFile(output_name, O_CREAT | O_RDWR, 0600));
Lalit Maganti2ae24642020-04-16 13:14:17 +0100246 if (!fd)
247 return util::ErrStatus("Failed to create file: %s", output_name.c_str());
Sami Kyostila33668942018-11-13 16:33:32 +0000248 int res = ftruncate(fd.get(), 0);
249 PERFETTO_CHECK(res == 0);
250 }
251
Sami Kyostila33668942018-11-13 16:33:32 +0000252 std::string attach_sql =
253 "ATTACH DATABASE '" + output_name + "' AS perfetto_export";
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100254 auto attach_it = g_tp->ExecuteQuery(attach_sql);
Lalit Magantic72cea22019-04-08 12:29:15 +0100255 bool attach_has_more = attach_it.Next();
256 PERFETTO_DCHECK(!attach_has_more);
Lalit Maganti1f067182019-05-09 14:50:05 +0100257
258 util::Status status = attach_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100259 if (!status.ok())
260 return util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila33668942018-11-13 16:33:32 +0000261
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000262 // Export real and virtual tables.
Lalit Magantic72cea22019-04-08 12:29:15 +0100263 auto tables_it = g_tp->ExecuteQuery(
264 "SELECT name FROM perfetto_tables UNION "
265 "SELECT name FROM sqlite_master WHERE type='table'");
266 for (uint32_t rows = 0; tables_it.Next(); rows++) {
267 std::string table_name = tables_it.Get(0).string_value;
268 PERFETTO_CHECK(table_name.find("'") == std::string::npos);
269 std::string export_sql = "CREATE TABLE perfetto_export." + table_name +
270 " AS SELECT * FROM " + table_name;
271
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100272 auto export_it = g_tp->ExecuteQuery(export_sql);
Lalit Magantic72cea22019-04-08 12:29:15 +0100273 bool export_has_more = export_it.Next();
274 PERFETTO_DCHECK(!export_has_more);
Lalit Maganti1f067182019-05-09 14:50:05 +0100275
276 status = export_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100277 if (!status.ok())
278 return util::ErrStatus("SQLite error: %s", status.c_message());
Lalit Magantic72cea22019-04-08 12:29:15 +0100279 }
Lalit Maganti1f067182019-05-09 14:50:05 +0100280 status = tables_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100281 if (!status.ok())
282 return util::ErrStatus("SQLite error: %s", status.c_message());
Lalit Magantic72cea22019-04-08 12:29:15 +0100283
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000284 // Export views.
285 auto views_it =
286 g_tp->ExecuteQuery("SELECT sql FROM sqlite_master WHERE type='view'");
287 for (uint32_t rows = 0; views_it.Next(); rows++) {
288 std::string sql = views_it.Get(0).string_value;
289 // View statements are of the form "CREATE VIEW name AS stmt". We need to
290 // rewrite name to point to the exported db.
291 const std::string kPrefix = "CREATE VIEW ";
292 PERFETTO_CHECK(sql.find(kPrefix) == 0);
293 sql = sql.substr(0, kPrefix.size()) + "perfetto_export." +
294 sql.substr(kPrefix.size());
295
296 auto export_it = g_tp->ExecuteQuery(sql);
297 bool export_has_more = export_it.Next();
298 PERFETTO_DCHECK(!export_has_more);
299
300 status = export_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100301 if (!status.ok())
302 return util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000303 }
304 status = views_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100305 if (!status.ok())
306 return util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000307
Lalit Magantic72cea22019-04-08 12:29:15 +0100308 auto detach_it = g_tp->ExecuteQuery("DETACH DATABASE perfetto_export");
309 bool detach_has_more = attach_it.Next();
310 PERFETTO_DCHECK(!detach_has_more);
Lalit Maganti1f067182019-05-09 14:50:05 +0100311 status = detach_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100312 return status.ok() ? util::OkStatus()
313 : util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila33668942018-11-13 16:33:32 +0000314}
315
Lalit Magantica4d5142019-05-28 13:25:47 +0100316class ErrorPrinter : public google::protobuf::io::ErrorCollector {
317 void AddError(int line, int col, const std::string& msg) override {
318 PERFETTO_ELOG("%d:%d: %s", line, col, msg.c_str());
319 }
320
321 void AddWarning(int line, int col, const std::string& msg) override {
322 PERFETTO_ILOG("%d:%d: %s", line, col, msg.c_str());
323 }
324};
325
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000326// This function returns an indentifier for a metric suitable for use
327// as an SQL table name (i.e. containing no forward or backward slashes).
328std::string BaseName(std::string metric_path) {
329 std::replace(metric_path.begin(), metric_path.end(), '\\', '/');
330 auto slash_idx = metric_path.rfind('/');
331 return slash_idx == std::string::npos ? metric_path
332 : metric_path.substr(slash_idx + 1);
333}
334
Lalit Magantica4d5142019-05-28 13:25:47 +0100335util::Status RegisterMetric(const std::string& register_metric) {
336 std::string sql;
337 base::ReadFile(register_metric, &sql);
338
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000339 std::string path = "shell/" + BaseName(register_metric);
Lalit Magantica4d5142019-05-28 13:25:47 +0100340
341 return g_tp->RegisterMetric(path, sql);
342}
343
Lalit Maganti812ef672019-05-28 13:28:02 +0100344util::Status ExtendMetricsProto(const std::string& extend_metrics_proto,
345 google::protobuf::DescriptorPool* pool) {
Lalit Magantica4d5142019-05-28 13:25:47 +0100346 google::protobuf::FileDescriptorSet desc_set;
347
348 base::ScopedFile file(base::OpenFile(extend_metrics_proto, O_RDONLY));
Lalit Magantif9d80302019-06-19 12:48:25 +0100349 if (file.get() == -1) {
350 return util::ErrStatus("Failed to open proto file %s",
351 extend_metrics_proto.c_str());
352 }
Lalit Magantica4d5142019-05-28 13:25:47 +0100353
354 google::protobuf::io::FileInputStream stream(file.get());
355 ErrorPrinter printer;
356 google::protobuf::io::Tokenizer tokenizer(&stream, &printer);
357
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500358 auto* file_desc = desc_set.add_file();
Lalit Magantica4d5142019-05-28 13:25:47 +0100359 google::protobuf::compiler::Parser parser;
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500360 parser.Parse(&tokenizer, file_desc);
Lalit Magantica4d5142019-05-28 13:25:47 +0100361
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500362 file_desc->set_name(BaseName(extend_metrics_proto));
363 pool->BuildFile(*file_desc);
Lalit Maganti812ef672019-05-28 13:28:02 +0100364
Lalit Magantica4d5142019-05-28 13:25:47 +0100365 std::vector<uint8_t> metric_proto;
Andres Medinad6a8d3c2020-11-04 17:12:49 -0800366 metric_proto.resize(desc_set.ByteSizeLong());
Lalit Magantica4d5142019-05-28 13:25:47 +0100367 desc_set.SerializeToArray(metric_proto.data(),
368 static_cast<int>(metric_proto.size()));
369
370 return g_tp->ExtendMetricsProto(metric_proto.data(), metric_proto.size());
371}
372
Lalit Maganti25863f72019-08-28 22:14:25 +0100373enum OutputFormat {
374 kBinaryProto,
375 kTextProto,
376 kJson,
Rafal Slawikd28f0302019-10-22 17:00:04 +0100377 kNone,
Lalit Maganti25863f72019-08-28 22:14:25 +0100378};
379
Lalit Maganti2ae24642020-04-16 13:14:17 +0100380util::Status RunMetrics(const std::vector<std::string>& metric_names,
381 OutputFormat format,
382 const google::protobuf::DescriptorPool& pool) {
Lalit Magantid9f86b62019-04-08 11:11:51 +0100383 std::vector<uint8_t> metric_result;
Lalit Magantid71a9452019-05-09 15:13:24 +0100384 util::Status status = g_tp->ComputeMetric(metric_names, &metric_result);
385 if (!status.ok()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100386 return util::ErrStatus("Error when computing metrics: %s",
387 status.c_message());
Lalit Maganti7c959782019-04-02 16:54:12 +0100388 }
Rafal Slawikd28f0302019-10-22 17:00:04 +0100389 if (format == OutputFormat::kNone) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100390 return util::OkStatus();
Rafal Slawikd28f0302019-10-22 17:00:04 +0100391 }
Lalit Maganti25863f72019-08-28 22:14:25 +0100392 if (format == OutputFormat::kBinaryProto) {
Lalit Maganti812ef672019-05-28 13:28:02 +0100393 fwrite(metric_result.data(), sizeof(uint8_t), metric_result.size(), stdout);
Lalit Maganti2ae24642020-04-16 13:14:17 +0100394 return util::OkStatus();
Lalit Maganti25863f72019-08-28 22:14:25 +0100395 }
396
397 google::protobuf::DynamicMessageFactory factory(&pool);
398 auto* descriptor = pool.FindMessageTypeByName("perfetto.protos.TraceMetrics");
399 std::unique_ptr<google::protobuf::Message> metrics(
400 factory.GetPrototype(descriptor)->New());
401 metrics->ParseFromArray(metric_result.data(),
402 static_cast<int>(metric_result.size()));
403
404 switch (format) {
405 case OutputFormat::kTextProto: {
406 std::string out;
407 google::protobuf::TextFormat::PrintToString(*metrics, &out);
408 fwrite(out.c_str(), sizeof(char), out.size(), stdout);
409 break;
410 }
411 case OutputFormat::kJson: {
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500412 // We need to instantiate field options from dynamic message factory
413 // because otherwise it cannot parse our custom extensions.
414 const google::protobuf::Message* field_options_prototype =
415 factory.GetPrototype(
416 pool.FindMessageTypeByName("google.protobuf.FieldOptions"));
417 auto out = proto_to_json::MessageToJsonWithAnnotations(
418 *metrics, field_options_prototype, 0);
Lalit Maganti25863f72019-08-28 22:14:25 +0100419 fwrite(out.c_str(), sizeof(char), out.size(), stdout);
420 break;
421 }
422 case OutputFormat::kBinaryProto:
Rafal Slawikd28f0302019-10-22 17:00:04 +0100423 case OutputFormat::kNone:
Lalit Maganti25863f72019-08-28 22:14:25 +0100424 PERFETTO_FATAL("Unsupported output format.");
Lalit Maganti812ef672019-05-28 13:28:02 +0100425 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100426 return util::OkStatus();
Lalit Maganti7c959782019-04-02 16:54:12 +0100427}
428
Primiano Tucci4e01f632020-06-11 17:03:05 +0100429void PrintQueryResultInteractively(Iterator* it,
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100430 base::TimeNanos t_start,
431 uint32_t column_width) {
Lalit Magantic72cea22019-04-08 12:29:15 +0100432 base::TimeNanos t_end = t_start;
433 for (uint32_t rows = 0; it->Next(); rows++) {
434 if (rows % 32 == 0) {
435 if (rows > 0) {
Primiano Tucci5968caf2018-08-06 10:31:46 +0100436 fprintf(stderr, "...\nType 'q' to stop, Enter for more records: ");
437 fflush(stderr);
438 char input[32];
439 if (!fgets(input, sizeof(input) - 1, stdin))
440 exit(0);
441 if (input[0] == 'q')
442 break;
Lalit Magantic72cea22019-04-08 12:29:15 +0100443 } else {
Lalit Magantiaac2f652019-04-30 12:16:21 +0100444 t_end = base::GetWallTimeNs();
Primiano Tucci5968caf2018-08-06 10:31:46 +0100445 }
Lalit Magantic72cea22019-04-08 12:29:15 +0100446 for (uint32_t i = 0; i < it->ColumnCount(); i++)
Lalit Magantid74f36a2019-07-12 16:35:57 +0100447 printf("%-*.*s ", column_width, column_width,
Eric Secklera4f75b72019-12-09 12:08:06 +0000448 it->GetColumnName(i).c_str());
Primiano Tucci5968caf2018-08-06 10:31:46 +0100449 printf("\n");
450
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100451 std::string divider(column_width, '-');
452 for (uint32_t i = 0; i < it->ColumnCount(); i++) {
453 printf("%-*s ", column_width, divider.c_str());
454 }
Primiano Tucci5968caf2018-08-06 10:31:46 +0100455 printf("\n");
456 }
457
Lalit Magantic72cea22019-04-08 12:29:15 +0100458 for (uint32_t c = 0; c < it->ColumnCount(); c++) {
459 auto value = it->Get(c);
460 switch (value.type) {
461 case SqlValue::Type::kNull:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100462 printf("%-*s", column_width, "[NULL]");
Lalit Magantic72cea22019-04-08 12:29:15 +0100463 break;
464 case SqlValue::Type::kDouble:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100465 printf("%*f", column_width, value.double_value);
Lalit Magantic72cea22019-04-08 12:29:15 +0100466 break;
467 case SqlValue::Type::kLong:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100468 printf("%*" PRIi64, column_width, value.long_value);
Lalit Magantic72cea22019-04-08 12:29:15 +0100469 break;
470 case SqlValue::Type::kString:
Lalit Magantid74f36a2019-07-12 16:35:57 +0100471 printf("%-*.*s", column_width, column_width, value.string_value);
Lalit Magantic72cea22019-04-08 12:29:15 +0100472 break;
Lalit Maganti62211072019-05-10 14:09:58 +0100473 case SqlValue::Type::kBytes:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100474 printf("%-*s", column_width, "<raw bytes>");
Lalit Maganti62211072019-05-10 14:09:58 +0100475 break;
Lalit Maganti21160e82018-10-16 09:40:29 +0100476 }
477 printf(" ");
478 }
479 printf("\n");
480 }
Lalit Magantic72cea22019-04-08 12:29:15 +0100481
Lalit Maganti1f067182019-05-09 14:50:05 +0100482 util::Status status = it->Status();
483 if (!status.ok()) {
484 PERFETTO_ELOG("SQLite error: %s", status.c_message());
Lalit Magantic72cea22019-04-08 12:29:15 +0100485 }
Florian Mayer39e40d42020-07-16 14:52:07 +0200486 printf("\nQuery executed in %.3f ms\n\n",
487 static_cast<double>((t_end - t_start).count()) / 1E6);
Lalit Maganti21160e82018-10-16 09:40:29 +0100488}
Sami Kyostila33668942018-11-13 16:33:32 +0000489
Primiano Tucci4e01f632020-06-11 17:03:05 +0100490util::Status PrintQueryResultAsCsv(Iterator* it, FILE* output) {
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100491 for (uint32_t c = 0; c < it->ColumnCount(); c++) {
492 if (c > 0)
493 fprintf(output, ",");
Eric Secklera4f75b72019-12-09 12:08:06 +0000494 fprintf(output, "\"%s\"", it->GetColumnName(c).c_str());
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100495 }
496 fprintf(output, "\n");
Lalit Maganti21160e82018-10-16 09:40:29 +0100497
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100498 for (uint32_t rows = 0; it->Next(); rows++) {
Lalit Magantic72cea22019-04-08 12:29:15 +0100499 for (uint32_t c = 0; c < it->ColumnCount(); c++) {
Lalit Maganti21160e82018-10-16 09:40:29 +0100500 if (c > 0)
501 fprintf(output, ",");
Lalit Magantib55c8842018-12-13 14:26:08 +0000502
Lalit Magantic72cea22019-04-08 12:29:15 +0100503 auto value = it->Get(c);
504 switch (value.type) {
505 case SqlValue::Type::kNull:
506 fprintf(output, "\"%s\"", "[NULL]");
507 break;
508 case SqlValue::Type::kDouble:
509 fprintf(output, "%f", value.double_value);
510 break;
511 case SqlValue::Type::kLong:
512 fprintf(output, "%" PRIi64, value.long_value);
513 break;
514 case SqlValue::Type::kString:
515 fprintf(output, "\"%s\"", value.string_value);
516 break;
Lalit Maganti62211072019-05-10 14:09:58 +0100517 case SqlValue::Type::kBytes:
518 fprintf(output, "\"%s\"", "<raw bytes>");
519 break;
Primiano Tucci5968caf2018-08-06 10:31:46 +0100520 }
521 }
Lalit Magantib55c8842018-12-13 14:26:08 +0000522 fprintf(output, "\n");
Primiano Tucci5968caf2018-08-06 10:31:46 +0100523 }
Mikhail Khokhlov7a3a8652019-07-08 13:56:39 +0100524 return it->Status();
Lalit Maganti21160e82018-10-16 09:40:29 +0100525}
526
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000527bool IsBlankLine(const std::string& buffer) {
528 return buffer == "\n" || buffer == "\r\n";
529}
530
531bool IsCommentLine(const std::string& buffer) {
532 return base::StartsWith(buffer, "--");
533}
534
535bool HasEndOfQueryDelimiter(const std::string& buffer) {
536 return base::EndsWith(buffer, ";\n") || base::EndsWith(buffer, ";") ||
537 base::EndsWith(buffer, ";\r\n");
Florian Mayer3c742432019-05-21 11:35:47 +0100538}
539
Lalit Maganti2ae24642020-04-16 13:14:17 +0100540util::Status LoadQueries(FILE* input, std::vector<std::string>* output) {
Lalit Maganti21160e82018-10-16 09:40:29 +0100541 char buffer[4096];
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000542 while (!feof(input) && !ferror(input)) {
Lalit Maganti21160e82018-10-16 09:40:29 +0100543 std::string sql_query;
544 while (fgets(buffer, sizeof(buffer), input)) {
Lalit Maganti9ae35302020-08-12 16:09:41 +0100545 std::string line = base::TrimLeading(buffer);
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000546 if (IsBlankLine(line))
Lalit Maganti21160e82018-10-16 09:40:29 +0100547 break;
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000548
549 if (IsCommentLine(line))
550 continue;
551
552 sql_query.append(line);
553
554 if (HasEndOfQueryDelimiter(line))
555 break;
Lalit Maganti21160e82018-10-16 09:40:29 +0100556 }
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000557 if (!sql_query.empty() && sql_query.back() == '\n')
Lalit Maganti21160e82018-10-16 09:40:29 +0100558 sql_query.resize(sql_query.size() - 1);
Lalit Maganticbccb0a2018-12-04 20:14:42 +0000559
560 // If we have a new line at the end of the file or an extra new line
561 // somewhere in the file, we'll end up with an empty query which we should
562 // just ignore.
563 if (sql_query.empty())
564 continue;
565
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000566 output->push_back(sql_query);
567 }
568 if (ferror(input)) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100569 return util::ErrStatus("Error reading query file");
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000570 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100571 return util::OkStatus();
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000572}
573
Lalit Maganti62062832020-07-16 19:34:08 +0100574util::Status RunQueriesWithoutOutput(const std::vector<std::string>& queries) {
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100575 for (const auto& sql_query : queries) {
576 PERFETTO_DLOG("Executing query: %s", sql_query.c_str());
577
578 auto it = g_tp->ExecuteQuery(sql_query);
Lalit Maganti62062832020-07-16 19:34:08 +0100579 RETURN_IF_ERROR(it.Status());
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100580 if (it.Next()) {
581 return util::ErrStatus("Unexpected result from a query.");
582 }
583 }
584 return util::OkStatus();
585}
586
Lalit Maganti62062832020-07-16 19:34:08 +0100587util::Status RunQueriesAndPrintResult(const std::vector<std::string>& queries,
588 FILE* output) {
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000589 bool is_first_query = true;
Ioannis Ilkos433c8e52019-02-11 12:52:35 +0000590 bool has_output = false;
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000591 for (const auto& sql_query : queries) {
592 // Add an extra newline separator between query results.
593 if (!is_first_query)
594 fprintf(output, "\n");
595 is_first_query = false;
596
Lalit Maganti21160e82018-10-16 09:40:29 +0100597 PERFETTO_ILOG("Executing query: %s", sql_query.c_str());
598
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100599 auto it = g_tp->ExecuteQuery(sql_query);
Lalit Maganti62062832020-07-16 19:34:08 +0100600 RETURN_IF_ERROR(it.Status());
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100601 if (it.ColumnCount() == 0) {
602 bool it_has_more = it.Next();
603 PERFETTO_DCHECK(!it_has_more);
604 continue;
605 }
606
Lalit Maganti0b810072020-07-08 12:00:45 +0100607 // If we have a single column with the name |suppress_query_output| that's
608 // a hint to shell that it should not treat the query as having real
609 // meaning.
610 if (it.ColumnCount() == 1 &&
611 it.GetColumnName(0) == "suppress_query_output") {
612 // We should only see a single null value as this feature is usually used
613 // as SELECT RUN_METRIC(<metric file>) as suppress_query_output and
614 // RUN_METRIC returns a single null.
615 bool has_next = it.Next();
Lalit Maganti62062832020-07-16 19:34:08 +0100616 RETURN_IF_ERROR(it.Status());
Lalit Maganti0b810072020-07-08 12:00:45 +0100617 PERFETTO_DCHECK(has_next);
618 PERFETTO_DCHECK(it.Get(0).is_null());
619
620 has_next = it.Next();
Lalit Maganti62062832020-07-16 19:34:08 +0100621 RETURN_IF_ERROR(it.Status());
Lalit Maganti0b810072020-07-08 12:00:45 +0100622 PERFETTO_DCHECK(!has_next);
Lalit Maganti0b810072020-07-08 12:00:45 +0100623 continue;
624 }
625
Hector Dearman2af21922019-09-03 13:48:38 +0100626 if (has_output) {
Lalit Maganti0b810072020-07-08 12:00:45 +0100627 return util::ErrStatus(
628 "More than one query generated result rows. This is unsupported.");
Hector Dearman2af21922019-09-03 13:48:38 +0100629 }
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100630 has_output = true;
Lalit Maganti62062832020-07-16 19:34:08 +0100631 RETURN_IF_ERROR(PrintQueryResultAsCsv(&it, output));
Lalit Maganti21160e82018-10-16 09:40:29 +0100632 }
Lalit Maganti0b810072020-07-08 12:00:45 +0100633 return util::OkStatus();
Lalit Maganti21160e82018-10-16 09:40:29 +0100634}
635
Lalit Maganti2ae24642020-04-16 13:14:17 +0100636util::Status PrintPerfFile(const std::string& perf_file_path,
637 base::TimeNanos t_load,
638 base::TimeNanos t_run) {
Lalit Maganti260e04d2019-05-03 13:17:01 +0100639 char buf[128];
640 int count = snprintf(buf, sizeof(buf), "%" PRId64 ",%" PRId64,
641 static_cast<int64_t>(t_load.count()),
642 static_cast<int64_t>(t_run.count()));
643 if (count < 0) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100644 return util::ErrStatus("Failed to write perf data");
Lalit Maganti260e04d2019-05-03 13:17:01 +0100645 }
646
Lalit Maganti04a450a2019-07-03 16:04:19 +0100647 auto fd(base::OpenFile(perf_file_path, O_WRONLY | O_CREAT | O_TRUNC, 0666));
Lalit Maganti260e04d2019-05-03 13:17:01 +0100648 if (!fd) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100649 return util::ErrStatus("Failed to open perf file");
Lalit Maganti260e04d2019-05-03 13:17:01 +0100650 }
651 base::WriteAll(fd.get(), buf, static_cast<size_t>(count));
Lalit Maganti2ae24642020-04-16 13:14:17 +0100652 return util::OkStatus();
Lalit Maganti260e04d2019-05-03 13:17:01 +0100653}
654
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100655struct CommandLineOptions {
656 std::string perf_file_path;
657 std::string query_file_path;
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100658 std::string pre_metrics_path;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100659 std::string sqlite_file_path;
660 std::string metric_names;
661 std::string metric_output;
662 std::string trace_file_path;
Anindita Ghoshff779472020-08-25 15:28:25 +0000663 std::string port_number;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100664 bool launch_shell = false;
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100665 bool enable_httpd = false;
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100666 bool wide = false;
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100667 bool force_full_sort = false;
Lalit Maganti427b8332020-05-27 16:09:45 +0100668 std::string metatrace_path;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100669};
670
Lalit Magantiedace412019-06-18 13:28:28 +0100671#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
672void PrintUsage(char** argv) {
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000673 PERFETTO_ELOG(R"(
674Interactive trace processor shell.
675Usage: %s [OPTIONS] trace_file.pb
676
677Options:
678 -q, --query-file FILE Read and execute an SQL query from a file.
679 If used with --run-metrics, the query is
680 executed after the selected metrics and
681 the metrics output is suppressed.
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100682 --pre-metrics FILE Read and execute an SQL query from a file.
683 This query is executed before the selected
684 metrics and can't output any results.
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000685 --run-metrics x,y,z Runs a comma separated list of metrics and
686 prints the result as a TraceMetrics proto
687 to stdout. The specified can either be
688 in-built metrics or SQL/proto files of
689 extension metrics.
690 --metrics-output [binary|text|json] Allows the output of --run-metrics to be
691 specified in either proto binary, proto
692 text format or JSON format (default: proto
693 text).)",
694 argv[0]);
Lalit Magantiedace412019-06-18 13:28:28 +0100695}
696
697CommandLineOptions ParseCommandLineOptions(int argc, char** argv) {
698 CommandLineOptions command_line_options;
699
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000700 if (argc < 2 || argc % 2 == 1) {
Lalit Magantiedace412019-06-18 13:28:28 +0100701 PrintUsage(argv);
702 exit(1);
703 }
704
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000705 for (int i = 1; i < argc - 1; i += 2) {
706 if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--query-file") == 0) {
707 command_line_options.query_file_path = argv[i + 1];
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100708 } else if (strcmp(argv[i], "--pre-metrics") == 0) {
709 command_line_options.pre_metrics_path = argv[i + 1];
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000710 } else if (strcmp(argv[i], "--run-metrics") == 0) {
711 command_line_options.metric_names = argv[i + 1];
712 } else if (strcmp(argv[i], "--metrics-output") == 0) {
713 command_line_options.metric_output = argv[i + 1];
714 } else {
715 PrintUsage(argv);
716 exit(1);
717 }
718 }
719 command_line_options.trace_file_path = argv[argc - 1];
720 command_line_options.launch_shell =
721 command_line_options.metric_names.empty() &&
722 command_line_options.query_file_path.empty();
Lalit Magantiedace412019-06-18 13:28:28 +0100723 return command_line_options;
724}
725
726#else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
Lalit Magantif9d80302019-06-19 12:48:25 +0100727
Lalit Magantiedace412019-06-18 13:28:28 +0100728void PrintUsage(char** argv) {
729 PERFETTO_ELOG(R"(
730Interactive trace processor shell.
731Usage: %s [OPTIONS] trace_file.pb
732
733Options:
Lalit Maganti82adf6a2019-09-26 18:05:51 +0100734 -h, --help Prints this guide.
735 -v, --version Prints the version of trace processor.
736 -d, --debug Enable virtual table debugging.
737 -W, --wide Prints interactive output with double
738 column width.
739 -p, --perf-file FILE Writes the time taken to ingest the trace
740 and execute the queries to the given file.
741 Only valid with -q or --run-metrics and
742 the file will only be written if the
743 execution is successful.
744 -q, --query-file FILE Read and execute an SQL query from a file.
Rafal Slawikd28f0302019-10-22 17:00:04 +0100745 If used with --run-metrics, the query is
746 executed after the selected metrics and
747 the metrics output is suppressed.
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100748 --pre-metrics FILE Read and execute an SQL query from a file.
749 This query is executed before the selected
750 metrics and can't output any results.
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100751 -D, --httpd Enables the HTTP RPC server.
Anindita Ghoshff779472020-08-25 15:28:25 +0000752 --http-port PORT Specify what port to run HTTP RPC server.
Lalit Maganti82adf6a2019-09-26 18:05:51 +0100753 -i, --interactive Starts interactive mode even after a query
754 file is specified with -q or
755 --run-metrics.
Lalit Maganti2ae24642020-04-16 13:14:17 +0100756 -e, --export FILE Export the contents of trace processor
757 into an SQLite database after running any
758 metrics or queries specified.
Lalit Maganti82adf6a2019-09-26 18:05:51 +0100759 --run-metrics x,y,z Runs a comma separated list of metrics and
760 prints the result as a TraceMetrics proto
761 to stdout. The specified can either be
762 in-built metrics or SQL/proto files of
763 extension metrics.
764 --metrics-output=[binary|text|json] Allows the output of --run-metrics to be
765 specified in either proto binary, proto
766 text format or JSON format (default: proto
767 text).
Lalit Maganti427b8332020-05-27 16:09:45 +0100768 -m, --metatrace FILE Enables metatracing of trace processor
769 writing the resulting trace into FILE.
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100770 --full-sort Forces the trace processor into performing
771 a full sort ignoring any windowing
772 logic.)",
Lalit Magantiedace412019-06-18 13:28:28 +0100773 argv[0]);
774}
Lalit Maganti260e04d2019-05-03 13:17:01 +0100775
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100776CommandLineOptions ParseCommandLineOptions(int argc, char** argv) {
777 CommandLineOptions command_line_options;
778 enum LongOption {
779 OPT_RUN_METRICS = 1000,
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100780 OPT_PRE_METRICS,
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100781 OPT_METRICS_OUTPUT,
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100782 OPT_FORCE_FULL_SORT,
Anindita Ghoshff779472020-08-25 15:28:25 +0000783 OPT_HTTP_PORT,
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100784 };
785
Primiano Tucci42433ab2020-11-30 18:42:01 +0100786 static const option long_options[] = {
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100787 {"help", no_argument, nullptr, 'h'},
788 {"version", no_argument, nullptr, 'v'},
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100789 {"wide", no_argument, nullptr, 'W'},
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100790 {"httpd", no_argument, nullptr, 'D'},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100791 {"interactive", no_argument, nullptr, 'i'},
792 {"debug", no_argument, nullptr, 'd'},
793 {"perf-file", required_argument, nullptr, 'p'},
794 {"query-file", required_argument, nullptr, 'q'},
795 {"export", required_argument, nullptr, 'e'},
Lalit Maganti427b8332020-05-27 16:09:45 +0100796 {"metatrace", required_argument, nullptr, 'm'},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100797 {"run-metrics", required_argument, nullptr, OPT_RUN_METRICS},
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100798 {"pre-metrics", required_argument, nullptr, OPT_PRE_METRICS},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100799 {"metrics-output", required_argument, nullptr, OPT_METRICS_OUTPUT},
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100800 {"full-sort", no_argument, nullptr, OPT_FORCE_FULL_SORT},
Anindita Ghoshff779472020-08-25 15:28:25 +0000801 {"http-port", required_argument, nullptr, OPT_HTTP_PORT},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100802 {nullptr, 0, nullptr, 0}};
803
804 bool explicit_interactive = false;
805 int option_index = 0;
806 for (;;) {
807 int option =
Lalit Maganti427b8332020-05-27 16:09:45 +0100808 getopt_long(argc, argv, "hvWiDdm:p:q:e:", long_options, &option_index);
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100809
810 if (option == -1)
811 break; // EOF.
812
813 if (option == 'v') {
Primiano Tucciec590132020-11-16 14:16:44 +0100814 printf("%s\n", base::GetVersionString());
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100815 exit(0);
816 }
817
818 if (option == 'i') {
819 explicit_interactive = true;
820 continue;
821 }
822
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100823 if (option == 'D') {
824#if PERFETTO_BUILDFLAG(PERFETTO_TP_HTTPD)
825 command_line_options.enable_httpd = true;
826#else
827 PERFETTO_FATAL("HTTP RPC module not supported in this build");
828#endif
829 continue;
830 }
831
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100832 if (option == 'W') {
833 command_line_options.wide = true;
834 continue;
835 }
836
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100837 if (option == 'd') {
838 EnableSQLiteVtableDebugging();
839 continue;
840 }
841
842 if (option == 'p') {
843 command_line_options.perf_file_path = optarg;
844 continue;
845 }
846
847 if (option == 'q') {
848 command_line_options.query_file_path = optarg;
849 continue;
850 }
851
852 if (option == 'e') {
853 command_line_options.sqlite_file_path = optarg;
854 continue;
855 }
856
Lalit Maganti427b8332020-05-27 16:09:45 +0100857 if (option == 'm') {
858 command_line_options.metatrace_path = optarg;
859 continue;
860 }
861
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100862 if (option == OPT_PRE_METRICS) {
863 command_line_options.pre_metrics_path = optarg;
864 continue;
865 }
866
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100867 if (option == OPT_RUN_METRICS) {
868 command_line_options.metric_names = optarg;
869 continue;
870 }
871
872 if (option == OPT_METRICS_OUTPUT) {
873 command_line_options.metric_output = optarg;
874 continue;
875 }
876
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100877 if (option == OPT_FORCE_FULL_SORT) {
878 command_line_options.force_full_sort = true;
879 continue;
880 }
881
Anindita Ghoshff779472020-08-25 15:28:25 +0000882 if (option == OPT_HTTP_PORT) {
883 command_line_options.port_number = optarg;
884 continue;
885 }
886
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100887 PrintUsage(argv);
888 exit(option == 'h' ? 0 : 1);
889 }
890
891 command_line_options.launch_shell =
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100892 explicit_interactive || (command_line_options.pre_metrics_path.empty() &&
893 command_line_options.metric_names.empty() &&
Lalit Maganti2ae24642020-04-16 13:14:17 +0100894 command_line_options.query_file_path.empty() &&
895 command_line_options.sqlite_file_path.empty());
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100896
897 // Only allow non-interactive queries to emit perf data.
898 if (!command_line_options.perf_file_path.empty() &&
899 command_line_options.launch_shell) {
900 PrintUsage(argv);
901 exit(1);
902 }
903
Primiano Tucciee2ce1d2019-11-01 19:14:17 +0100904 // The only case where we allow omitting the trace file path is when running
905 // in --http mode. In all other cases, the last argument must be the trace
906 // file.
907 if (optind == argc - 1 && argv[optind]) {
908 command_line_options.trace_file_path = argv[optind];
909 } else if (!command_line_options.enable_httpd) {
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100910 PrintUsage(argv);
911 exit(1);
912 }
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100913 return command_line_options;
914}
Lalit Magantif9d80302019-06-19 12:48:25 +0100915
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100916#endif // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
917
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500918void ExtendPoolWithBinaryDescriptor(google::protobuf::DescriptorPool& pool,
919 const void* data,
920 int size) {
921 google::protobuf::FileDescriptorSet desc_set;
922 desc_set.ParseFromArray(data, size);
923 for (const auto& desc : desc_set.file()) {
924 pool.BuildFile(desc);
925 }
926}
927
Lalit Maganti2ae24642020-04-16 13:14:17 +0100928util::Status LoadTrace(const std::string& trace_file_path, double* size_mb) {
929 util::Status read_status =
930 ReadTrace(g_tp, trace_file_path.c_str(), [&size_mb](size_t parsed_size) {
Florian Mayer39e40d42020-07-16 14:52:07 +0200931 *size_mb = static_cast<double>(parsed_size) / 1E6;
Lalit Maganti2ae24642020-04-16 13:14:17 +0100932 fprintf(stderr, "\rLoading trace: %.2f MB\r", *size_mb);
933 });
934 if (!read_status.ok()) {
935 return util::ErrStatus("Could not read trace file (path: %s): %s",
936 trace_file_path.c_str(), read_status.c_message());
937 }
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100938
Florian Mayer6d1f0ae2020-07-21 08:59:29 +0100939 std::unique_ptr<profiling::Symbolizer> symbolizer =
940 profiling::LocalSymbolizerOrDie(profiling::GetPerfettoBinaryPath(),
941 getenv("PERFETTO_SYMBOLIZER_MODE"));
Lalit Magantie8cd8a32020-02-27 16:54:46 +0000942
Lalit Maganti2ae24642020-04-16 13:14:17 +0100943 if (symbolizer) {
944 profiling::SymbolizeDatabase(
945 g_tp, symbolizer.get(), [](const std::string& trace_proto) {
946 std::unique_ptr<uint8_t[]> buf(new uint8_t[trace_proto.size()]);
947 memcpy(buf.get(), trace_proto.data(), trace_proto.size());
948 auto status = g_tp->Parse(std::move(buf), trace_proto.size());
949 if (!status.ok()) {
950 PERFETTO_DFATAL_OR_ELOG("Failed to parse: %s",
951 status.message().c_str());
952 return;
953 }
954 });
955 g_tp->NotifyEndOfFile();
Primiano Tucciee2ce1d2019-11-01 19:14:17 +0100956 }
Florian Mayerf4255a42020-12-14 19:12:34 +0000957
958 auto maybe_map = profiling::GetPerfettoProguardMapPath();
959 if (!maybe_map.empty()) {
960 profiling::ReadProguardMapsToDeobfuscationPackets(
961 maybe_map, [](const std::string& trace_proto) {
962 std::unique_ptr<uint8_t[]> buf(new uint8_t[trace_proto.size()]);
963 memcpy(buf.get(), trace_proto.data(), trace_proto.size());
964 auto status = g_tp->Parse(std::move(buf), trace_proto.size());
965 if (!status.ok()) {
966 PERFETTO_DFATAL_OR_ELOG("Failed to parse: %s",
967 status.message().c_str());
968 return;
969 }
970 });
971 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100972 return util::OkStatus();
973}
Primiano Tucciee2ce1d2019-11-01 19:14:17 +0100974
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100975util::Status RunQueries(const std::string& query_file_path,
976 bool expect_output) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100977 std::vector<std::string> queries;
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100978 base::ScopedFstream file(fopen(query_file_path.c_str(), "r"));
Lalit Maganti2ae24642020-04-16 13:14:17 +0100979 if (!file) {
980 return util::ErrStatus("Could not open query file (path: %s)",
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100981 query_file_path.c_str());
Lalit Maganti2ae24642020-04-16 13:14:17 +0100982 }
983 RETURN_IF_ERROR(LoadQueries(file.get(), &queries));
Lalit Maganti62062832020-07-16 19:34:08 +0100984
985 util::Status status;
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100986 if (expect_output) {
Lalit Maganti62062832020-07-16 19:34:08 +0100987 status = RunQueriesAndPrintResult(queries, stdout);
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100988 } else {
Lalit Maganti62062832020-07-16 19:34:08 +0100989 status = RunQueriesWithoutOutput(queries);
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100990 }
Lalit Maganti62062832020-07-16 19:34:08 +0100991 if (!status.ok()) {
992 return util::ErrStatus("Encountered error while running queries: %s",
993 status.c_message());
994 }
995 return util::OkStatus();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100996}
Primiano Tucci5968caf2018-08-06 10:31:46 +0100997
Lalit Maganti2ae24642020-04-16 13:14:17 +0100998util::Status RunMetrics(const CommandLineOptions& options) {
Lalit Maganti812ef672019-05-28 13:28:02 +0100999 // Descriptor pool used for printing output as textproto.
Deepanjan Royab8c05d2020-01-21 09:55:26 -05001000 // Building on top of generated pool so default protos in
1001 // google.protobuf.descriptor.proto are available.
1002 google::protobuf::DescriptorPool pool(
1003 google::protobuf::DescriptorPool::generated_pool());
1004 ExtendPoolWithBinaryDescriptor(pool, kMetricsDescriptor.data(),
1005 kMetricsDescriptor.size());
Deepanjan Royf4da5092020-07-15 17:59:04 -04001006 ExtendPoolWithBinaryDescriptor(pool, kAllChromeMetricsDescriptor.data(),
1007 kAllChromeMetricsDescriptor.size());
Lalit Maganti812ef672019-05-28 13:28:02 +01001008
Lalit Maganti2ae24642020-04-16 13:14:17 +01001009 std::vector<std::string> metrics;
1010 for (base::StringSplitter ss(options.metric_names, ','); ss.Next();) {
1011 metrics.emplace_back(ss.cur_token());
Rafal Slawikd28f0302019-10-22 17:00:04 +01001012 }
Lalit Maganti7c959782019-04-02 16:54:12 +01001013
Lalit Maganti2ae24642020-04-16 13:14:17 +01001014 // For all metrics which are files, register them and extend the metrics
1015 // proto.
1016 for (size_t i = 0; i < metrics.size(); ++i) {
1017 const std::string& metric_or_path = metrics[i];
1018
1019 // If there is no extension, we assume it is a builtin metric.
1020 auto ext_idx = metric_or_path.rfind(".");
1021 if (ext_idx == std::string::npos)
1022 continue;
1023
1024 std::string no_ext_name = metric_or_path.substr(0, ext_idx);
Deepanjan Roy05d99132020-09-10 11:33:41 -04001025
1026 // The proto must be extended before registering the metric.
1027 util::Status status = ExtendMetricsProto(no_ext_name + ".proto", &pool);
Lalit Maganti2ae24642020-04-16 13:14:17 +01001028 if (!status.ok()) {
Deepanjan Roy05d99132020-09-10 11:33:41 -04001029 return util::ErrStatus("Unable to extend metrics proto %s: %s",
Lalit Maganti2ae24642020-04-16 13:14:17 +01001030 metric_or_path.c_str(), status.c_message());
1031 }
1032
Deepanjan Roy05d99132020-09-10 11:33:41 -04001033 status = RegisterMetric(no_ext_name + ".sql");
Lalit Maganti2ae24642020-04-16 13:14:17 +01001034 if (!status.ok()) {
Deepanjan Roy05d99132020-09-10 11:33:41 -04001035 return util::ErrStatus("Unable to register metric %s: %s",
Lalit Maganti2ae24642020-04-16 13:14:17 +01001036 metric_or_path.c_str(), status.c_message());
1037 }
1038
1039 metrics[i] = BaseName(no_ext_name);
1040 }
1041
1042 OutputFormat format;
Rafal Slawikd28f0302019-10-22 17:00:04 +01001043 if (!options.query_file_path.empty()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +01001044 format = OutputFormat::kNone;
1045 } else if (options.metric_output == "binary") {
1046 format = OutputFormat::kBinaryProto;
1047 } else if (options.metric_output == "json") {
1048 format = OutputFormat::kJson;
1049 } else {
1050 format = OutputFormat::kTextProto;
1051 }
1052 return RunMetrics(std::move(metrics), format, pool);
1053}
1054
Dan Elphick2b4c8ae2020-11-03 17:59:19 +00001055void PrintShellUsage() {
1056 PERFETTO_ELOG(
1057 "Available commands:\n"
1058 ".quit, .q Exit the shell.\n"
1059 ".help This text.\n"
1060 ".dump FILE Export the trace as a sqlite database.\n"
1061 ".read FILE Executes the queries in the FILE.\n"
1062 ".reset Destroys all tables/view created by the user.\n");
1063}
1064
1065util::Status StartInteractiveShell(uint32_t column_width) {
1066 SetupLineEditor();
1067
1068 for (;;) {
1069 ScopedLine line = GetLine("> ");
1070 if (!line)
1071 break;
1072 if (strcmp(line.get(), "") == 0) {
1073 printf("If you want to quit either type .q or press CTRL-D (EOF)\n");
1074 continue;
1075 }
1076 if (line.get()[0] == '.') {
1077 char command[32] = {};
1078 char arg[1024] = {};
1079 sscanf(line.get() + 1, "%31s %1023s", command, arg);
1080 if (strcmp(command, "quit") == 0 || strcmp(command, "q") == 0) {
1081 break;
1082 } else if (strcmp(command, "help") == 0) {
1083 PrintShellUsage();
1084 } else if (strcmp(command, "dump") == 0 && strlen(arg)) {
1085 if (!ExportTraceToDatabase(arg).ok())
1086 PERFETTO_ELOG("Database export failed");
1087 } else if (strcmp(command, "reset") == 0) {
1088 g_tp->RestoreInitialTables();
1089 } else if (strcmp(command, "read") == 0 && strlen(arg)) {
1090 util::Status status = RunQueries(arg, true);
1091 if (!status.ok()) {
1092 PERFETTO_ELOG("%s", status.c_message());
1093 }
1094 } else {
1095 PrintShellUsage();
1096 }
1097 continue;
1098 }
1099
1100 base::TimeNanos t_start = base::GetWallTimeNs();
1101 auto it = g_tp->ExecuteQuery(line.get());
1102 PrintQueryResultInteractively(&it, t_start, column_width);
1103 }
1104 return util::OkStatus();
1105}
1106
Lalit Maganti2ae24642020-04-16 13:14:17 +01001107util::Status TraceProcessorMain(int argc, char** argv) {
1108 CommandLineOptions options = ParseCommandLineOptions(argc, argv);
1109
1110 Config config;
1111 config.force_full_sort = options.force_full_sort;
1112
1113 std::unique_ptr<TraceProcessor> tp = TraceProcessor::CreateInstance(config);
1114 g_tp = tp.get();
1115
Lalit Maganti427b8332020-05-27 16:09:45 +01001116 // Enable metatracing as soon as possible.
1117 if (!options.metatrace_path.empty()) {
1118 tp->EnableMetatrace();
1119 }
1120
Lalit Maganti2ae24642020-04-16 13:14:17 +01001121 base::TimeNanos t_load{};
1122 if (!options.trace_file_path.empty()) {
1123 base::TimeNanos t_load_start = base::GetWallTimeNs();
1124 double size_mb = 0;
1125 RETURN_IF_ERROR(LoadTrace(options.trace_file_path, &size_mb));
1126 t_load = base::GetWallTimeNs() - t_load_start;
1127
Florian Mayer39e40d42020-07-16 14:52:07 +02001128 double t_load_s = static_cast<double>(t_load.count()) / 1E9;
Lalit Maganti2ae24642020-04-16 13:14:17 +01001129 PERFETTO_ILOG("Trace loaded: %.2f MB (%.1f MB/s)", size_mb,
1130 size_mb / t_load_s);
1131
1132 RETURN_IF_ERROR(PrintStats());
Rafal Slawikd28f0302019-10-22 17:00:04 +01001133 }
1134
Lalit Maganti2ae24642020-04-16 13:14:17 +01001135#if PERFETTO_BUILDFLAG(PERFETTO_TP_HTTPD)
1136 if (options.enable_httpd) {
Anindita Ghoshff779472020-08-25 15:28:25 +00001137 RunHttpRPCServer(std::move(tp), options.port_number);
Lalit Maganti2ae24642020-04-16 13:14:17 +01001138 PERFETTO_FATAL("Should never return");
Primiano Tucci7e330292018-08-24 19:10:52 +02001139 }
Lalit Maganti2ae24642020-04-16 13:14:17 +01001140#endif
1141
1142#if PERFETTO_HAS_SIGNAL_H()
1143 signal(SIGINT, [](int) { g_tp->InterruptQuery(); });
1144#endif
1145
1146 base::TimeNanos t_query_start = base::GetWallTimeNs();
Mikhail Khokhlova0978752020-06-09 12:26:27 +01001147 if (!options.pre_metrics_path.empty()) {
1148 RETURN_IF_ERROR(RunQueries(options.pre_metrics_path, false));
1149 }
1150
Lalit Maganti2ae24642020-04-16 13:14:17 +01001151 if (!options.metric_names.empty()) {
1152 RETURN_IF_ERROR(RunMetrics(options));
1153 }
1154
1155 if (!options.query_file_path.empty()) {
Mikhail Khokhlova0978752020-06-09 12:26:27 +01001156 RETURN_IF_ERROR(RunQueries(options.query_file_path, true));
Lalit Maganti2ae24642020-04-16 13:14:17 +01001157 }
1158 base::TimeNanos t_query = base::GetWallTimeNs() - t_query_start;
Hector Dearmane44ad452018-09-21 11:51:57 +01001159
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +01001160 if (!options.sqlite_file_path.empty()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +01001161 RETURN_IF_ERROR(ExportTraceToDatabase(options.sqlite_file_path));
Sami Kyostila33668942018-11-13 16:33:32 +00001162 }
1163
Lalit Maganti2ae24642020-04-16 13:14:17 +01001164 if (options.launch_shell) {
1165 RETURN_IF_ERROR(StartInteractiveShell(options.wide ? 40 : 20));
1166 } else if (!options.perf_file_path.empty()) {
1167 RETURN_IF_ERROR(PrintPerfFile(options.perf_file_path, t_load, t_query));
Sami Kyostila33668942018-11-13 16:33:32 +00001168 }
Lalit Maganti427b8332020-05-27 16:09:45 +01001169
1170 if (!options.metatrace_path.empty()) {
1171 std::vector<uint8_t> serialized;
1172 util::Status status = g_tp->DisableAndReadMetatrace(&serialized);
1173 if (!status.ok())
1174 return status;
1175
1176 auto file =
1177 base::OpenFile(options.metatrace_path, O_CREAT | O_RDWR | O_TRUNC);
1178 if (!file)
1179 return util::ErrStatus("Unable to open metatrace file");
1180
1181 ssize_t res = base::WriteAll(*file, serialized.data(), serialized.size());
1182 if (res < 0)
1183 return util::ErrStatus("Error while writing metatrace file");
1184 }
1185
Lalit Maganti2ae24642020-04-16 13:14:17 +01001186 return util::OkStatus();
Primiano Tucci5968caf2018-08-06 10:31:46 +01001187}
Lalit Maganti1ebebf12018-10-15 17:24:04 +01001188
1189} // namespace
1190
1191} // namespace trace_processor
1192} // namespace perfetto
1193
1194int main(int argc, char** argv) {
Lalit Maganti2ae24642020-04-16 13:14:17 +01001195 auto status = perfetto::trace_processor::TraceProcessorMain(argc, argv);
1196 if (!status.ok()) {
1197 PERFETTO_ELOG("%s", status.c_message());
1198 return 1;
1199 }
1200 return 0;
Lalit Maganti1ebebf12018-10-15 17:24:04 +01001201}