blob: b50c172415009f0d6e95bc14f6307a59bc6a04d4 [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 Maganti26f69bd2019-04-29 18:23:47 +010018#include <stdio.h>
Primiano Tucci7e330292018-08-24 19:10:52 +020019#include <sys/stat.h>
Primiano Tucci5968caf2018-08-06 10:31:46 +010020
Primiano Tucci58d2dc62021-06-24 16:03:24 +010021#include <cinttypes>
Primiano Tucci5968caf2018-08-06 10:31:46 +010022#include <functional>
Lalit Maganti21160e82018-10-16 09:40:29 +010023#include <iostream>
Deepanjan Roy4ed736c2021-08-12 20:54:02 -040024#include <unordered_set>
Lalit Maganti7c959782019-04-02 16:54:12 +010025#include <vector>
Primiano Tucci5968caf2018-08-06 10:31:46 +010026
Lalit Magantica4d5142019-05-28 13:25:47 +010027#include <google/protobuf/compiler/parser.h>
Lalit Maganti812ef672019-05-28 13:28:02 +010028#include <google/protobuf/dynamic_message.h>
Lalit Magantica4d5142019-05-28 13:25:47 +010029#include <google/protobuf/io/zero_copy_stream_impl.h>
Lalit Maganti812ef672019-05-28 13:28:02 +010030#include <google/protobuf/text_format.h>
Lalit Magantica4d5142019-05-28 13:25:47 +010031
Primiano Tucci24647142018-08-13 21:18:24 +020032#include "perfetto/base/build_config.h"
Primiano Tucci5968caf2018-08-06 10:31:46 +010033#include "perfetto/base/logging.h"
Deepanjan Roy4ed736c2021-08-12 20:54:02 -040034#include "perfetto/base/status.h"
Eric Seckler83dcc8c2019-08-21 12:18:43 +010035#include "perfetto/base/time.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010036#include "perfetto/ext/base/file_utils.h"
Primiano Tucciccaf6db2021-01-05 22:32:26 +010037#include "perfetto/ext/base/getopt.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010038#include "perfetto/ext/base/scoped_file.h"
39#include "perfetto/ext/base/string_splitter.h"
Lalit Maganti7e2d2d32020-03-20 21:55:11 +000040#include "perfetto/ext/base/string_utils.h"
Primiano Tucciec590132020-11-16 14:16:44 +010041#include "perfetto/ext/base/version.h"
Florian Mayer9a683092020-12-23 18:30:00 +000042
Eric Seckler8f70bbf2019-10-09 09:37:43 +010043#include "perfetto/trace_processor/read_trace.h"
Ioannis Ilkoseff38f52018-10-29 10:37:55 +000044#include "perfetto/trace_processor/trace_processor.h"
Deepanjan Royf4da5092020-07-15 17:59:04 -040045#include "src/trace_processor/metrics/chrome/all_chrome_metrics.descriptor.h"
Lalit Maganti812ef672019-05-28 13:28:02 +010046#include "src/trace_processor/metrics/metrics.descriptor.h"
Deepanjan Roy4ed736c2021-08-12 20:54:02 -040047#include "src/trace_processor/metrics/metrics.h"
Lalit Maganti3d9bbff2020-04-15 13:40:58 +010048#include "src/trace_processor/util/proto_to_json.h"
Lalit Maganti2ae24642020-04-16 13:14:17 +010049#include "src/trace_processor/util/status_macros.h"
Primiano Tucci5968caf2018-08-06 10:31:46 +010050
Primiano Tucci41327402021-06-01 20:28:00 +010051#include "protos/perfetto/trace_processor/trace_processor.pbzero.h"
52
Primiano Tuccia36cccc2019-10-27 13:15:04 +010053#if PERFETTO_BUILDFLAG(PERFETTO_TP_HTTPD)
54#include "src/trace_processor/rpc/httpd.h"
55#endif
Florian Mayer9a683092020-12-23 18:30:00 +000056#include "src/profiling/deobfuscator.h"
Andres Medinad6a8d3c2020-11-04 17:12:49 -080057#include "src/profiling/symbolizer/local_symbolizer.h"
Florian Mayer6cc8b1d2019-12-18 16:37:32 +000058#include "src/profiling/symbolizer/symbolize_database.h"
59#include "src/profiling/symbolizer/symbolizer.h"
Florian Mayer6cc8b1d2019-12-18 16:37:32 +000060
Primiano Tucci24647142018-08-13 21:18:24 +020061#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
62 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
Primiano Tucci15f5e872020-07-27 23:08:05 +020063 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
Primiano Tucci24647142018-08-13 21:18:24 +020064#define PERFETTO_HAS_SIGNAL_H() 1
65#else
66#define PERFETTO_HAS_SIGNAL_H() 0
67#endif
68
Primiano Tucci02c11762019-08-30 00:57:59 +020069#if PERFETTO_BUILDFLAG(PERFETTO_TP_LINENOISE)
Hector Dearmane44ad452018-09-21 11:51:57 +010070#include <linenoise.h>
Hector Dearman36adc822018-10-02 11:35:08 +010071#include <pwd.h>
72#include <sys/types.h>
Primiano Tucci75ae50e2019-08-28 13:09:55 +020073#endif
74
Primiano Tucci24647142018-08-13 21:18:24 +020075#if PERFETTO_HAS_SIGNAL_H()
76#include <signal.h>
77#endif
78
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +010079#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
Primiano Tuccie775ede2020-12-08 17:06:28 +010080#include <io.h>
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +010081#define ftruncate _chsize
82#else
Lalit Magantif9d80302019-06-19 12:48:25 +010083#include <dirent.h>
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +010084#endif
85
Primiano Tucciab293f52020-12-08 11:46:52 +010086#if PERFETTO_BUILDFLAG(PERFETTO_TP_LINENOISE) && \
87 !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
88#include <unistd.h> // For getuid() in GetConfigPath().
89#endif
90
Lalit Maganti1ebebf12018-10-15 17:24:04 +010091namespace perfetto {
92namespace trace_processor {
Primiano Tucci5968caf2018-08-06 10:31:46 +010093
94namespace {
Primiano Tucci24647142018-08-13 21:18:24 +020095TraceProcessor* g_tp;
96
Primiano Tucci02c11762019-08-30 00:57:59 +020097#if PERFETTO_BUILDFLAG(PERFETTO_TP_LINENOISE)
Hector Dearmane44ad452018-09-21 11:51:57 +010098
Hector Dearman36adc822018-10-02 11:35:08 +010099bool EnsureDir(const std::string& path) {
Primiano Tuccib730b112020-12-01 14:56:11 +0100100 return base::Mkdir(path) || errno == EEXIST;
Hector Dearman36adc822018-10-02 11:35:08 +0100101}
102
103bool EnsureFile(const std::string& path) {
Primiano Tuccif675dc22018-10-18 00:17:26 +0200104 return base::OpenFile(path, O_RDONLY | O_CREAT, 0644).get() != -1;
Hector Dearman36adc822018-10-02 11:35:08 +0100105}
106
107std::string GetConfigPath() {
108 const char* homedir = getenv("HOME");
Primiano Tucciab293f52020-12-08 11:46:52 +0100109#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \
110 PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) || \
111 PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE)
Hector Dearman36adc822018-10-02 11:35:08 +0100112 if (homedir == nullptr)
113 homedir = getpwuid(getuid())->pw_dir;
Primiano Tucciab293f52020-12-08 11:46:52 +0100114#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
115 if (homedir == nullptr)
116 homedir = getenv("USERPROFILE");
117#endif
Hector Dearman36adc822018-10-02 11:35:08 +0100118 if (homedir == nullptr)
119 return "";
120 return std::string(homedir) + "/.config";
121}
122
123std::string GetPerfettoPath() {
124 std::string config = GetConfigPath();
Hector Dearmane97c89b2021-01-08 13:00:13 +0000125 if (config.empty())
Hector Dearman36adc822018-10-02 11:35:08 +0100126 return "";
127 return config + "/perfetto";
128}
129
130std::string GetHistoryPath() {
131 std::string perfetto = GetPerfettoPath();
Hector Dearmane97c89b2021-01-08 13:00:13 +0000132 if (perfetto.empty())
Hector Dearman36adc822018-10-02 11:35:08 +0100133 return "";
134 return perfetto + "/.trace_processor_shell_history";
135}
136
Hector Dearmane44ad452018-09-21 11:51:57 +0100137void SetupLineEditor() {
138 linenoiseSetMultiLine(true);
139 linenoiseHistorySetMaxLen(1000);
Hector Dearman36adc822018-10-02 11:35:08 +0100140
Hector Dearmane97c89b2021-01-08 13:00:13 +0000141 bool success = !GetHistoryPath().empty();
Hector Dearman36adc822018-10-02 11:35:08 +0100142 success = success && EnsureDir(GetConfigPath());
143 success = success && EnsureDir(GetPerfettoPath());
144 success = success && EnsureFile(GetHistoryPath());
145 success = success && linenoiseHistoryLoad(GetHistoryPath().c_str()) != -1;
146 if (!success) {
147 PERFETTO_PLOG("Could not load history from %s", GetHistoryPath().c_str());
148 }
Primiano Tucci5968caf2018-08-06 10:31:46 +0100149}
150
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000151struct LineDeleter {
152 void operator()(char* p) const {
153 linenoiseHistoryAdd(p);
154 linenoiseHistorySave(GetHistoryPath().c_str());
155 linenoiseFree(p);
156 }
157};
Hector Dearmane44ad452018-09-21 11:51:57 +0100158
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000159using ScopedLine = std::unique_ptr<char, LineDeleter>;
160
161ScopedLine GetLine(const char* prompt) {
Primiano Tucci0f3872d2020-06-02 22:44:28 +0100162 errno = 0;
163 auto line = ScopedLine(linenoise(prompt));
164 // linenoise returns a nullptr both for CTRL-C and CTRL-D, however in the
165 // former case it sets errno to EAGAIN.
166 // If the user press CTRL-C return "" instead of nullptr. We don't want the
167 // main loop to quit in that case as that is inconsistent with the behavior
168 // "CTRL-C interrupts the current query" and frustrating when hitting that
169 // a split second after the query is done.
170 if (!line && errno == EAGAIN)
171 return ScopedLine(strdup(""));
172 return line;
Hector Dearmane44ad452018-09-21 11:51:57 +0100173}
174
175#else
176
177void SetupLineEditor() {}
178
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000179using ScopedLine = std::unique_ptr<char>;
Hector Dearmane44ad452018-09-21 11:51:57 +0100180
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000181ScopedLine GetLine(const char* prompt) {
Hector Dearmane44ad452018-09-21 11:51:57 +0100182 printf("\r%80s\r%s", "", prompt);
183 fflush(stdout);
Florian Mayerb5fa0c92019-12-18 12:44:46 +0000184 ScopedLine line(new char[1024]);
Lalit Maganti3be20912019-12-18 13:48:45 +0000185 if (!fgets(line.get(), 1024 - 1, stdin))
Hector Dearmane44ad452018-09-21 11:51:57 +0100186 return nullptr;
Lalit Maganti3be20912019-12-18 13:48:45 +0000187 if (strlen(line.get()) > 0)
188 line.get()[strlen(line.get()) - 1] = 0;
Hector Dearmane44ad452018-09-21 11:51:57 +0100189 return line;
190}
191
Primiano Tucci02c11762019-08-30 00:57:59 +0200192#endif // PERFETTO_TP_LINENOISE
Hector Dearmane44ad452018-09-21 11:51:57 +0100193
Lalit Maganti2ae24642020-04-16 13:14:17 +0100194util::Status PrintStats() {
Lalit Maganti49ae9012019-04-03 16:10:39 +0100195 auto it = g_tp->ExecuteQuery(
196 "SELECT name, idx, source, value from stats "
Ioannis Ilkos5e79b8a2019-05-23 18:09:54 +0100197 "where severity IN ('error', 'data_loss') and value > 0");
Lalit Maganti49ae9012019-04-03 16:10:39 +0100198
199 bool first = true;
200 for (uint32_t rows = 0; it.Next(); rows++) {
201 if (first) {
202 fprintf(stderr, "Error stats for this trace:\n");
203
204 for (uint32_t i = 0; i < it.ColumnCount(); i++)
Eric Secklera4f75b72019-12-09 12:08:06 +0000205 fprintf(stderr, "%40s ", it.GetColumnName(i).c_str());
Lalit Maganti49ae9012019-04-03 16:10:39 +0100206 fprintf(stderr, "\n");
207
208 for (uint32_t i = 0; i < it.ColumnCount(); i++)
209 fprintf(stderr, "%40s ", "----------------------------------------");
210 fprintf(stderr, "\n");
211
212 first = false;
213 }
214
215 for (uint32_t c = 0; c < it.ColumnCount(); c++) {
216 auto value = it.Get(c);
217 switch (value.type) {
218 case SqlValue::Type::kNull:
219 fprintf(stderr, "%-40.40s", "[NULL]");
220 break;
221 case SqlValue::Type::kDouble:
222 fprintf(stderr, "%40f", value.double_value);
223 break;
224 case SqlValue::Type::kLong:
225 fprintf(stderr, "%40" PRIi64, value.long_value);
226 break;
227 case SqlValue::Type::kString:
228 fprintf(stderr, "%-40.40s", value.string_value);
229 break;
Lalit Maganti62211072019-05-10 14:09:58 +0100230 case SqlValue::Type::kBytes:
231 printf("%-40.40s", "<raw bytes>");
232 break;
Lalit Maganti49ae9012019-04-03 16:10:39 +0100233 }
234 fprintf(stderr, " ");
235 }
236 fprintf(stderr, "\n");
237 }
238
Lalit Maganti1f067182019-05-09 14:50:05 +0100239 util::Status status = it.Status();
240 if (!status.ok()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100241 return util::ErrStatus("Error while iterating stats (%s)",
242 status.c_message());
Lalit Maganti49ae9012019-04-03 16:10:39 +0100243 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100244 return util::OkStatus();
Lalit Maganti49ae9012019-04-03 16:10:39 +0100245}
246
Lalit Maganti2ae24642020-04-16 13:14:17 +0100247util::Status ExportTraceToDatabase(const std::string& output_name) {
Hector Dearman9f5b5bf2021-01-29 14:59:22 +0000248 PERFETTO_CHECK(output_name.find('\'') == std::string::npos);
Sami Kyostila33668942018-11-13 16:33:32 +0000249 {
250 base::ScopedFile fd(base::OpenFile(output_name, O_CREAT | O_RDWR, 0600));
Lalit Maganti2ae24642020-04-16 13:14:17 +0100251 if (!fd)
252 return util::ErrStatus("Failed to create file: %s", output_name.c_str());
Sami Kyostila33668942018-11-13 16:33:32 +0000253 int res = ftruncate(fd.get(), 0);
254 PERFETTO_CHECK(res == 0);
255 }
256
Sami Kyostila33668942018-11-13 16:33:32 +0000257 std::string attach_sql =
258 "ATTACH DATABASE '" + output_name + "' AS perfetto_export";
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100259 auto attach_it = g_tp->ExecuteQuery(attach_sql);
Lalit Magantic72cea22019-04-08 12:29:15 +0100260 bool attach_has_more = attach_it.Next();
261 PERFETTO_DCHECK(!attach_has_more);
Lalit Maganti1f067182019-05-09 14:50:05 +0100262
263 util::Status status = attach_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100264 if (!status.ok())
265 return util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila33668942018-11-13 16:33:32 +0000266
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000267 // Export real and virtual tables.
Lalit Magantic72cea22019-04-08 12:29:15 +0100268 auto tables_it = g_tp->ExecuteQuery(
269 "SELECT name FROM perfetto_tables UNION "
270 "SELECT name FROM sqlite_master WHERE type='table'");
271 for (uint32_t rows = 0; tables_it.Next(); rows++) {
272 std::string table_name = tables_it.Get(0).string_value;
Hector Dearman6be5c742021-05-12 20:12:02 +0100273 PERFETTO_CHECK(!base::Contains(table_name, '\''));
Lalit Magantic72cea22019-04-08 12:29:15 +0100274 std::string export_sql = "CREATE TABLE perfetto_export." + table_name +
275 " AS SELECT * FROM " + table_name;
276
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100277 auto export_it = g_tp->ExecuteQuery(export_sql);
Lalit Magantic72cea22019-04-08 12:29:15 +0100278 bool export_has_more = export_it.Next();
279 PERFETTO_DCHECK(!export_has_more);
Lalit Maganti1f067182019-05-09 14:50:05 +0100280
281 status = export_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100282 if (!status.ok())
283 return util::ErrStatus("SQLite error: %s", status.c_message());
Lalit Magantic72cea22019-04-08 12:29:15 +0100284 }
Lalit Maganti1f067182019-05-09 14:50:05 +0100285 status = tables_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100286 if (!status.ok())
287 return util::ErrStatus("SQLite error: %s", status.c_message());
Lalit Magantic72cea22019-04-08 12:29:15 +0100288
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000289 // Export views.
290 auto views_it =
291 g_tp->ExecuteQuery("SELECT sql FROM sqlite_master WHERE type='view'");
292 for (uint32_t rows = 0; views_it.Next(); rows++) {
293 std::string sql = views_it.Get(0).string_value;
294 // View statements are of the form "CREATE VIEW name AS stmt". We need to
295 // rewrite name to point to the exported db.
296 const std::string kPrefix = "CREATE VIEW ";
297 PERFETTO_CHECK(sql.find(kPrefix) == 0);
298 sql = sql.substr(0, kPrefix.size()) + "perfetto_export." +
299 sql.substr(kPrefix.size());
300
301 auto export_it = g_tp->ExecuteQuery(sql);
302 bool export_has_more = export_it.Next();
303 PERFETTO_DCHECK(!export_has_more);
304
305 status = export_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100306 if (!status.ok())
307 return util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000308 }
309 status = views_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100310 if (!status.ok())
311 return util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila5e81d2d2020-02-26 12:07:10 +0000312
Lalit Magantic72cea22019-04-08 12:29:15 +0100313 auto detach_it = g_tp->ExecuteQuery("DETACH DATABASE perfetto_export");
314 bool detach_has_more = attach_it.Next();
315 PERFETTO_DCHECK(!detach_has_more);
Lalit Maganti1f067182019-05-09 14:50:05 +0100316 status = detach_it.Status();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100317 return status.ok() ? util::OkStatus()
318 : util::ErrStatus("SQLite error: %s", status.c_message());
Sami Kyostila33668942018-11-13 16:33:32 +0000319}
320
Lalit Magantica4d5142019-05-28 13:25:47 +0100321class ErrorPrinter : public google::protobuf::io::ErrorCollector {
322 void AddError(int line, int col, const std::string& msg) override {
323 PERFETTO_ELOG("%d:%d: %s", line, col, msg.c_str());
324 }
325
326 void AddWarning(int line, int col, const std::string& msg) override {
327 PERFETTO_ILOG("%d:%d: %s", line, col, msg.c_str());
328 }
329};
330
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000331// This function returns an indentifier for a metric suitable for use
332// as an SQL table name (i.e. containing no forward or backward slashes).
333std::string BaseName(std::string metric_path) {
334 std::replace(metric_path.begin(), metric_path.end(), '\\', '/');
335 auto slash_idx = metric_path.rfind('/');
336 return slash_idx == std::string::npos ? metric_path
337 : metric_path.substr(slash_idx + 1);
338}
339
Lalit Magantica4d5142019-05-28 13:25:47 +0100340util::Status RegisterMetric(const std::string& register_metric) {
341 std::string sql;
342 base::ReadFile(register_metric, &sql);
343
Mikhail Khokhlov582f7ce2020-01-14 17:30:34 +0000344 std::string path = "shell/" + BaseName(register_metric);
Lalit Magantica4d5142019-05-28 13:25:47 +0100345
346 return g_tp->RegisterMetric(path, sql);
347}
348
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400349base::Status ParseToFileDescriptorProto(
350 const std::string& filename,
351 google::protobuf::FileDescriptorProto* file_desc) {
352 base::ScopedFile file(base::OpenFile(filename, O_RDONLY));
Lalit Magantif9d80302019-06-19 12:48:25 +0100353 if (file.get() == -1) {
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400354 return base::ErrStatus("Failed to open proto file %s", filename.c_str());
Lalit Magantif9d80302019-06-19 12:48:25 +0100355 }
Lalit Magantica4d5142019-05-28 13:25:47 +0100356
357 google::protobuf::io::FileInputStream stream(file.get());
358 ErrorPrinter printer;
359 google::protobuf::io::Tokenizer tokenizer(&stream, &printer);
360
Lalit Magantica4d5142019-05-28 13:25:47 +0100361 google::protobuf::compiler::Parser parser;
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500362 parser.Parse(&tokenizer, file_desc);
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400363 return base::OkStatus();
364}
365
366util::Status ExtendMetricsProto(const std::string& extend_metrics_proto,
367 google::protobuf::DescriptorPool* pool) {
368 google::protobuf::FileDescriptorSet desc_set;
369 auto* file_desc = desc_set.add_file();
370 RETURN_IF_ERROR(ParseToFileDescriptorProto(extend_metrics_proto, file_desc));
Lalit Magantica4d5142019-05-28 13:25:47 +0100371
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500372 file_desc->set_name(BaseName(extend_metrics_proto));
373 pool->BuildFile(*file_desc);
Lalit Maganti812ef672019-05-28 13:28:02 +0100374
Lalit Magantica4d5142019-05-28 13:25:47 +0100375 std::vector<uint8_t> metric_proto;
Andres Medinad6a8d3c2020-11-04 17:12:49 -0800376 metric_proto.resize(desc_set.ByteSizeLong());
Lalit Magantica4d5142019-05-28 13:25:47 +0100377 desc_set.SerializeToArray(metric_proto.data(),
378 static_cast<int>(metric_proto.size()));
379
380 return g_tp->ExtendMetricsProto(metric_proto.data(), metric_proto.size());
381}
382
Lalit Maganti25863f72019-08-28 22:14:25 +0100383enum OutputFormat {
384 kBinaryProto,
385 kTextProto,
386 kJson,
Rafal Slawikd28f0302019-10-22 17:00:04 +0100387 kNone,
Lalit Maganti25863f72019-08-28 22:14:25 +0100388};
389
Lalit Maganti2ae24642020-04-16 13:14:17 +0100390util::Status RunMetrics(const std::vector<std::string>& metric_names,
391 OutputFormat format,
392 const google::protobuf::DescriptorPool& pool) {
Lalit Magantid9f86b62019-04-08 11:11:51 +0100393 std::vector<uint8_t> metric_result;
Lalit Magantid71a9452019-05-09 15:13:24 +0100394 util::Status status = g_tp->ComputeMetric(metric_names, &metric_result);
395 if (!status.ok()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100396 return util::ErrStatus("Error when computing metrics: %s",
397 status.c_message());
Lalit Maganti7c959782019-04-02 16:54:12 +0100398 }
Rafal Slawikd28f0302019-10-22 17:00:04 +0100399 if (format == OutputFormat::kNone) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100400 return util::OkStatus();
Rafal Slawikd28f0302019-10-22 17:00:04 +0100401 }
Lalit Maganti25863f72019-08-28 22:14:25 +0100402 if (format == OutputFormat::kBinaryProto) {
Lalit Maganti812ef672019-05-28 13:28:02 +0100403 fwrite(metric_result.data(), sizeof(uint8_t), metric_result.size(), stdout);
Lalit Maganti2ae24642020-04-16 13:14:17 +0100404 return util::OkStatus();
Lalit Maganti25863f72019-08-28 22:14:25 +0100405 }
406
407 google::protobuf::DynamicMessageFactory factory(&pool);
408 auto* descriptor = pool.FindMessageTypeByName("perfetto.protos.TraceMetrics");
409 std::unique_ptr<google::protobuf::Message> metrics(
410 factory.GetPrototype(descriptor)->New());
411 metrics->ParseFromArray(metric_result.data(),
412 static_cast<int>(metric_result.size()));
413
414 switch (format) {
415 case OutputFormat::kTextProto: {
416 std::string out;
417 google::protobuf::TextFormat::PrintToString(*metrics, &out);
418 fwrite(out.c_str(), sizeof(char), out.size(), stdout);
419 break;
420 }
421 case OutputFormat::kJson: {
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500422 // We need to instantiate field options from dynamic message factory
423 // because otherwise it cannot parse our custom extensions.
424 const google::protobuf::Message* field_options_prototype =
425 factory.GetPrototype(
426 pool.FindMessageTypeByName("google.protobuf.FieldOptions"));
427 auto out = proto_to_json::MessageToJsonWithAnnotations(
428 *metrics, field_options_prototype, 0);
Lalit Maganti25863f72019-08-28 22:14:25 +0100429 fwrite(out.c_str(), sizeof(char), out.size(), stdout);
430 break;
431 }
432 case OutputFormat::kBinaryProto:
Rafal Slawikd28f0302019-10-22 17:00:04 +0100433 case OutputFormat::kNone:
Lalit Maganti25863f72019-08-28 22:14:25 +0100434 PERFETTO_FATAL("Unsupported output format.");
Lalit Maganti812ef672019-05-28 13:28:02 +0100435 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100436 return util::OkStatus();
Lalit Maganti7c959782019-04-02 16:54:12 +0100437}
438
Primiano Tucci4e01f632020-06-11 17:03:05 +0100439void PrintQueryResultInteractively(Iterator* it,
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100440 base::TimeNanos t_start,
441 uint32_t column_width) {
Lalit Magantic72cea22019-04-08 12:29:15 +0100442 base::TimeNanos t_end = t_start;
443 for (uint32_t rows = 0; it->Next(); rows++) {
444 if (rows % 32 == 0) {
445 if (rows > 0) {
Primiano Tucci5968caf2018-08-06 10:31:46 +0100446 fprintf(stderr, "...\nType 'q' to stop, Enter for more records: ");
447 fflush(stderr);
448 char input[32];
449 if (!fgets(input, sizeof(input) - 1, stdin))
450 exit(0);
451 if (input[0] == 'q')
452 break;
Lalit Magantic72cea22019-04-08 12:29:15 +0100453 } else {
Lalit Magantiaac2f652019-04-30 12:16:21 +0100454 t_end = base::GetWallTimeNs();
Primiano Tucci5968caf2018-08-06 10:31:46 +0100455 }
Lalit Magantic72cea22019-04-08 12:29:15 +0100456 for (uint32_t i = 0; i < it->ColumnCount(); i++)
Lalit Magantid74f36a2019-07-12 16:35:57 +0100457 printf("%-*.*s ", column_width, column_width,
Eric Secklera4f75b72019-12-09 12:08:06 +0000458 it->GetColumnName(i).c_str());
Primiano Tucci5968caf2018-08-06 10:31:46 +0100459 printf("\n");
460
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100461 std::string divider(column_width, '-');
462 for (uint32_t i = 0; i < it->ColumnCount(); i++) {
463 printf("%-*s ", column_width, divider.c_str());
464 }
Primiano Tucci5968caf2018-08-06 10:31:46 +0100465 printf("\n");
466 }
467
Lalit Magantic72cea22019-04-08 12:29:15 +0100468 for (uint32_t c = 0; c < it->ColumnCount(); c++) {
469 auto value = it->Get(c);
470 switch (value.type) {
471 case SqlValue::Type::kNull:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100472 printf("%-*s", column_width, "[NULL]");
Lalit Magantic72cea22019-04-08 12:29:15 +0100473 break;
474 case SqlValue::Type::kDouble:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100475 printf("%*f", column_width, value.double_value);
Lalit Magantic72cea22019-04-08 12:29:15 +0100476 break;
477 case SqlValue::Type::kLong:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100478 printf("%*" PRIi64, column_width, value.long_value);
Lalit Magantic72cea22019-04-08 12:29:15 +0100479 break;
480 case SqlValue::Type::kString:
Lalit Magantid74f36a2019-07-12 16:35:57 +0100481 printf("%-*.*s", column_width, column_width, value.string_value);
Lalit Magantic72cea22019-04-08 12:29:15 +0100482 break;
Lalit Maganti62211072019-05-10 14:09:58 +0100483 case SqlValue::Type::kBytes:
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100484 printf("%-*s", column_width, "<raw bytes>");
Lalit Maganti62211072019-05-10 14:09:58 +0100485 break;
Lalit Maganti21160e82018-10-16 09:40:29 +0100486 }
487 printf(" ");
488 }
489 printf("\n");
490 }
Lalit Magantic72cea22019-04-08 12:29:15 +0100491
Lalit Maganti1f067182019-05-09 14:50:05 +0100492 util::Status status = it->Status();
493 if (!status.ok()) {
494 PERFETTO_ELOG("SQLite error: %s", status.c_message());
Lalit Magantic72cea22019-04-08 12:29:15 +0100495 }
Florian Mayer39e40d42020-07-16 14:52:07 +0200496 printf("\nQuery executed in %.3f ms\n\n",
497 static_cast<double>((t_end - t_start).count()) / 1E6);
Lalit Maganti21160e82018-10-16 09:40:29 +0100498}
Sami Kyostila33668942018-11-13 16:33:32 +0000499
Primiano Tucci4e01f632020-06-11 17:03:05 +0100500util::Status PrintQueryResultAsCsv(Iterator* it, FILE* output) {
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100501 for (uint32_t c = 0; c < it->ColumnCount(); c++) {
502 if (c > 0)
503 fprintf(output, ",");
Eric Secklera4f75b72019-12-09 12:08:06 +0000504 fprintf(output, "\"%s\"", it->GetColumnName(c).c_str());
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100505 }
506 fprintf(output, "\n");
Lalit Maganti21160e82018-10-16 09:40:29 +0100507
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100508 for (uint32_t rows = 0; it->Next(); rows++) {
Lalit Magantic72cea22019-04-08 12:29:15 +0100509 for (uint32_t c = 0; c < it->ColumnCount(); c++) {
Lalit Maganti21160e82018-10-16 09:40:29 +0100510 if (c > 0)
511 fprintf(output, ",");
Lalit Magantib55c8842018-12-13 14:26:08 +0000512
Lalit Magantic72cea22019-04-08 12:29:15 +0100513 auto value = it->Get(c);
514 switch (value.type) {
515 case SqlValue::Type::kNull:
516 fprintf(output, "\"%s\"", "[NULL]");
517 break;
518 case SqlValue::Type::kDouble:
519 fprintf(output, "%f", value.double_value);
520 break;
521 case SqlValue::Type::kLong:
522 fprintf(output, "%" PRIi64, value.long_value);
523 break;
524 case SqlValue::Type::kString:
525 fprintf(output, "\"%s\"", value.string_value);
526 break;
Lalit Maganti62211072019-05-10 14:09:58 +0100527 case SqlValue::Type::kBytes:
528 fprintf(output, "\"%s\"", "<raw bytes>");
529 break;
Primiano Tucci5968caf2018-08-06 10:31:46 +0100530 }
531 }
Lalit Magantib55c8842018-12-13 14:26:08 +0000532 fprintf(output, "\n");
Primiano Tucci5968caf2018-08-06 10:31:46 +0100533 }
Mikhail Khokhlov7a3a8652019-07-08 13:56:39 +0100534 return it->Status();
Lalit Maganti21160e82018-10-16 09:40:29 +0100535}
536
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000537bool IsBlankLine(const std::string& buffer) {
538 return buffer == "\n" || buffer == "\r\n";
539}
540
541bool IsCommentLine(const std::string& buffer) {
542 return base::StartsWith(buffer, "--");
543}
544
545bool HasEndOfQueryDelimiter(const std::string& buffer) {
546 return base::EndsWith(buffer, ";\n") || base::EndsWith(buffer, ";") ||
547 base::EndsWith(buffer, ";\r\n");
Florian Mayer3c742432019-05-21 11:35:47 +0100548}
549
Lalit Maganti2ae24642020-04-16 13:14:17 +0100550util::Status LoadQueries(FILE* input, std::vector<std::string>* output) {
Lalit Maganti21160e82018-10-16 09:40:29 +0100551 char buffer[4096];
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000552 while (!feof(input) && !ferror(input)) {
Lalit Maganti21160e82018-10-16 09:40:29 +0100553 std::string sql_query;
554 while (fgets(buffer, sizeof(buffer), input)) {
Lalit Maganti9ae35302020-08-12 16:09:41 +0100555 std::string line = base::TrimLeading(buffer);
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000556 if (IsBlankLine(line))
Lalit Maganti21160e82018-10-16 09:40:29 +0100557 break;
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000558
559 if (IsCommentLine(line))
560 continue;
561
562 sql_query.append(line);
563
564 if (HasEndOfQueryDelimiter(line))
565 break;
Lalit Maganti21160e82018-10-16 09:40:29 +0100566 }
Lalit Maganti7e2d2d32020-03-20 21:55:11 +0000567 if (!sql_query.empty() && sql_query.back() == '\n')
Lalit Maganti21160e82018-10-16 09:40:29 +0100568 sql_query.resize(sql_query.size() - 1);
Lalit Maganticbccb0a2018-12-04 20:14:42 +0000569
570 // If we have a new line at the end of the file or an extra new line
571 // somewhere in the file, we'll end up with an empty query which we should
572 // just ignore.
573 if (sql_query.empty())
574 continue;
575
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000576 output->push_back(sql_query);
577 }
578 if (ferror(input)) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100579 return util::ErrStatus("Error reading query file");
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000580 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100581 return util::OkStatus();
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000582}
583
Lalit Maganti62062832020-07-16 19:34:08 +0100584util::Status RunQueriesWithoutOutput(const std::vector<std::string>& queries) {
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100585 for (const auto& sql_query : queries) {
586 PERFETTO_DLOG("Executing query: %s", sql_query.c_str());
587
588 auto it = g_tp->ExecuteQuery(sql_query);
Lalit Maganti62062832020-07-16 19:34:08 +0100589 RETURN_IF_ERROR(it.Status());
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100590 if (it.Next()) {
591 return util::ErrStatus("Unexpected result from a query.");
592 }
Lalit Maganti738d5a32021-05-25 19:25:15 +0100593 RETURN_IF_ERROR(it.Status());
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100594 }
595 return util::OkStatus();
596}
597
Lalit Maganti62062832020-07-16 19:34:08 +0100598util::Status RunQueriesAndPrintResult(const std::vector<std::string>& queries,
599 FILE* output) {
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000600 bool is_first_query = true;
Ioannis Ilkos433c8e52019-02-11 12:52:35 +0000601 bool has_output = false;
Ioannis Ilkos42dafcc2019-02-08 17:35:27 +0000602 for (const auto& sql_query : queries) {
603 // Add an extra newline separator between query results.
604 if (!is_first_query)
605 fprintf(output, "\n");
606 is_first_query = false;
607
Lalit Maganti21160e82018-10-16 09:40:29 +0100608 PERFETTO_ILOG("Executing query: %s", sql_query.c_str());
609
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100610 auto it = g_tp->ExecuteQuery(sql_query);
Lalit Maganti62062832020-07-16 19:34:08 +0100611 RETURN_IF_ERROR(it.Status());
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100612 if (it.ColumnCount() == 0) {
613 bool it_has_more = it.Next();
Lalit Maganti738d5a32021-05-25 19:25:15 +0100614 RETURN_IF_ERROR(it.Status());
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100615 PERFETTO_DCHECK(!it_has_more);
616 continue;
617 }
618
Lalit Maganti0b810072020-07-08 12:00:45 +0100619 // If we have a single column with the name |suppress_query_output| that's
620 // a hint to shell that it should not treat the query as having real
621 // meaning.
622 if (it.ColumnCount() == 1 &&
623 it.GetColumnName(0) == "suppress_query_output") {
624 // We should only see a single null value as this feature is usually used
625 // as SELECT RUN_METRIC(<metric file>) as suppress_query_output and
626 // RUN_METRIC returns a single null.
627 bool has_next = it.Next();
Lalit Maganti62062832020-07-16 19:34:08 +0100628 RETURN_IF_ERROR(it.Status());
Lalit Maganti0b810072020-07-08 12:00:45 +0100629 PERFETTO_DCHECK(has_next);
630 PERFETTO_DCHECK(it.Get(0).is_null());
631
632 has_next = it.Next();
Lalit Maganti62062832020-07-16 19:34:08 +0100633 RETURN_IF_ERROR(it.Status());
Lalit Maganti0b810072020-07-08 12:00:45 +0100634 PERFETTO_DCHECK(!has_next);
Lalit Maganti0b810072020-07-08 12:00:45 +0100635 continue;
636 }
637
Hector Dearman2af21922019-09-03 13:48:38 +0100638 if (has_output) {
Lalit Maganti0b810072020-07-08 12:00:45 +0100639 return util::ErrStatus(
640 "More than one query generated result rows. This is unsupported.");
Hector Dearman2af21922019-09-03 13:48:38 +0100641 }
Lalit Maganti73b1a0a2019-04-08 13:51:14 +0100642 has_output = true;
Lalit Maganti62062832020-07-16 19:34:08 +0100643 RETURN_IF_ERROR(PrintQueryResultAsCsv(&it, output));
Lalit Maganti21160e82018-10-16 09:40:29 +0100644 }
Lalit Maganti0b810072020-07-08 12:00:45 +0100645 return util::OkStatus();
Lalit Maganti21160e82018-10-16 09:40:29 +0100646}
647
Lalit Maganti2ae24642020-04-16 13:14:17 +0100648util::Status PrintPerfFile(const std::string& perf_file_path,
649 base::TimeNanos t_load,
650 base::TimeNanos t_run) {
Lalit Maganti260e04d2019-05-03 13:17:01 +0100651 char buf[128];
652 int count = snprintf(buf, sizeof(buf), "%" PRId64 ",%" PRId64,
653 static_cast<int64_t>(t_load.count()),
654 static_cast<int64_t>(t_run.count()));
655 if (count < 0) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100656 return util::ErrStatus("Failed to write perf data");
Lalit Maganti260e04d2019-05-03 13:17:01 +0100657 }
658
Lalit Maganti04a450a2019-07-03 16:04:19 +0100659 auto fd(base::OpenFile(perf_file_path, O_WRONLY | O_CREAT | O_TRUNC, 0666));
Lalit Maganti260e04d2019-05-03 13:17:01 +0100660 if (!fd) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100661 return util::ErrStatus("Failed to open perf file");
Lalit Maganti260e04d2019-05-03 13:17:01 +0100662 }
663 base::WriteAll(fd.get(), buf, static_cast<size_t>(count));
Lalit Maganti2ae24642020-04-16 13:14:17 +0100664 return util::OkStatus();
Lalit Maganti260e04d2019-05-03 13:17:01 +0100665}
666
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400667class MetricExtension {
668 public:
669 void SetDiskPath(std::string path) {
670 AddTrailingSlashIfNeeded(path);
671 disk_path_ = std::move(path);
672 }
673 void SetVirtualPath(std::string path) {
674 AddTrailingSlashIfNeeded(path);
675 virtual_path_ = std::move(path);
676 }
677
678 // Disk location. Ends with a trailing slash.
679 const std::string& disk_path() const { return disk_path_; }
680 // Virtual location. Ends with a trailing slash.
681 const std::string& virtual_path() const { return virtual_path_; }
682
683 private:
684 std::string disk_path_;
685 std::string virtual_path_;
686
687 static void AddTrailingSlashIfNeeded(std::string& path) {
688 if (path.length() > 0 && path[path.length() - 1] != '/') {
689 path.push_back('/');
690 }
691 }
692};
693
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100694struct CommandLineOptions {
695 std::string perf_file_path;
696 std::string query_file_path;
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100697 std::string pre_metrics_path;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100698 std::string sqlite_file_path;
699 std::string metric_names;
700 std::string metric_output;
701 std::string trace_file_path;
Anindita Ghoshff779472020-08-25 15:28:25 +0000702 std::string port_number;
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400703 std::vector<std::string> raw_metric_extensions;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100704 bool launch_shell = false;
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100705 bool enable_httpd = false;
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100706 bool wide = false;
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100707 bool force_full_sort = false;
Lalit Maganti427b8332020-05-27 16:09:45 +0100708 std::string metatrace_path;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100709};
710
Lalit Magantiedace412019-06-18 13:28:28 +0100711void PrintUsage(char** argv) {
712 PERFETTO_ELOG(R"(
713Interactive trace processor shell.
714Usage: %s [OPTIONS] trace_file.pb
715
716Options:
Lalit Maganti82adf6a2019-09-26 18:05:51 +0100717 -h, --help Prints this guide.
718 -v, --version Prints the version of trace processor.
719 -d, --debug Enable virtual table debugging.
720 -W, --wide Prints interactive output with double
721 column width.
722 -p, --perf-file FILE Writes the time taken to ingest the trace
723 and execute the queries to the given file.
724 Only valid with -q or --run-metrics and
725 the file will only be written if the
726 execution is successful.
727 -q, --query-file FILE Read and execute an SQL query from a file.
Rafal Slawikd28f0302019-10-22 17:00:04 +0100728 If used with --run-metrics, the query is
729 executed after the selected metrics and
730 the metrics output is suppressed.
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100731 --pre-metrics FILE Read and execute an SQL query from a file.
732 This query is executed before the selected
733 metrics and can't output any results.
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100734 -D, --httpd Enables the HTTP RPC server.
Anindita Ghoshff779472020-08-25 15:28:25 +0000735 --http-port PORT Specify what port to run HTTP RPC server.
Lalit Maganti82adf6a2019-09-26 18:05:51 +0100736 -i, --interactive Starts interactive mode even after a query
737 file is specified with -q or
738 --run-metrics.
Lalit Maganti2ae24642020-04-16 13:14:17 +0100739 -e, --export FILE Export the contents of trace processor
740 into an SQLite database after running any
741 metrics or queries specified.
Lalit Maganti82adf6a2019-09-26 18:05:51 +0100742 --run-metrics x,y,z Runs a comma separated list of metrics and
743 prints the result as a TraceMetrics proto
744 to stdout. The specified can either be
745 in-built metrics or SQL/proto files of
746 extension metrics.
747 --metrics-output=[binary|text|json] Allows the output of --run-metrics to be
748 specified in either proto binary, proto
749 text format or JSON format (default: proto
750 text).
Lalit Maganti427b8332020-05-27 16:09:45 +0100751 -m, --metatrace FILE Enables metatracing of trace processor
752 writing the resulting trace into FILE.
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100753 --full-sort Forces the trace processor into performing
754 a full sort ignoring any windowing
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400755 logic.
756 --metric-extension DISK_PATH:VIRTUAL_PATH
757 Loads metric proto and sql files from
758 DISK_PATH/protos and DISK_PATH/sql
759 respectively, and mounts them onto
760 VIRTUAL_PATH.)",
Lalit Magantiedace412019-06-18 13:28:28 +0100761 argv[0]);
762}
Lalit Maganti260e04d2019-05-03 13:17:01 +0100763
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100764CommandLineOptions ParseCommandLineOptions(int argc, char** argv) {
765 CommandLineOptions command_line_options;
766 enum LongOption {
767 OPT_RUN_METRICS = 1000,
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100768 OPT_PRE_METRICS,
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100769 OPT_METRICS_OUTPUT,
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100770 OPT_FORCE_FULL_SORT,
Anindita Ghoshff779472020-08-25 15:28:25 +0000771 OPT_HTTP_PORT,
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400772 OPT_METRIC_EXTENSION,
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100773 };
774
Primiano Tucci42433ab2020-11-30 18:42:01 +0100775 static const option long_options[] = {
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100776 {"help", no_argument, nullptr, 'h'},
777 {"version", no_argument, nullptr, 'v'},
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100778 {"wide", no_argument, nullptr, 'W'},
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100779 {"httpd", no_argument, nullptr, 'D'},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100780 {"interactive", no_argument, nullptr, 'i'},
781 {"debug", no_argument, nullptr, 'd'},
782 {"perf-file", required_argument, nullptr, 'p'},
783 {"query-file", required_argument, nullptr, 'q'},
784 {"export", required_argument, nullptr, 'e'},
Lalit Maganti427b8332020-05-27 16:09:45 +0100785 {"metatrace", required_argument, nullptr, 'm'},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100786 {"run-metrics", required_argument, nullptr, OPT_RUN_METRICS},
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100787 {"pre-metrics", required_argument, nullptr, OPT_PRE_METRICS},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100788 {"metrics-output", required_argument, nullptr, OPT_METRICS_OUTPUT},
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100789 {"full-sort", no_argument, nullptr, OPT_FORCE_FULL_SORT},
Anindita Ghoshff779472020-08-25 15:28:25 +0000790 {"http-port", required_argument, nullptr, OPT_HTTP_PORT},
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400791 {"metric-extension", required_argument, nullptr, OPT_METRIC_EXTENSION},
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100792 {nullptr, 0, nullptr, 0}};
793
794 bool explicit_interactive = false;
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100795 for (;;) {
796 int option =
Primiano Tucciccaf6db2021-01-05 22:32:26 +0100797 getopt_long(argc, argv, "hvWiDdm:p:q:e:", long_options, nullptr);
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100798
799 if (option == -1)
800 break; // EOF.
801
802 if (option == 'v') {
Primiano Tucciec590132020-11-16 14:16:44 +0100803 printf("%s\n", base::GetVersionString());
Primiano Tucci41327402021-06-01 20:28:00 +0100804 printf("Trace Processor RPC API version: %d\n",
805 protos::pbzero::TRACE_PROCESSOR_CURRENT_API_VERSION);
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100806 exit(0);
807 }
808
809 if (option == 'i') {
810 explicit_interactive = true;
811 continue;
812 }
813
Primiano Tuccia36cccc2019-10-27 13:15:04 +0100814 if (option == 'D') {
815#if PERFETTO_BUILDFLAG(PERFETTO_TP_HTTPD)
816 command_line_options.enable_httpd = true;
817#else
818 PERFETTO_FATAL("HTTP RPC module not supported in this build");
819#endif
820 continue;
821 }
822
Lalit Magantia8dcfdd2019-07-08 18:14:27 +0100823 if (option == 'W') {
824 command_line_options.wide = true;
825 continue;
826 }
827
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100828 if (option == 'd') {
829 EnableSQLiteVtableDebugging();
830 continue;
831 }
832
833 if (option == 'p') {
834 command_line_options.perf_file_path = optarg;
835 continue;
836 }
837
838 if (option == 'q') {
839 command_line_options.query_file_path = optarg;
840 continue;
841 }
842
843 if (option == 'e') {
844 command_line_options.sqlite_file_path = optarg;
845 continue;
846 }
847
Lalit Maganti427b8332020-05-27 16:09:45 +0100848 if (option == 'm') {
849 command_line_options.metatrace_path = optarg;
850 continue;
851 }
852
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100853 if (option == OPT_PRE_METRICS) {
854 command_line_options.pre_metrics_path = optarg;
855 continue;
856 }
857
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100858 if (option == OPT_RUN_METRICS) {
859 command_line_options.metric_names = optarg;
860 continue;
861 }
862
863 if (option == OPT_METRICS_OUTPUT) {
864 command_line_options.metric_output = optarg;
865 continue;
866 }
867
Lalit Maganti55d0bc72019-10-23 16:22:00 +0100868 if (option == OPT_FORCE_FULL_SORT) {
869 command_line_options.force_full_sort = true;
870 continue;
871 }
872
Anindita Ghoshff779472020-08-25 15:28:25 +0000873 if (option == OPT_HTTP_PORT) {
874 command_line_options.port_number = optarg;
875 continue;
876 }
877
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400878 if (option == OPT_METRIC_EXTENSION) {
879 command_line_options.raw_metric_extensions.push_back(optarg);
880 continue;
881 }
882
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100883 PrintUsage(argv);
884 exit(option == 'h' ? 0 : 1);
885 }
886
887 command_line_options.launch_shell =
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100888 explicit_interactive || (command_line_options.pre_metrics_path.empty() &&
889 command_line_options.metric_names.empty() &&
Lalit Maganti2ae24642020-04-16 13:14:17 +0100890 command_line_options.query_file_path.empty() &&
891 command_line_options.sqlite_file_path.empty());
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100892
893 // Only allow non-interactive queries to emit perf data.
894 if (!command_line_options.perf_file_path.empty() &&
895 command_line_options.launch_shell) {
896 PrintUsage(argv);
897 exit(1);
898 }
899
Primiano Tucciee2ce1d2019-11-01 19:14:17 +0100900 // The only case where we allow omitting the trace file path is when running
901 // in --http mode. In all other cases, the last argument must be the trace
902 // file.
903 if (optind == argc - 1 && argv[optind]) {
904 command_line_options.trace_file_path = argv[optind];
905 } else if (!command_line_options.enable_httpd) {
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100906 PrintUsage(argv);
907 exit(1);
908 }
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400909
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100910 return command_line_options;
911}
Lalit Magantif9d80302019-06-19 12:48:25 +0100912
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500913void ExtendPoolWithBinaryDescriptor(google::protobuf::DescriptorPool& pool,
914 const void* data,
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400915 int size,
916 std::vector<std::string>& skip_prefixes) {
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500917 google::protobuf::FileDescriptorSet desc_set;
918 desc_set.ParseFromArray(data, size);
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400919 for (const auto& file_desc : desc_set.file()) {
920 if (base::StartsWithAny(file_desc.name(), skip_prefixes))
921 continue;
922 pool.BuildFile(file_desc);
Deepanjan Royab8c05d2020-01-21 09:55:26 -0500923 }
924}
925
Lalit Maganti2ae24642020-04-16 13:14:17 +0100926util::Status LoadTrace(const std::string& trace_file_path, double* size_mb) {
927 util::Status read_status =
928 ReadTrace(g_tp, trace_file_path.c_str(), [&size_mb](size_t parsed_size) {
Florian Mayer39e40d42020-07-16 14:52:07 +0200929 *size_mb = static_cast<double>(parsed_size) / 1E6;
Lalit Maganti2ae24642020-04-16 13:14:17 +0100930 fprintf(stderr, "\rLoading trace: %.2f MB\r", *size_mb);
931 });
932 if (!read_status.ok()) {
933 return util::ErrStatus("Could not read trace file (path: %s): %s",
934 trace_file_path.c_str(), read_status.c_message());
935 }
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +0100936
Florian Mayer6d1f0ae2020-07-21 08:59:29 +0100937 std::unique_ptr<profiling::Symbolizer> symbolizer =
938 profiling::LocalSymbolizerOrDie(profiling::GetPerfettoBinaryPath(),
939 getenv("PERFETTO_SYMBOLIZER_MODE"));
Lalit Magantie8cd8a32020-02-27 16:54:46 +0000940
Lalit Maganti2ae24642020-04-16 13:14:17 +0100941 if (symbolizer) {
942 profiling::SymbolizeDatabase(
943 g_tp, symbolizer.get(), [](const std::string& trace_proto) {
944 std::unique_ptr<uint8_t[]> buf(new uint8_t[trace_proto.size()]);
945 memcpy(buf.get(), trace_proto.data(), trace_proto.size());
946 auto status = g_tp->Parse(std::move(buf), trace_proto.size());
947 if (!status.ok()) {
948 PERFETTO_DFATAL_OR_ELOG("Failed to parse: %s",
949 status.message().c_str());
950 return;
951 }
952 });
953 g_tp->NotifyEndOfFile();
Primiano Tucciee2ce1d2019-11-01 19:14:17 +0100954 }
Florian Mayerf4255a42020-12-14 19:12:34 +0000955
956 auto maybe_map = profiling::GetPerfettoProguardMapPath();
957 if (!maybe_map.empty()) {
958 profiling::ReadProguardMapsToDeobfuscationPackets(
959 maybe_map, [](const std::string& trace_proto) {
960 std::unique_ptr<uint8_t[]> buf(new uint8_t[trace_proto.size()]);
961 memcpy(buf.get(), trace_proto.data(), trace_proto.size());
962 auto status = g_tp->Parse(std::move(buf), trace_proto.size());
963 if (!status.ok()) {
964 PERFETTO_DFATAL_OR_ELOG("Failed to parse: %s",
965 status.message().c_str());
966 return;
967 }
968 });
969 }
Lalit Maganti2ae24642020-04-16 13:14:17 +0100970 return util::OkStatus();
971}
Primiano Tucciee2ce1d2019-11-01 19:14:17 +0100972
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100973util::Status RunQueries(const std::string& query_file_path,
974 bool expect_output) {
Lalit Maganti2ae24642020-04-16 13:14:17 +0100975 std::vector<std::string> queries;
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100976 base::ScopedFstream file(fopen(query_file_path.c_str(), "r"));
Lalit Maganti2ae24642020-04-16 13:14:17 +0100977 if (!file) {
978 return util::ErrStatus("Could not open query file (path: %s)",
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100979 query_file_path.c_str());
Lalit Maganti2ae24642020-04-16 13:14:17 +0100980 }
981 RETURN_IF_ERROR(LoadQueries(file.get(), &queries));
Lalit Maganti62062832020-07-16 19:34:08 +0100982
983 util::Status status;
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100984 if (expect_output) {
Lalit Maganti62062832020-07-16 19:34:08 +0100985 status = RunQueriesAndPrintResult(queries, stdout);
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100986 } else {
Lalit Maganti62062832020-07-16 19:34:08 +0100987 status = RunQueriesWithoutOutput(queries);
Mikhail Khokhlova0978752020-06-09 12:26:27 +0100988 }
Lalit Maganti62062832020-07-16 19:34:08 +0100989 if (!status.ok()) {
990 return util::ErrStatus("Encountered error while running queries: %s",
991 status.c_message());
992 }
993 return util::OkStatus();
Lalit Maganti2ae24642020-04-16 13:14:17 +0100994}
Primiano Tucci5968caf2018-08-06 10:31:46 +0100995
Deepanjan Roy4ed736c2021-08-12 20:54:02 -0400996base::Status ParseSingleMetricExtensionPath(const std::string& raw_extension,
997 MetricExtension& parsed_extension) {
998 std::vector<std::string> parts = base::SplitString(raw_extension, ":");
999 if (parts.size() != 2 || parts[0].length() == 0 || parts[1].length() == 0) {
1000 return base::ErrStatus(
1001 "--metric-extension-dir must be of format disk_path:virtual_path");
1002 }
1003
1004 parsed_extension.SetDiskPath(std::move(parts[0]));
1005 parsed_extension.SetVirtualPath(std::move(parts[1]));
1006
1007 if (parsed_extension.virtual_path() == "shell/") {
1008 return base::Status(
1009 "Cannot have 'shell/' as metric extension virtual path.");
1010 }
1011 return util::OkStatus();
1012}
1013
1014base::Status CheckForDuplicateMetricExtension(
1015 const std::vector<MetricExtension>& metric_extensions) {
1016 std::unordered_set<std::string> disk_paths;
1017 std::unordered_set<std::string> virtual_paths;
1018 for (const auto& extension : metric_extensions) {
1019 auto ret = disk_paths.insert(extension.disk_path());
1020 if (!ret.second) {
1021 return base::ErrStatus(
1022 "Another metric extension is already using disk path %s",
1023 extension.disk_path().c_str());
1024 }
1025 ret = virtual_paths.insert(extension.virtual_path());
1026 if (!ret.second) {
1027 return base::ErrStatus(
1028 "Another metric extension is already using virtual path %s",
1029 extension.virtual_path().c_str());
1030 }
1031 }
1032 return base::OkStatus();
1033}
1034
1035base::Status ParseMetricExtensionPaths(
1036 const std::vector<std::string>& raw_metric_extensions,
1037 std::vector<MetricExtension>& metric_extensions) {
1038 for (const auto& raw_extension : raw_metric_extensions) {
1039 metric_extensions.push_back({});
1040 RETURN_IF_ERROR(ParseSingleMetricExtensionPath(raw_extension,
1041 metric_extensions.back()));
1042 }
1043 return CheckForDuplicateMetricExtension(metric_extensions);
1044}
1045
1046base::Status LoadMetricExtensionProtos(const std::string& proto_root,
1047 const std::string& mount_path) {
1048 if (!base::FileExists(proto_root)) {
1049 return base::ErrStatus(
1050 "Directory %s does not exist. Metric extension directory must contain "
1051 "a 'sql/' and 'protos/' subdirectory.",
1052 proto_root.c_str());
1053 }
1054 std::vector<std::string> proto_files;
1055 RETURN_IF_ERROR(base::ListFilesRecursive(proto_root, proto_files));
1056
1057 google::protobuf::FileDescriptorSet parsed_protos;
1058 for (const auto& file_path : proto_files) {
1059 if (base::GetFileExtension(file_path) != ".proto")
1060 continue;
1061 auto* file_desc = parsed_protos.add_file();
1062 ParseToFileDescriptorProto(proto_root + file_path, file_desc);
1063 file_desc->set_name(mount_path + file_path);
1064 }
1065
1066 std::vector<uint8_t> serialized_filedescset;
1067 serialized_filedescset.resize(parsed_protos.ByteSizeLong());
1068 parsed_protos.SerializeToArray(
1069 serialized_filedescset.data(),
1070 static_cast<int>(serialized_filedescset.size()));
1071
1072 RETURN_IF_ERROR(g_tp->ExtendMetricsProto(serialized_filedescset.data(),
1073 serialized_filedescset.size()));
1074
1075 return base::OkStatus();
1076}
1077
1078base::Status LoadMetricExtensionSql(const std::string& sql_root,
1079 const std::string& mount_path) {
1080 if (!base::FileExists(sql_root)) {
1081 return base::ErrStatus(
1082 "Directory %s does not exist. Metric extension directory must contain "
1083 "a 'sql/' and 'protos/' subdirectory.",
1084 sql_root.c_str());
1085 }
1086
1087 std::vector<std::string> sql_files;
1088 RETURN_IF_ERROR(base::ListFilesRecursive(sql_root, sql_files));
1089 for (const auto& file_path : sql_files) {
1090 if (base::GetFileExtension(file_path) != ".sql")
1091 continue;
1092 std::string file_contents;
1093 if (!base::ReadFile(sql_root + file_path, &file_contents)) {
1094 return base::ErrStatus("Cannot read file %s", file_path.c_str());
1095 }
1096 RETURN_IF_ERROR(
1097 g_tp->RegisterMetric(mount_path + file_path, file_contents));
1098 }
1099
1100 return base::OkStatus();
1101}
1102
1103base::Status LoadMetricExtension(const MetricExtension& extension) {
1104 const std::string& disk_path = extension.disk_path();
1105 const std::string& virtual_path = extension.virtual_path();
1106
1107 if (!base::FileExists(disk_path)) {
1108 return base::ErrStatus("Metric extension directory %s does not exist",
1109 disk_path.c_str());
1110 }
1111
1112 // Note: Proto files must be loaded first, because we determine whether an SQL
1113 // file is a metric or not by checking if the name matches a field of the root
1114 // TraceMetrics proto.
1115 RETURN_IF_ERROR(LoadMetricExtensionProtos(disk_path + "protos/",
1116 kMetricProtoRoot + virtual_path));
1117 RETURN_IF_ERROR(LoadMetricExtensionSql(disk_path + "sql/", virtual_path));
1118
1119 return base::OkStatus();
1120}
1121
1122util::Status RunMetrics(const CommandLineOptions& options,
1123 std::vector<MetricExtension>& metric_extensions) {
1124 // Descriptor pool used for printing output as textproto. Building on top of
1125 // generated pool so default protos in google.protobuf.descriptor.proto are
1126 // available.
Deepanjan Royab8c05d2020-01-21 09:55:26 -05001127 google::protobuf::DescriptorPool pool(
1128 google::protobuf::DescriptorPool::generated_pool());
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001129 // TODO(b/182165266): There is code duplication here with trace_processor_impl
1130 // SetupMetrics. This will be removed when we switch the output formatter to
1131 // use internal DescriptorPool.
1132 std::vector<std::string> skip_prefixes;
1133 for (const auto& ext : metric_extensions) {
1134 skip_prefixes.push_back(kMetricProtoRoot + ext.virtual_path());
1135 }
Deepanjan Royab8c05d2020-01-21 09:55:26 -05001136 ExtendPoolWithBinaryDescriptor(pool, kMetricsDescriptor.data(),
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001137 kMetricsDescriptor.size(), skip_prefixes);
Deepanjan Royf4da5092020-07-15 17:59:04 -04001138 ExtendPoolWithBinaryDescriptor(pool, kAllChromeMetricsDescriptor.data(),
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001139 kAllChromeMetricsDescriptor.size(),
1140 skip_prefixes);
Lalit Maganti812ef672019-05-28 13:28:02 +01001141
Lalit Maganti2ae24642020-04-16 13:14:17 +01001142 std::vector<std::string> metrics;
1143 for (base::StringSplitter ss(options.metric_names, ','); ss.Next();) {
1144 metrics.emplace_back(ss.cur_token());
Rafal Slawikd28f0302019-10-22 17:00:04 +01001145 }
Lalit Maganti7c959782019-04-02 16:54:12 +01001146
Lalit Maganti2ae24642020-04-16 13:14:17 +01001147 // For all metrics which are files, register them and extend the metrics
1148 // proto.
1149 for (size_t i = 0; i < metrics.size(); ++i) {
1150 const std::string& metric_or_path = metrics[i];
1151
1152 // If there is no extension, we assume it is a builtin metric.
Hector Dearman9f5b5bf2021-01-29 14:59:22 +00001153 auto ext_idx = metric_or_path.rfind('.');
Lalit Maganti2ae24642020-04-16 13:14:17 +01001154 if (ext_idx == std::string::npos)
1155 continue;
1156
1157 std::string no_ext_name = metric_or_path.substr(0, ext_idx);
Deepanjan Roy05d99132020-09-10 11:33:41 -04001158
1159 // The proto must be extended before registering the metric.
1160 util::Status status = ExtendMetricsProto(no_ext_name + ".proto", &pool);
Lalit Maganti2ae24642020-04-16 13:14:17 +01001161 if (!status.ok()) {
Deepanjan Roy05d99132020-09-10 11:33:41 -04001162 return util::ErrStatus("Unable to extend metrics proto %s: %s",
Lalit Maganti2ae24642020-04-16 13:14:17 +01001163 metric_or_path.c_str(), status.c_message());
1164 }
1165
Deepanjan Roy05d99132020-09-10 11:33:41 -04001166 status = RegisterMetric(no_ext_name + ".sql");
Lalit Maganti2ae24642020-04-16 13:14:17 +01001167 if (!status.ok()) {
Deepanjan Roy05d99132020-09-10 11:33:41 -04001168 return util::ErrStatus("Unable to register metric %s: %s",
Lalit Maganti2ae24642020-04-16 13:14:17 +01001169 metric_or_path.c_str(), status.c_message());
1170 }
1171
1172 metrics[i] = BaseName(no_ext_name);
1173 }
1174
1175 OutputFormat format;
Rafal Slawikd28f0302019-10-22 17:00:04 +01001176 if (!options.query_file_path.empty()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +01001177 format = OutputFormat::kNone;
1178 } else if (options.metric_output == "binary") {
1179 format = OutputFormat::kBinaryProto;
1180 } else if (options.metric_output == "json") {
1181 format = OutputFormat::kJson;
1182 } else {
1183 format = OutputFormat::kTextProto;
1184 }
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001185
Lalit Maganti2ae24642020-04-16 13:14:17 +01001186 return RunMetrics(std::move(metrics), format, pool);
1187}
1188
Dan Elphick2b4c8ae2020-11-03 17:59:19 +00001189void PrintShellUsage() {
1190 PERFETTO_ELOG(
1191 "Available commands:\n"
1192 ".quit, .q Exit the shell.\n"
1193 ".help This text.\n"
1194 ".dump FILE Export the trace as a sqlite database.\n"
1195 ".read FILE Executes the queries in the FILE.\n"
1196 ".reset Destroys all tables/view created by the user.\n");
1197}
1198
1199util::Status StartInteractiveShell(uint32_t column_width) {
1200 SetupLineEditor();
1201
1202 for (;;) {
1203 ScopedLine line = GetLine("> ");
1204 if (!line)
1205 break;
1206 if (strcmp(line.get(), "") == 0) {
1207 printf("If you want to quit either type .q or press CTRL-D (EOF)\n");
1208 continue;
1209 }
1210 if (line.get()[0] == '.') {
1211 char command[32] = {};
1212 char arg[1024] = {};
1213 sscanf(line.get() + 1, "%31s %1023s", command, arg);
1214 if (strcmp(command, "quit") == 0 || strcmp(command, "q") == 0) {
1215 break;
1216 } else if (strcmp(command, "help") == 0) {
1217 PrintShellUsage();
1218 } else if (strcmp(command, "dump") == 0 && strlen(arg)) {
1219 if (!ExportTraceToDatabase(arg).ok())
1220 PERFETTO_ELOG("Database export failed");
1221 } else if (strcmp(command, "reset") == 0) {
1222 g_tp->RestoreInitialTables();
1223 } else if (strcmp(command, "read") == 0 && strlen(arg)) {
1224 util::Status status = RunQueries(arg, true);
1225 if (!status.ok()) {
1226 PERFETTO_ELOG("%s", status.c_message());
1227 }
1228 } else {
1229 PrintShellUsage();
1230 }
1231 continue;
1232 }
1233
1234 base::TimeNanos t_start = base::GetWallTimeNs();
1235 auto it = g_tp->ExecuteQuery(line.get());
1236 PrintQueryResultInteractively(&it, t_start, column_width);
1237 }
1238 return util::OkStatus();
1239}
1240
Lalit Maganti2ae24642020-04-16 13:14:17 +01001241util::Status TraceProcessorMain(int argc, char** argv) {
1242 CommandLineOptions options = ParseCommandLineOptions(argc, argv);
1243
1244 Config config;
Lalit Maganti88eb6982021-03-01 14:28:51 +00001245 config.sorting_mode = options.force_full_sort
1246 ? SortingMode::kForceFullSort
Lalit Maganti512d9782021-03-03 15:30:11 +00001247 : SortingMode::kDefaultHeuristics;
Lalit Maganti2ae24642020-04-16 13:14:17 +01001248
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001249 std::vector<MetricExtension> metric_extensions;
1250 RETURN_IF_ERROR(ParseMetricExtensionPaths(options.raw_metric_extensions,
1251 metric_extensions));
1252
1253 for (const auto& extension : metric_extensions) {
1254 config.skip_builtin_metric_paths.push_back(extension.virtual_path());
1255 }
1256
Lalit Maganti2ae24642020-04-16 13:14:17 +01001257 std::unique_ptr<TraceProcessor> tp = TraceProcessor::CreateInstance(config);
1258 g_tp = tp.get();
1259
Lalit Maganti427b8332020-05-27 16:09:45 +01001260 // Enable metatracing as soon as possible.
1261 if (!options.metatrace_path.empty()) {
1262 tp->EnableMetatrace();
1263 }
1264
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001265 // We load all the metric extensions even when --run-metrics arg is not there,
1266 // because we want the metrics to be available in interactive mode or when
1267 // used in UI using httpd.
1268 for (const auto& extension : metric_extensions) {
1269 RETURN_IF_ERROR(LoadMetricExtension(extension));
1270 }
1271
Lalit Maganti2ae24642020-04-16 13:14:17 +01001272 base::TimeNanos t_load{};
1273 if (!options.trace_file_path.empty()) {
1274 base::TimeNanos t_load_start = base::GetWallTimeNs();
1275 double size_mb = 0;
1276 RETURN_IF_ERROR(LoadTrace(options.trace_file_path, &size_mb));
1277 t_load = base::GetWallTimeNs() - t_load_start;
1278
Florian Mayer39e40d42020-07-16 14:52:07 +02001279 double t_load_s = static_cast<double>(t_load.count()) / 1E9;
Lalit Maganti2ae24642020-04-16 13:14:17 +01001280 PERFETTO_ILOG("Trace loaded: %.2f MB (%.1f MB/s)", size_mb,
1281 size_mb / t_load_s);
1282
1283 RETURN_IF_ERROR(PrintStats());
Rafal Slawikd28f0302019-10-22 17:00:04 +01001284 }
1285
Lalit Maganti2ae24642020-04-16 13:14:17 +01001286#if PERFETTO_BUILDFLAG(PERFETTO_TP_HTTPD)
1287 if (options.enable_httpd) {
Anindita Ghoshff779472020-08-25 15:28:25 +00001288 RunHttpRPCServer(std::move(tp), options.port_number);
Lalit Maganti2ae24642020-04-16 13:14:17 +01001289 PERFETTO_FATAL("Should never return");
Primiano Tucci7e330292018-08-24 19:10:52 +02001290 }
Lalit Maganti2ae24642020-04-16 13:14:17 +01001291#endif
1292
1293#if PERFETTO_HAS_SIGNAL_H()
1294 signal(SIGINT, [](int) { g_tp->InterruptQuery(); });
1295#endif
1296
1297 base::TimeNanos t_query_start = base::GetWallTimeNs();
Mikhail Khokhlova0978752020-06-09 12:26:27 +01001298 if (!options.pre_metrics_path.empty()) {
1299 RETURN_IF_ERROR(RunQueries(options.pre_metrics_path, false));
1300 }
1301
Lalit Maganti2ae24642020-04-16 13:14:17 +01001302 if (!options.metric_names.empty()) {
Deepanjan Roy4ed736c2021-08-12 20:54:02 -04001303 RETURN_IF_ERROR(RunMetrics(options, metric_extensions));
Lalit Maganti2ae24642020-04-16 13:14:17 +01001304 }
1305
1306 if (!options.query_file_path.empty()) {
Mikhail Khokhlova0978752020-06-09 12:26:27 +01001307 RETURN_IF_ERROR(RunQueries(options.query_file_path, true));
Lalit Maganti2ae24642020-04-16 13:14:17 +01001308 }
1309 base::TimeNanos t_query = base::GetWallTimeNs() - t_query_start;
Hector Dearmane44ad452018-09-21 11:51:57 +01001310
Mikhail Khokhlov8643d1c2019-06-04 12:02:47 +01001311 if (!options.sqlite_file_path.empty()) {
Lalit Maganti2ae24642020-04-16 13:14:17 +01001312 RETURN_IF_ERROR(ExportTraceToDatabase(options.sqlite_file_path));
Sami Kyostila33668942018-11-13 16:33:32 +00001313 }
1314
Lalit Maganti2ae24642020-04-16 13:14:17 +01001315 if (options.launch_shell) {
1316 RETURN_IF_ERROR(StartInteractiveShell(options.wide ? 40 : 20));
1317 } else if (!options.perf_file_path.empty()) {
1318 RETURN_IF_ERROR(PrintPerfFile(options.perf_file_path, t_load, t_query));
Sami Kyostila33668942018-11-13 16:33:32 +00001319 }
Lalit Maganti427b8332020-05-27 16:09:45 +01001320
1321 if (!options.metatrace_path.empty()) {
1322 std::vector<uint8_t> serialized;
1323 util::Status status = g_tp->DisableAndReadMetatrace(&serialized);
1324 if (!status.ok())
1325 return status;
1326
1327 auto file =
1328 base::OpenFile(options.metatrace_path, O_CREAT | O_RDWR | O_TRUNC);
1329 if (!file)
1330 return util::ErrStatus("Unable to open metatrace file");
1331
1332 ssize_t res = base::WriteAll(*file, serialized.data(), serialized.size());
1333 if (res < 0)
1334 return util::ErrStatus("Error while writing metatrace file");
1335 }
1336
Lalit Maganti2ae24642020-04-16 13:14:17 +01001337 return util::OkStatus();
Primiano Tucci5968caf2018-08-06 10:31:46 +01001338}
Lalit Maganti1ebebf12018-10-15 17:24:04 +01001339
1340} // namespace
1341
1342} // namespace trace_processor
1343} // namespace perfetto
1344
1345int main(int argc, char** argv) {
Lalit Maganti2ae24642020-04-16 13:14:17 +01001346 auto status = perfetto::trace_processor::TraceProcessorMain(argc, argv);
1347 if (!status.ok()) {
1348 PERFETTO_ELOG("%s", status.c_message());
1349 return 1;
1350 }
1351 return 0;
Lalit Maganti1ebebf12018-10-15 17:24:04 +01001352}