1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "src/perfetto_cmd/perfetto_cmd.h"
18
19 #include "perfetto/base/build_config.h"
20 #include "perfetto/base/proc_utils.h"
21 #include "perfetto/ext/base/scoped_file.h"
22
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <time.h>
28
29 // For dup().
30 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
31 #include <io.h>
32 #else
33 #include <unistd.h>
34 #endif
35
36 #include <chrono>
37 #include <fstream>
38 #include <iostream>
39 #include <iterator>
40 #include <random>
41 #include <sstream>
42 #include <thread>
43
44 #include "perfetto/base/compiler.h"
45 #include "perfetto/base/logging.h"
46 #include "perfetto/base/time.h"
47 #include "perfetto/ext/base/android_utils.h"
48 #include "perfetto/ext/base/ctrl_c_handler.h"
49 #include "perfetto/ext/base/file_utils.h"
50 #include "perfetto/ext/base/getopt.h"
51 #include "perfetto/ext/base/pipe.h"
52 #include "perfetto/ext/base/string_view.h"
53 #include "perfetto/ext/base/thread_utils.h"
54 #include "perfetto/ext/base/utils.h"
55 #include "perfetto/ext/base/uuid.h"
56 #include "perfetto/ext/base/version.h"
57 #include "perfetto/ext/traced/traced.h"
58 #include "perfetto/ext/tracing/core/basic_types.h"
59 #include "perfetto/ext/tracing/core/trace_packet.h"
60 #include "perfetto/ext/tracing/ipc/default_socket.h"
61 #include "perfetto/protozero/proto_utils.h"
62 #include "perfetto/tracing/core/data_source_descriptor.h"
63 #include "perfetto/tracing/core/trace_config.h"
64 #include "perfetto/tracing/core/tracing_service_state.h"
65 #include "src/android_stats/statsd_logging_helper.h"
66 #include "src/perfetto_cmd/config.h"
67 #include "src/perfetto_cmd/packet_writer.h"
68 #include "src/perfetto_cmd/pbtxt_to_pb.h"
69 #include "src/perfetto_cmd/trigger_producer.h"
70
71 #include "protos/perfetto/common/ftrace_descriptor.gen.h"
72 #include "protos/perfetto/common/tracing_service_state.gen.h"
73 #include "protos/perfetto/common/track_event_descriptor.gen.h"
74
75 namespace perfetto {
76 namespace {
77
78 perfetto::PerfettoCmd* g_perfetto_cmd;
79
80 uint32_t kOnTraceDataTimeoutMs = 3000;
81
82 class LoggingErrorReporter : public ErrorReporter {
83 public:
LoggingErrorReporter(std::string file_name,const char * config)84 LoggingErrorReporter(std::string file_name, const char* config)
85 : file_name_(file_name), config_(config) {}
86
AddError(size_t row,size_t column,size_t length,const std::string & message)87 void AddError(size_t row,
88 size_t column,
89 size_t length,
90 const std::string& message) override {
91 parsed_successfully_ = false;
92 std::string line = ExtractLine(row - 1).ToStdString();
93 if (!line.empty() && line[line.length() - 1] == '\n') {
94 line.erase(line.length() - 1);
95 }
96
97 std::string guide(column + length, ' ');
98 for (size_t i = column; i < column + length; i++) {
99 guide[i - 1] = i == column ? '^' : '~';
100 }
101 fprintf(stderr, "%s:%zu:%zu error: %s\n", file_name_.c_str(), row, column,
102 message.c_str());
103 fprintf(stderr, "%s\n", line.c_str());
104 fprintf(stderr, "%s\n", guide.c_str());
105 }
106
Success() const107 bool Success() const { return parsed_successfully_; }
108
109 private:
ExtractLine(size_t line)110 base::StringView ExtractLine(size_t line) {
111 const char* start = config_;
112 const char* end = config_;
113
114 for (size_t i = 0; i < line + 1; i++) {
115 start = end;
116 char c;
117 while ((c = *end++) && c != '\n')
118 ;
119 }
120 return base::StringView(start, static_cast<size_t>(end - start));
121 }
122
123 bool parsed_successfully_ = true;
124 std::string file_name_;
125 const char* config_;
126 };
127
ParseTraceConfigPbtxt(const std::string & file_name,const std::string & pbtxt,TraceConfig * config)128 bool ParseTraceConfigPbtxt(const std::string& file_name,
129 const std::string& pbtxt,
130 TraceConfig* config) {
131 LoggingErrorReporter reporter(file_name, pbtxt.c_str());
132 std::vector<uint8_t> buf = PbtxtToPb(pbtxt, &reporter);
133 if (!reporter.Success())
134 return false;
135 if (!config->ParseFromArray(buf.data(), buf.size()))
136 return false;
137 return true;
138 }
139
IsUserBuild()140 bool IsUserBuild() {
141 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
142 std::string build_type = base::GetAndroidProp("ro.build.type");
143 if (build_type.empty()) {
144 PERFETTO_ELOG("Unable to read ro.build.type: assuming user build");
145 return true;
146 }
147 return build_type == "user";
148 #else
149 return false;
150 #endif // PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
151 }
152
ConvertRateLimiterResponseToAtom(RateLimiter::ShouldTraceResponse resp)153 base::Optional<PerfettoStatsdAtom> ConvertRateLimiterResponseToAtom(
154 RateLimiter::ShouldTraceResponse resp) {
155 switch (resp) {
156 case RateLimiter::kNotAllowedOnUserBuild:
157 return PerfettoStatsdAtom::kCmdUserBuildTracingNotAllowed;
158 case RateLimiter::kFailedToInitState:
159 return PerfettoStatsdAtom::kCmdFailedToInitGuardrailState;
160 case RateLimiter::kInvalidState:
161 return PerfettoStatsdAtom::kCmdInvalidGuardrailState;
162 case RateLimiter::kHitUploadLimit:
163 return PerfettoStatsdAtom::kCmdHitUploadLimit;
164 case RateLimiter::kOkToTrace:
165 return base::nullopt;
166 }
167 PERFETTO_FATAL("For GCC");
168 }
169
170 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
171 // Reports trace with `uuid` being finalized to the trace marker.
172 //
173 // This reimplements parts of android libcutils, because:
174 // * libcutils is not exposed to the NDK and cannot be used from standalone
175 // perfetto
176 // * libcutils atrace uses properties to enable tags, which are not required in
177 // this case.
ReportFinalizeTraceUuidToAtrace(const base::Uuid & uuid)178 void ReportFinalizeTraceUuidToAtrace(const base::Uuid& uuid) {
179 base::ScopedFile file =
180 base::OpenFile("/sys/kernel/tracing/trace_marker", O_WRONLY);
181 if (!file) {
182 file = base::OpenFile("/sys/kernel/debug/tracing/trace_marker", O_WRONLY);
183 if (!file) {
184 return;
185 }
186 }
187 base::StackString<100> uuid_slice("N|%d|OtherTraces|finalize-uuid-%s",
188 base::GetProcessId(),
189 uuid.ToPrettyString().c_str());
190 PERFETTO_EINTR(write(file.get(), uuid_slice.c_str(), uuid_slice.len()));
191 }
192 #endif // PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
193
194 } // namespace
195
196 const char* kStateDir = "/data/misc/perfetto-traces";
197
PerfettoCmd()198 PerfettoCmd::PerfettoCmd() {
199 PERFETTO_DCHECK(!g_perfetto_cmd);
200 g_perfetto_cmd = this;
201 }
202
~PerfettoCmd()203 PerfettoCmd::~PerfettoCmd() {
204 PERFETTO_DCHECK(g_perfetto_cmd == this);
205 g_perfetto_cmd = nullptr;
206 }
207
PrintUsage(const char * argv0)208 void PerfettoCmd::PrintUsage(const char* argv0) {
209 fprintf(stderr, R"(
210 Usage: %s
211 --background -d : Exits immediately and continues in the background.
212 Prints the PID of the bg process. The printed PID
213 can used to gracefully terminate the tracing
214 session by issuing a `kill -TERM $PRINTED_PID`.
215 --background-wait -D : Like --background, but waits (up to 30s) for all
216 data sources to be started before exiting. Exit
217 code is zero if a successful acknowledgement is
218 received, non-zero otherwise (error or timeout).
219 --config -c : /path/to/trace/config/file or - for stdin
220 --out -o : /path/to/out/trace/file or - for stdout
221 --txt : Parse config as pbtxt. Not for production use.
222 Not a stable API.
223 --query : Queries the service state and prints it as
224 human-readable text.
225 --query-raw : Like --query, but prints raw proto-encoded bytes
226 of tracing_service_state.proto.
227 --help -h
228
229 Light configuration flags: (only when NOT using -c/--config)
230 --time -t : Trace duration N[s,m,h] (default: 10s)
231 --buffer -b : Ring buffer size N[mb,gb] (default: 32mb)
232 --size -s : Max file size N[mb,gb]
233 (default: in-memory ring-buffer only)
234 --app -a : Android (atrace) app name
235 FTRACE_GROUP/FTRACE_NAME : Record ftrace event (e.g. sched/sched_switch)
236 ATRACE_CAT : Record ATRACE_CAT (e.g. wm) (Android only)
237
238 Statsd-specific and other Android-only flags:
239 --alert-id : ID of the alert that triggered this trace.
240 --config-id : ID of the triggering config.
241 --config-uid : UID of app which registered the config.
242 --subscription-id : ID of the subscription that triggered this trace.
243 --upload : Upload trace.
244 --dropbox TAG : DEPRECATED: Use --upload instead
245 TAG should always be set to 'perfetto'.
246 --save-for-bugreport : If a trace with bugreport_score > 0 is running, it
247 saves it into a file. Outputs the path when done.
248 --no-guardrails : Ignore guardrails triggered when using --upload
249 (testing only).
250 --reset-guardrails : Resets the state of the guardails and exits
251 (testing only).
252
253 Detach mode. DISCOURAGED, read https://perfetto.dev/docs/concepts/detached-mode
254 --detach=key : Detach from the tracing session with the given key.
255 --attach=key [--stop] : Re-attach to the session (optionally stop tracing
256 once reattached).
257 --is_detached=key : Check if the session can be re-attached.
258 Exit code: 0:Yes, 2:No, 1:Error.
259 )", /* this comment fixes syntax highlighting in some editors */
260 argv0);
261 }
262
ParseCmdlineAndMaybeDaemonize(int argc,char ** argv)263 base::Optional<int> PerfettoCmd::ParseCmdlineAndMaybeDaemonize(int argc,
264 char** argv) {
265 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
266 umask(0000); // make sure that file creation is not affected by umask.
267 #endif
268 enum LongOption {
269 OPT_ALERT_ID = 1000,
270 OPT_BUGREPORT,
271 OPT_CONFIG_ID,
272 OPT_CONFIG_UID,
273 OPT_SUBSCRIPTION_ID,
274 OPT_RESET_GUARDRAILS,
275 OPT_PBTXT_CONFIG,
276 OPT_DROPBOX,
277 OPT_UPLOAD,
278 OPT_IGNORE_GUARDRAILS,
279 OPT_DETACH,
280 OPT_ATTACH,
281 OPT_IS_DETACHED,
282 OPT_STOP,
283 OPT_QUERY,
284 OPT_QUERY_RAW,
285 OPT_VERSION,
286 };
287 static const option long_options[] = {
288 {"help", no_argument, nullptr, 'h'},
289 {"config", required_argument, nullptr, 'c'},
290 {"out", required_argument, nullptr, 'o'},
291 {"background", no_argument, nullptr, 'd'},
292 {"background-wait", no_argument, nullptr, 'D'},
293 {"time", required_argument, nullptr, 't'},
294 {"buffer", required_argument, nullptr, 'b'},
295 {"size", required_argument, nullptr, 's'},
296 {"app", required_argument, nullptr, 'a'},
297 {"no-guardrails", no_argument, nullptr, OPT_IGNORE_GUARDRAILS},
298 {"txt", no_argument, nullptr, OPT_PBTXT_CONFIG},
299 {"upload", no_argument, nullptr, OPT_UPLOAD},
300 {"dropbox", required_argument, nullptr, OPT_DROPBOX},
301 {"alert-id", required_argument, nullptr, OPT_ALERT_ID},
302 {"config-id", required_argument, nullptr, OPT_CONFIG_ID},
303 {"config-uid", required_argument, nullptr, OPT_CONFIG_UID},
304 {"subscription-id", required_argument, nullptr, OPT_SUBSCRIPTION_ID},
305 {"reset-guardrails", no_argument, nullptr, OPT_RESET_GUARDRAILS},
306 {"detach", required_argument, nullptr, OPT_DETACH},
307 {"attach", required_argument, nullptr, OPT_ATTACH},
308 {"is_detached", required_argument, nullptr, OPT_IS_DETACHED},
309 {"stop", no_argument, nullptr, OPT_STOP},
310 {"query", no_argument, nullptr, OPT_QUERY},
311 {"query-raw", no_argument, nullptr, OPT_QUERY_RAW},
312 {"version", no_argument, nullptr, OPT_VERSION},
313 {"save-for-bugreport", no_argument, nullptr, OPT_BUGREPORT},
314 {nullptr, 0, nullptr, 0}};
315
316 std::string config_file_name;
317 std::string trace_config_raw;
318 bool parse_as_pbtxt = false;
319 TraceConfig::StatsdMetadata statsd_metadata;
320 limiter_.reset(new RateLimiter());
321
322 ConfigOptions config_options;
323 bool has_config_options = false;
324
325 if (argc <= 1) {
326 PrintUsage(argv[0]);
327 return 1;
328 }
329
330 for (;;) {
331 int option =
332 getopt_long(argc, argv, "hc:o:dDt:b:s:a:", long_options, nullptr);
333
334 if (option == -1)
335 break; // EOF.
336
337 if (option == 'c') {
338 config_file_name = std::string(optarg);
339 if (strcmp(optarg, "-") == 0) {
340 std::istreambuf_iterator<char> begin(std::cin), end;
341 trace_config_raw.assign(begin, end);
342 } else if (strcmp(optarg, ":test") == 0) {
343 TraceConfig test_config;
344 ConfigOptions opts;
345 opts.time = "2s";
346 opts.categories.emplace_back("sched/sched_switch");
347 opts.categories.emplace_back("power/cpu_idle");
348 opts.categories.emplace_back("power/cpu_frequency");
349 opts.categories.emplace_back("power/gpu_frequency");
350 PERFETTO_CHECK(CreateConfigFromOptions(opts, &test_config));
351 trace_config_raw = test_config.SerializeAsString();
352 } else {
353 if (!base::ReadFile(optarg, &trace_config_raw)) {
354 PERFETTO_PLOG("Could not open %s", optarg);
355 return 1;
356 }
357 }
358 continue;
359 }
360
361 if (option == 'o') {
362 trace_out_path_ = optarg;
363 continue;
364 }
365
366 if (option == 'd') {
367 background_ = true;
368 continue;
369 }
370
371 if (option == 'D') {
372 background_ = true;
373 background_wait_ = true;
374 continue;
375 }
376
377 if (option == 't') {
378 has_config_options = true;
379 config_options.time = std::string(optarg);
380 continue;
381 }
382
383 if (option == 'b') {
384 has_config_options = true;
385 config_options.buffer_size = std::string(optarg);
386 continue;
387 }
388
389 if (option == 's') {
390 has_config_options = true;
391 config_options.max_file_size = std::string(optarg);
392 continue;
393 }
394
395 if (option == 'a') {
396 config_options.atrace_apps.push_back(std::string(optarg));
397 has_config_options = true;
398 continue;
399 }
400
401 if (option == OPT_UPLOAD) {
402 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
403 upload_flag_ = true;
404 continue;
405 #else
406 PERFETTO_ELOG("--upload is only supported on Android");
407 return 1;
408 #endif
409 }
410
411 if (option == OPT_DROPBOX) {
412 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
413 PERFETTO_CHECK(optarg);
414 upload_flag_ = true;
415 continue;
416 #else
417 PERFETTO_ELOG("--dropbox is only supported on Android");
418 return 1;
419 #endif
420 }
421
422 if (option == OPT_PBTXT_CONFIG) {
423 parse_as_pbtxt = true;
424 continue;
425 }
426
427 if (option == OPT_IGNORE_GUARDRAILS) {
428 ignore_guardrails_ = true;
429 continue;
430 }
431
432 if (option == OPT_RESET_GUARDRAILS) {
433 PERFETTO_CHECK(limiter_->ClearState());
434 PERFETTO_ILOG("Guardrail state cleared");
435 return 0;
436 }
437
438 if (option == OPT_ALERT_ID) {
439 statsd_metadata.set_triggering_alert_id(atoll(optarg));
440 continue;
441 }
442
443 if (option == OPT_CONFIG_ID) {
444 statsd_metadata.set_triggering_config_id(atoll(optarg));
445 continue;
446 }
447
448 if (option == OPT_CONFIG_UID) {
449 statsd_metadata.set_triggering_config_uid(atoi(optarg));
450 continue;
451 }
452
453 if (option == OPT_SUBSCRIPTION_ID) {
454 statsd_metadata.set_triggering_subscription_id(atoll(optarg));
455 continue;
456 }
457
458 if (option == OPT_DETACH) {
459 detach_key_ = std::string(optarg);
460 PERFETTO_CHECK(!detach_key_.empty());
461 continue;
462 }
463
464 if (option == OPT_ATTACH) {
465 attach_key_ = std::string(optarg);
466 PERFETTO_CHECK(!attach_key_.empty());
467 continue;
468 }
469
470 if (option == OPT_IS_DETACHED) {
471 attach_key_ = std::string(optarg);
472 redetach_once_attached_ = true;
473 PERFETTO_CHECK(!attach_key_.empty());
474 continue;
475 }
476
477 if (option == OPT_STOP) {
478 stop_trace_once_attached_ = true;
479 continue;
480 }
481
482 if (option == OPT_QUERY) {
483 query_service_ = true;
484 continue;
485 }
486
487 if (option == OPT_QUERY_RAW) {
488 query_service_ = true;
489 query_service_output_raw_ = true;
490 continue;
491 }
492
493 if (option == OPT_VERSION) {
494 printf("%s\n", base::GetVersionString());
495 return 0;
496 }
497
498 if (option == OPT_BUGREPORT) {
499 bugreport_ = true;
500 continue;
501 }
502
503 PrintUsage(argv[0]);
504 return 1;
505 }
506
507 for (ssize_t i = optind; i < argc; i++) {
508 has_config_options = true;
509 config_options.categories.push_back(argv[i]);
510 }
511
512 if (query_service_ && (is_detach() || is_attach() || background_)) {
513 PERFETTO_ELOG("--query cannot be combined with any other argument");
514 return 1;
515 }
516
517 if (is_detach() && is_attach()) {
518 PERFETTO_ELOG("--attach and --detach are mutually exclusive");
519 return 1;
520 }
521
522 if (is_detach() && background_) {
523 PERFETTO_ELOG("--detach and --background are mutually exclusive");
524 return 1;
525 }
526
527 if (stop_trace_once_attached_ && !is_attach()) {
528 PERFETTO_ELOG("--stop is supported only in combination with --attach");
529 return 1;
530 }
531
532 if (bugreport_ && (is_attach() || is_detach() || query_service_ ||
533 has_config_options || background_wait_)) {
534 PERFETTO_ELOG("--save-for-bugreport cannot take any other argument");
535 return 1;
536 }
537
538 // Parse the trace config. It can be either:
539 // 1) A proto-encoded file/stdin (-c ...).
540 // 2) A proto-text file/stdin (-c ... --txt).
541 // 3) A set of option arguments (-t 10s -s 10m).
542 // The only cases in which a trace config is not expected is --attach.
543 // For this we are just acting on already existing sessions.
544 trace_config_.reset(new TraceConfig());
545
546 bool parsed = false;
547 const bool will_trace_or_trigger =
548 !is_attach() && !query_service_ && !bugreport_;
549 if (!will_trace_or_trigger) {
550 if ((!trace_config_raw.empty() || has_config_options)) {
551 PERFETTO_ELOG("Cannot specify a trace config with this option");
552 return 1;
553 }
554 } else if (has_config_options) {
555 if (!trace_config_raw.empty()) {
556 PERFETTO_ELOG(
557 "Cannot specify both -c/--config and any of --time, --size, "
558 "--buffer, --app, ATRACE_CAT, FTRACE_EVENT");
559 return 1;
560 }
561 parsed = CreateConfigFromOptions(config_options, trace_config_.get());
562 } else {
563 if (trace_config_raw.empty()) {
564 PERFETTO_ELOG("The TraceConfig is empty");
565 return 1;
566 }
567 PERFETTO_DLOG("Parsing TraceConfig, %zu bytes", trace_config_raw.size());
568 if (parse_as_pbtxt) {
569 parsed = ParseTraceConfigPbtxt(config_file_name, trace_config_raw,
570 trace_config_.get());
571 } else {
572 parsed = trace_config_->ParseFromString(trace_config_raw);
573 }
574 }
575
576 if (parsed) {
577 *trace_config_->mutable_statsd_metadata() = std::move(statsd_metadata);
578 trace_config_raw.clear();
579 } else if (will_trace_or_trigger) {
580 PERFETTO_ELOG("The trace config is invalid, bailing out.");
581 return 1;
582 }
583
584 if (trace_config_->trace_uuid_lsb() == 0 &&
585 trace_config_->trace_uuid_msb() == 0) {
586 base::Uuid uuid = base::Uuidv4();
587 if (trace_config_->statsd_metadata().triggering_subscription_id()) {
588 uuid.set_lsb(
589 trace_config_->statsd_metadata().triggering_subscription_id());
590 }
591 uuid_ = uuid.ToString();
592 trace_config_->set_trace_uuid_msb(uuid.msb());
593 trace_config_->set_trace_uuid_lsb(uuid.lsb());
594 } else {
595 base::Uuid uuid(trace_config_->trace_uuid_lsb(),
596 trace_config_->trace_uuid_msb());
597 uuid_ = uuid.ToString();
598 }
599
600 const auto& delay = trace_config_->cmd_trace_start_delay();
601 if (delay.has_max_delay_ms() != delay.has_min_delay_ms()) {
602 PERFETTO_ELOG("cmd_trace_start_delay field is only partially specified.");
603 return 1;
604 }
605
606 bool has_incidentd_package =
607 !trace_config_->incident_report_config().destination_package().empty();
608 if (has_incidentd_package && !upload_flag_) {
609 PERFETTO_ELOG(
610 "Unexpected IncidentReportConfig without --dropbox / --upload.");
611 return 1;
612 }
613
614 bool has_android_reporter_package = !trace_config_->android_report_config()
615 .reporter_service_package()
616 .empty();
617 if (has_android_reporter_package && !upload_flag_) {
618 PERFETTO_ELOG(
619 "Unexpected AndroidReportConfig without --dropbox / --upload.");
620 return 1;
621 }
622
623 if (has_incidentd_package && has_android_reporter_package) {
624 PERFETTO_ELOG(
625 "Only one of IncidentReportConfig and AndroidReportConfig "
626 "allowed in the same config.");
627 return 1;
628 }
629
630 // If the upload flag is set, we can only be doing one of three things:
631 // 1. Reporting to either incidentd or Android framework.
632 // 2. Skipping incidentd/Android report because it was explicitly
633 // specified in the config.
634 // 3. Activating triggers.
635 bool incidentd_valid =
636 has_incidentd_package ||
637 trace_config_->incident_report_config().skip_incidentd();
638 bool android_report_valid =
639 has_android_reporter_package ||
640 trace_config_->android_report_config().skip_report();
641 bool has_triggers = !trace_config_->activate_triggers().empty();
642 if (upload_flag_ && !incidentd_valid && !android_report_valid &&
643 !has_triggers) {
644 PERFETTO_ELOG(
645 "One of IncidentReportConfig, AndroidReportConfig or activate_triggers "
646 "must be specified with --dropbox / --upload.");
647 return 1;
648 }
649
650 // Only save to incidentd if:
651 // 1) |destination_package| is set
652 // 2) |skip_incidentd| is absent or false.
653 // 3) we are not simply activating triggers.
654 save_to_incidentd_ =
655 has_incidentd_package &&
656 !trace_config_->incident_report_config().skip_incidentd() &&
657 !has_triggers;
658
659 // Only report to the Andorid framework if:
660 // 1) |reporter_service_package| is set
661 // 2) |skip_report| is absent or false.
662 // 3) we are not simply activating triggers.
663 report_to_android_framework_ =
664 has_android_reporter_package &&
665 !trace_config_->android_report_config().skip_report() && !has_triggers;
666
667 // Respect the wishes of the config with respect to statsd logging or fall
668 // back on the presence of the --upload flag if not set.
669 switch (trace_config_->statsd_logging()) {
670 case TraceConfig::STATSD_LOGGING_ENABLED:
671 statsd_logging_ = true;
672 break;
673 case TraceConfig::STATSD_LOGGING_DISABLED:
674 statsd_logging_ = false;
675 break;
676 case TraceConfig::STATSD_LOGGING_UNSPECIFIED:
677 statsd_logging_ = upload_flag_;
678 break;
679 }
680 trace_config_->set_statsd_logging(statsd_logging_
681 ? TraceConfig::STATSD_LOGGING_ENABLED
682 : TraceConfig::STATSD_LOGGING_DISABLED);
683
684 // Set up the output file. Either --out or --upload are expected, with the
685 // only exception of --attach. In this case the output file is passed when
686 // detaching.
687 if (!trace_out_path_.empty() && upload_flag_) {
688 PERFETTO_ELOG(
689 "Can't log to a file (--out) and incidentd (--upload) at the same "
690 "time");
691 return 1;
692 }
693
694 if (!trace_config_->output_path().empty()) {
695 if (!trace_out_path_.empty() || upload_flag_) {
696 PERFETTO_ELOG(
697 "Can't pass --out or --upload if output_path is set in the "
698 "trace config");
699 return 1;
700 }
701 if (base::FileExists(trace_config_->output_path())) {
702 PERFETTO_ELOG(
703 "The output_path must not exist, the service cannot overwrite "
704 "existing files for security reasons. Remove %s or use a different "
705 "path.",
706 trace_config_->output_path().c_str());
707 return 1;
708 }
709 }
710
711 // |activate_triggers| in the trace config is shorthand for trigger_perfetto.
712 // In this case we don't intend to send any trace config to the service,
713 // rather use that as a signal to the cmdline client to connect as a producer
714 // and activate triggers.
715 if (has_triggers) {
716 for (const auto& trigger : trace_config_->activate_triggers()) {
717 triggers_to_activate_.push_back(trigger);
718 }
719 trace_config_.reset(new TraceConfig());
720 }
721
722 bool open_out_file = true;
723 if (!will_trace_or_trigger) {
724 open_out_file = false;
725 if (!trace_out_path_.empty() || upload_flag_) {
726 PERFETTO_ELOG("Can't pass an --out file (or --upload) with this option");
727 return 1;
728 }
729 } else if (!triggers_to_activate_.empty() ||
730 (trace_config_->write_into_file() &&
731 !trace_config_->output_path().empty())) {
732 open_out_file = false;
733 } else if (trace_out_path_.empty() && !upload_flag_) {
734 PERFETTO_ELOG("Either --out or --upload is required");
735 return 1;
736 } else if (is_detach() && !trace_config_->write_into_file()) {
737 // In detached mode we must pass the file descriptor to the service and
738 // let that one write the trace. We cannot use the IPC readback code path
739 // because the client process is about to exit soon after detaching.
740 // We could support detach && !write_into_file, but that would make the
741 // cmdline logic more complex. The feasible configurations are:
742 // 1. Using write_into_file and passing the file path on the --detach call.
743 // 2. Using pure ring-buffer mode, setting write_into_file = false and
744 // passing the output file path to the --attach call.
745 // This is too complicated and harder to reason about, so we support only 1.
746 // Traceur gets around this by always setting write_into_file and specifying
747 // file_write_period_ms = 1week (which effectively means: write into the
748 // file only at the end of the trace) to achieve ring buffer traces.
749 PERFETTO_ELOG(
750 "TraceConfig's write_into_file must be true when using --detach");
751 return 1;
752 }
753 if (open_out_file) {
754 if (!OpenOutputFile())
755 return 1;
756 if (!trace_config_->write_into_file())
757 packet_writer_ = CreateFilePacketWriter(trace_out_stream_.get());
758 }
759
760 if (trace_config_->compression_type() ==
761 TraceConfig::COMPRESSION_TYPE_DEFLATE) {
762 if (packet_writer_) {
763 #if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
764 packet_writer_ = CreateZipPacketWriter(std::move(packet_writer_));
765 #else
766 PERFETTO_ELOG("Cannot compress. Zlib not enabled in the build config");
767 #endif
768 } else {
769 PERFETTO_ELOG("Cannot compress when tracing directly to file.");
770 }
771 }
772
773 bool will_trace_indefinitely =
774 trace_config_->duration_ms() == 0 &&
775 trace_config_->trigger_config().trigger_timeout_ms() == 0;
776 if (will_trace_indefinitely && save_to_incidentd_ && !ignore_guardrails_) {
777 PERFETTO_ELOG("Can't trace indefinitely when tracing to Incidentd.");
778 return 1;
779 }
780
781 if (will_trace_indefinitely && report_to_android_framework_ &&
782 !ignore_guardrails_) {
783 PERFETTO_ELOG(
784 "Can't trace indefinitely when reporting to Android framework.");
785 return 1;
786 }
787
788 if (background_) {
789 if (background_wait_) {
790 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
791 background_wait_pipe_ = base::Pipe::Create(base::Pipe::kRdNonBlock);
792 #endif
793 }
794
795 base::Daemonize([this]() -> int {
796 background_wait_pipe_.wr.reset();
797
798 if (background_wait_) {
799 return WaitOnBgProcessPipe();
800 }
801
802 return 0;
803 });
804 background_wait_pipe_.rd.reset();
805 }
806
807 return base::nullopt; // Continues in ConnectToServiceRunAndMaybeNotify()
808 // below.
809 }
810
NotifyBgProcessPipe(BgProcessStatus status)811 void PerfettoCmd::NotifyBgProcessPipe(BgProcessStatus status) {
812 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
813 if (!background_wait_pipe_.wr) {
814 return;
815 }
816 static_assert(sizeof status == 1, "Enum bigger than one byte");
817 PERFETTO_EINTR(write(background_wait_pipe_.wr.get(), &status, 1));
818 background_wait_pipe_.wr.reset();
819 #else // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
820 base::ignore_result(status);
821 #endif //! PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
822 }
823
WaitOnBgProcessPipe()824 PerfettoCmd::BgProcessStatus PerfettoCmd::WaitOnBgProcessPipe() {
825 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
826 base::ScopedPlatformHandle fd = std::move(background_wait_pipe_.rd);
827 PERFETTO_CHECK(fd);
828
829 BgProcessStatus msg;
830 static_assert(sizeof msg == 1, "Enum bigger than one byte");
831 std::array<pollfd, 1> pollfds = {pollfd{fd.get(), POLLIN, 0}};
832
833 int ret = PERFETTO_EINTR(poll(&pollfds[0], pollfds.size(), 30000 /*ms*/));
834 PERFETTO_CHECK(ret >= 0);
835 if (ret == 0) {
836 fprintf(stderr, "Timeout waiting for all data sources to start\n");
837 return kBackgroundTimeout;
838 }
839 ssize_t read_ret = PERFETTO_EINTR(read(fd.get(), &msg, 1));
840 PERFETTO_CHECK(read_ret >= 0);
841 if (read_ret == 0) {
842 fprintf(stderr, "Background process didn't report anything\n");
843 return kBackgroundOtherError;
844 }
845
846 if (msg != kBackgroundOk) {
847 fprintf(stderr, "Background process failed, BgProcessStatus=%d\n",
848 static_cast<int>(msg));
849 return msg;
850 }
851 #endif //! PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
852
853 return kBackgroundOk;
854 }
855
ConnectToServiceRunAndMaybeNotify()856 int PerfettoCmd::ConnectToServiceRunAndMaybeNotify() {
857 int exit_code = ConnectToServiceAndRun();
858
859 NotifyBgProcessPipe(exit_code == 0 ? kBackgroundOk : kBackgroundOtherError);
860
861 return exit_code;
862 }
863
ConnectToServiceAndRun()864 int PerfettoCmd::ConnectToServiceAndRun() {
865 // If we are just activating triggers then we don't need to rate limit,
866 // connect as a consumer or run the trace. So bail out after processing all
867 // the options.
868 if (!triggers_to_activate_.empty()) {
869 LogTriggerEvents(PerfettoTriggerAtom::kCmdTrigger, triggers_to_activate_);
870
871 bool finished_with_success = false;
872 TriggerProducer producer(
873 &task_runner_,
874 [this, &finished_with_success](bool success) {
875 finished_with_success = success;
876 task_runner_.Quit();
877 },
878 &triggers_to_activate_);
879 task_runner_.Run();
880 if (!finished_with_success) {
881 LogTriggerEvents(PerfettoTriggerAtom::kCmdTriggerFail,
882 triggers_to_activate_);
883 }
884 return finished_with_success ? 0 : 1;
885 } // if (triggers_to_activate_)
886
887 if (query_service_ || bugreport_) {
888 consumer_endpoint_ =
889 ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
890 task_runner_.Run();
891 return 1; // We can legitimately get here if the service disconnects.
892 } // if (query_service || bugreport_)
893
894 RateLimiter::Args args{};
895 args.is_user_build = IsUserBuild();
896 args.is_uploading = save_to_incidentd_ || report_to_android_framework_;
897 args.current_time = base::GetWallTimeS();
898 args.ignore_guardrails = ignore_guardrails_;
899 args.allow_user_build_tracing = trace_config_->allow_user_build_tracing();
900 args.unique_session_name = trace_config_->unique_session_name();
901 args.max_upload_bytes_override =
902 trace_config_->guardrail_overrides().max_upload_per_day_bytes();
903
904 if (!args.unique_session_name.empty())
905 base::MaybeSetThreadName("p-" + args.unique_session_name);
906
907 expected_duration_ms_ = trace_config_->duration_ms();
908 if (!expected_duration_ms_) {
909 uint32_t timeout_ms = trace_config_->trigger_config().trigger_timeout_ms();
910 uint32_t max_stop_delay_ms = 0;
911 for (const auto& trigger : trace_config_->trigger_config().triggers()) {
912 max_stop_delay_ms = std::max(max_stop_delay_ms, trigger.stop_delay_ms());
913 }
914 expected_duration_ms_ = timeout_ms + max_stop_delay_ms;
915 }
916
917 const auto& delay = trace_config_->cmd_trace_start_delay();
918 if (delay.has_min_delay_ms()) {
919 PERFETTO_DCHECK(delay.has_max_delay_ms());
920 std::random_device r;
921 std::minstd_rand minstd(r());
922 std::uniform_int_distribution<uint32_t> dist(delay.min_delay_ms(),
923 delay.max_delay_ms());
924 std::this_thread::sleep_for(std::chrono::milliseconds(dist(minstd)));
925 }
926
927 if (trace_config_->trigger_config().trigger_timeout_ms() == 0) {
928 LogUploadEvent(PerfettoStatsdAtom::kTraceBegin);
929 } else {
930 LogUploadEvent(PerfettoStatsdAtom::kBackgroundTraceBegin);
931 }
932
933 auto err_atom = ConvertRateLimiterResponseToAtom(limiter_->ShouldTrace(args));
934 if (err_atom) {
935 LogUploadEvent(err_atom.value());
936 return 1;
937 }
938
939 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
940 if (!background_ && !is_detach() && !upload_flag_ &&
941 triggers_to_activate_.empty() && !isatty(STDIN_FILENO) &&
942 !isatty(STDERR_FILENO)) {
943 fprintf(stderr,
944 "Warning: No PTY. CTRL+C won't gracefully stop the trace. If you "
945 "are running perfetto via adb shell, use the -tt arg (adb shell "
946 "-t perfetto ...) or consider using the helper script "
947 "tools/record_android_trace from the Perfetto repository.\n\n");
948 }
949 #endif
950
951 consumer_endpoint_ =
952 ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
953 SetupCtrlCSignalHandler();
954 task_runner_.Run();
955
956 return limiter_->OnTraceDone(args, update_guardrail_state_, bytes_written_)
957 ? 0
958 : 1;
959 }
960
OnConnect()961 void PerfettoCmd::OnConnect() {
962 LogUploadEvent(PerfettoStatsdAtom::kOnConnect);
963
964 if (background_wait_) {
965 consumer_endpoint_->ObserveEvents(
966 perfetto::ObservableEvents::TYPE_ALL_DATA_SOURCES_STARTED);
967 }
968
969 if (query_service_) {
970 consumer_endpoint_->QueryServiceState(
971 [this](bool success, const TracingServiceState& svc_state) {
972 PrintServiceState(success, svc_state);
973 fflush(stdout);
974 exit(success ? 0 : 1);
975 });
976 return;
977 }
978
979 if (bugreport_) {
980 consumer_endpoint_->SaveTraceForBugreport(
981 [](bool success, const std::string& msg) {
982 if (success) {
983 PERFETTO_ILOG("Trace saved into %s", msg.c_str());
984 exit(0);
985 }
986 PERFETTO_ELOG("%s", msg.c_str());
987 exit(1);
988 });
989 return;
990 }
991
992 if (is_attach()) {
993 consumer_endpoint_->Attach(attach_key_);
994 return;
995 }
996
997 if (expected_duration_ms_) {
998 PERFETTO_LOG("Connected to the Perfetto traced service, TTL: %ds",
999 (expected_duration_ms_ + 999) / 1000);
1000 } else {
1001 PERFETTO_LOG("Connected to the Perfetto traced service, starting tracing");
1002 }
1003
1004 PERFETTO_DCHECK(trace_config_);
1005 trace_config_->set_enable_extra_guardrails(
1006 (save_to_incidentd_ || report_to_android_framework_) &&
1007 !ignore_guardrails_);
1008
1009 // Set the statsd logging flag if we're uploading
1010
1011 base::ScopedFile optional_fd;
1012 if (trace_config_->write_into_file() && trace_config_->output_path().empty())
1013 optional_fd.reset(dup(fileno(*trace_out_stream_)));
1014
1015 consumer_endpoint_->EnableTracing(*trace_config_, std::move(optional_fd));
1016
1017 if (is_detach()) {
1018 consumer_endpoint_->Detach(detach_key_); // Will invoke OnDetach() soon.
1019 return;
1020 }
1021
1022 // Failsafe mechanism to avoid waiting indefinitely if the service hangs.
1023 if (expected_duration_ms_) {
1024 uint32_t trace_timeout = expected_duration_ms_ + 60000 +
1025 trace_config_->flush_timeout_ms() +
1026 trace_config_->data_source_stop_timeout_ms();
1027 task_runner_.PostDelayedTask(std::bind(&PerfettoCmd::OnTimeout, this),
1028 trace_timeout);
1029 }
1030 }
1031
OnDisconnect()1032 void PerfettoCmd::OnDisconnect() {
1033 PERFETTO_LOG("Disconnected from the Perfetto traced service");
1034 task_runner_.Quit();
1035 }
1036
OnTimeout()1037 void PerfettoCmd::OnTimeout() {
1038 PERFETTO_ELOG("Timed out while waiting for trace from the service, aborting");
1039 LogUploadEvent(PerfettoStatsdAtom::kOnTimeout);
1040 task_runner_.Quit();
1041 }
1042
CheckTraceDataTimeout()1043 void PerfettoCmd::CheckTraceDataTimeout() {
1044 if (trace_data_timeout_armed_) {
1045 PERFETTO_ELOG("Timed out while waiting for OnTraceData, aborting");
1046 FinalizeTraceAndExit();
1047 }
1048 trace_data_timeout_armed_ = true;
1049 task_runner_.PostDelayedTask(
1050 std::bind(&PerfettoCmd::CheckTraceDataTimeout, this),
1051 kOnTraceDataTimeoutMs);
1052 }
1053
OnTraceData(std::vector<TracePacket> packets,bool has_more)1054 void PerfettoCmd::OnTraceData(std::vector<TracePacket> packets, bool has_more) {
1055 trace_data_timeout_armed_ = false;
1056
1057 if (!packet_writer_->WritePackets(packets)) {
1058 PERFETTO_ELOG("Failed to write packets");
1059 FinalizeTraceAndExit();
1060 }
1061
1062 if (!has_more)
1063 FinalizeTraceAndExit(); // Reached end of trace.
1064 }
1065
OnTracingDisabled(const std::string & error)1066 void PerfettoCmd::OnTracingDisabled(const std::string& error) {
1067 if (!error.empty()) {
1068 // Some of these errors (e.g. unique session name already exists) are soft
1069 // errors and likely to happen in nominal condition. As such they shouldn't
1070 // be marked as "E" in the event log. Hence why LOG and not ELOG here.
1071 PERFETTO_LOG("Service error: %s", error.c_str());
1072
1073 // Update guardrail state even if we failed. This is for two
1074 // reasons:
1075 // 1. Keeps compatibility with pre-stats code which used to
1076 // ignore errors from the service and always update state.
1077 // 2. We want to prevent failure storms and the guardrails help
1078 // by preventing tracing too frequently with the same session.
1079 update_guardrail_state_ = true;
1080 task_runner_.Quit();
1081 return;
1082 }
1083
1084 // Make sure to only log this atom if |error| is empty; traced
1085 // would have logged a terminal error atom corresponding to |error|
1086 // and we don't want to log anything after that.
1087 LogUploadEvent(PerfettoStatsdAtom::kOnTracingDisabled);
1088
1089 if (trace_config_->write_into_file()) {
1090 // If write_into_file == true, at this point the passed file contains
1091 // already all the packets.
1092 return FinalizeTraceAndExit();
1093 }
1094
1095 trace_data_timeout_armed_ = false;
1096 CheckTraceDataTimeout();
1097
1098 // This will cause a bunch of OnTraceData callbacks. The last one will
1099 // save the file and exit.
1100 consumer_endpoint_->ReadBuffers();
1101 }
1102
FinalizeTraceAndExit()1103 void PerfettoCmd::FinalizeTraceAndExit() {
1104 LogUploadEvent(PerfettoStatsdAtom::kFinalizeTraceAndExit);
1105 packet_writer_.reset();
1106
1107 if (trace_out_stream_) {
1108 fseek(*trace_out_stream_, 0, SEEK_END);
1109 off_t sz = ftell(*trace_out_stream_);
1110 if (sz > 0)
1111 bytes_written_ = static_cast<size_t>(sz);
1112 }
1113
1114 if (save_to_incidentd_) {
1115 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1116 SaveTraceIntoIncidentOrCrash();
1117 #endif
1118 } else if (report_to_android_framework_) {
1119 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1120 ReportTraceToAndroidFrameworkOrCrash();
1121 #endif
1122 } else {
1123 trace_out_stream_.reset();
1124 if (trace_config_->write_into_file()) {
1125 // trace_out_path_ might be empty in the case of --attach.
1126 PERFETTO_LOG("Trace written into the output file");
1127 } else {
1128 PERFETTO_LOG("Wrote %" PRIu64 " bytes into %s", bytes_written_,
1129 trace_out_path_ == "-" ? "stdout" : trace_out_path_.c_str());
1130 }
1131 }
1132
1133 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1134 // When multiple traces are being recorded at the same time, this is used to
1135 // correlate one trace with another.
1136 ReportFinalizeTraceUuidToAtrace(base::Uuid(uuid_));
1137 #endif
1138
1139 update_guardrail_state_ = true;
1140 task_runner_.Quit();
1141 }
1142
OpenOutputFile()1143 bool PerfettoCmd::OpenOutputFile() {
1144 base::ScopedFile fd;
1145 if (trace_out_path_.empty()) {
1146 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1147 fd = CreateUnlinkedTmpFile();
1148 #endif
1149 } else if (trace_out_path_ == "-") {
1150 fd.reset(dup(fileno(stdout)));
1151 } else {
1152 fd = base::OpenFile(trace_out_path_, O_RDWR | O_CREAT | O_TRUNC, 0600);
1153 }
1154 if (!fd) {
1155 PERFETTO_PLOG(
1156 "Failed to open %s. If you get permission denied in "
1157 "/data/misc/perfetto-traces, the file might have been "
1158 "created by another user, try deleting it first.",
1159 trace_out_path_.c_str());
1160 return false;
1161 }
1162 trace_out_stream_.reset(fdopen(fd.release(), "wb"));
1163 PERFETTO_CHECK(trace_out_stream_);
1164 return true;
1165 }
1166
SetupCtrlCSignalHandler()1167 void PerfettoCmd::SetupCtrlCSignalHandler() {
1168 base::InstallCtrCHandler([] { g_perfetto_cmd->SignalCtrlC(); });
1169 task_runner_.AddFileDescriptorWatch(ctrl_c_evt_.fd(), [this] {
1170 PERFETTO_LOG("SIGINT/SIGTERM received: disabling tracing.");
1171 ctrl_c_evt_.Clear();
1172 consumer_endpoint_->Flush(0, [this](bool flush_success) {
1173 if (!flush_success)
1174 PERFETTO_ELOG("Final flush unsuccessful.");
1175 consumer_endpoint_->DisableTracing();
1176 });
1177 });
1178 }
1179
OnDetach(bool success)1180 void PerfettoCmd::OnDetach(bool success) {
1181 if (!success) {
1182 PERFETTO_ELOG("Session detach failed");
1183 exit(1);
1184 }
1185 exit(0);
1186 }
1187
OnAttach(bool success,const TraceConfig & trace_config)1188 void PerfettoCmd::OnAttach(bool success, const TraceConfig& trace_config) {
1189 if (!success) {
1190 if (!redetach_once_attached_) {
1191 // Print an error message if attach fails, with the exception of the
1192 // --is_detached case, where we want to silently return.
1193 PERFETTO_ELOG("Session re-attach failed. Check service logs for details");
1194 }
1195 // Keep this exit code distinguishable from the general error code so
1196 // --is_detached can tell the difference between a general error and the
1197 // not-detached case.
1198 exit(2);
1199 }
1200
1201 if (redetach_once_attached_) {
1202 consumer_endpoint_->Detach(attach_key_); // Will invoke OnDetach() soon.
1203 return;
1204 }
1205
1206 trace_config_.reset(new TraceConfig(trace_config));
1207 PERFETTO_DCHECK(trace_config_->write_into_file());
1208
1209 if (stop_trace_once_attached_) {
1210 consumer_endpoint_->Flush(0, [this](bool flush_success) {
1211 if (!flush_success)
1212 PERFETTO_ELOG("Final flush unsuccessful.");
1213 consumer_endpoint_->DisableTracing();
1214 });
1215 }
1216 }
1217
OnTraceStats(bool,const TraceStats &)1218 void PerfettoCmd::OnTraceStats(bool /*success*/,
1219 const TraceStats& /*trace_config*/) {
1220 // TODO(eseckler): Support GetTraceStats().
1221 }
1222
PrintServiceState(bool success,const TracingServiceState & svc_state)1223 void PerfettoCmd::PrintServiceState(bool success,
1224 const TracingServiceState& svc_state) {
1225 if (!success) {
1226 PERFETTO_ELOG("Failed to query the service state");
1227 return;
1228 }
1229
1230 if (query_service_output_raw_) {
1231 std::string str = svc_state.SerializeAsString();
1232 fwrite(str.data(), 1, str.size(), stdout);
1233 return;
1234 }
1235
1236 printf(
1237 "\x1b[31mNot meant for machine consumption. Use --query-raw for "
1238 "scripts.\x1b[0m\n\n");
1239 printf(
1240 "Service: %s\n"
1241 "Tracing sessions: %d (started: %d)\n",
1242 svc_state.tracing_service_version().c_str(), svc_state.num_sessions(),
1243 svc_state.num_sessions_started());
1244
1245 printf(R"(
1246
1247 PRODUCER PROCESSES CONNECTED:
1248
1249 ID PID UID NAME SDK
1250 == === === ==== ===
1251 )");
1252 for (const auto& producer : svc_state.producers()) {
1253 printf("%-10d %-10d %-10d %-32s %s\n", producer.id(), producer.pid(),
1254 producer.uid(), producer.name().c_str(),
1255 producer.sdk_version().c_str());
1256 }
1257
1258 printf(R"(
1259
1260 DATA SOURCES REGISTERED:
1261
1262 NAME PRODUCER DETAILS
1263 === ======== ========
1264 )");
1265 for (const auto& ds : svc_state.data_sources()) {
1266 char producer_id_and_name[128]{};
1267 const int ds_producer_id = ds.producer_id();
1268 for (const auto& producer : svc_state.producers()) {
1269 if (producer.id() == ds_producer_id) {
1270 base::SprintfTrunc(producer_id_and_name, sizeof(producer_id_and_name),
1271 "%s (%d)", producer.name().c_str(), ds_producer_id);
1272 break;
1273 }
1274 }
1275
1276 printf("%-40s %-40s ", ds.ds_descriptor().name().c_str(),
1277 producer_id_and_name);
1278 // Print the category names for clients using the track event SDK.
1279 if (!ds.ds_descriptor().track_event_descriptor_raw().empty()) {
1280 const std::string& raw = ds.ds_descriptor().track_event_descriptor_raw();
1281 protos::gen::TrackEventDescriptor desc;
1282 if (desc.ParseFromArray(raw.data(), raw.size())) {
1283 for (const auto& cat : desc.available_categories()) {
1284 printf("%s,", cat.name().c_str());
1285 }
1286 }
1287 } else if (!ds.ds_descriptor().ftrace_descriptor_raw().empty()) {
1288 const std::string& raw = ds.ds_descriptor().ftrace_descriptor_raw();
1289 protos::gen::FtraceDescriptor desc;
1290 if (desc.ParseFromArray(raw.data(), raw.size())) {
1291 for (const auto& cat : desc.atrace_categories()) {
1292 printf("%s,", cat.name().c_str());
1293 }
1294 }
1295 }
1296 printf("\n");
1297 } // for data_sources()
1298
1299 if (svc_state.supports_tracing_sessions()) {
1300 printf(R"(
1301
1302 TRACING SESSIONS:
1303
1304 ID UID STATE BUF (#) KB DUR (s) #DS STARTED NAME
1305 === === ===== ========== ======= === ======= ====
1306 )");
1307 for (const auto& sess : svc_state.tracing_sessions()) {
1308 uint32_t buf_tot_kb = 0;
1309 for (uint32_t kb : sess.buffer_size_kb())
1310 buf_tot_kb += kb;
1311 int sec =
1312 static_cast<int>((sess.start_realtime_ns() / 1000000000) % 86400);
1313 int h = sec / 3600;
1314 int m = (sec - (h * 3600)) / 60;
1315 int s = (sec - h * 3600 - m * 60);
1316 printf("%-7" PRIu64 " %-7d %-10s (%d) %-8u %-9u %-4u %02d:%02d:%02d %s\n",
1317 sess.id(), sess.consumer_uid(), sess.state().c_str(),
1318 sess.buffer_size_kb_size(), buf_tot_kb, sess.duration_ms() / 1000,
1319 sess.num_data_sources(), h, m, s,
1320 sess.unique_session_name().c_str());
1321 } // for tracing_sessions()
1322
1323 int sessions_listed = static_cast<int>(svc_state.tracing_sessions().size());
1324 if (sessions_listed != svc_state.num_sessions() &&
1325 base::GetCurrentUserId() != 0) {
1326 printf(
1327 "\n"
1328 "NOTE: Some tracing sessions are not reported in the list above.\n"
1329 "This is likely because they are owned by a different UID.\n"
1330 "If you want to list all session, run again this command as root.\n");
1331 }
1332 } // if (supports_tracing_sessions)
1333 }
1334
OnObservableEvents(const ObservableEvents & observable_events)1335 void PerfettoCmd::OnObservableEvents(
1336 const ObservableEvents& observable_events) {
1337 if (observable_events.all_data_sources_started()) {
1338 NotifyBgProcessPipe(kBackgroundOk);
1339 }
1340 }
1341
LogUploadEvent(PerfettoStatsdAtom atom)1342 void PerfettoCmd::LogUploadEvent(PerfettoStatsdAtom atom) {
1343 if (!statsd_logging_)
1344 return;
1345 base::Uuid uuid(uuid_);
1346 android_stats::MaybeLogUploadEvent(atom, uuid.lsb(), uuid.msb());
1347 }
1348
LogTriggerEvents(PerfettoTriggerAtom atom,const std::vector<std::string> & trigger_names)1349 void PerfettoCmd::LogTriggerEvents(
1350 PerfettoTriggerAtom atom,
1351 const std::vector<std::string>& trigger_names) {
1352 if (!statsd_logging_)
1353 return;
1354 android_stats::MaybeLogTriggerEvents(atom, trigger_names);
1355 }
1356
PerfettoCmdMain(int argc,char ** argv)1357 int PERFETTO_EXPORT_ENTRYPOINT PerfettoCmdMain(int argc, char** argv) {
1358 perfetto::PerfettoCmd cmd;
1359 auto opt_res = cmd.ParseCmdlineAndMaybeDaemonize(argc, argv);
1360 if (opt_res.has_value())
1361 return *opt_res;
1362 return cmd.ConnectToServiceRunAndMaybeNotify();
1363 }
1364
1365 } // namespace perfetto
1366