• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
21 #include <fcntl.h>
22 #include <stdio.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <time.h>
26 
27 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
28 #include <sys/system_properties.h>
29 #endif  // PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
30 
31 // For dup().
32 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
33 #include <io.h>
34 #else
35 #include <unistd.h>
36 #endif
37 
38 #include <fstream>
39 #include <iostream>
40 #include <iterator>
41 #include <sstream>
42 
43 #include "perfetto/base/compiler.h"
44 #include "perfetto/base/logging.h"
45 #include "perfetto/base/time.h"
46 #include "perfetto/ext/base/ctrl_c_handler.h"
47 #include "perfetto/ext/base/file_utils.h"
48 #include "perfetto/ext/base/getopt.h"
49 #include "perfetto/ext/base/string_view.h"
50 #include "perfetto/ext/base/thread_utils.h"
51 #include "perfetto/ext/base/utils.h"
52 #include "perfetto/ext/base/uuid.h"
53 #include "perfetto/ext/base/version.h"
54 #include "perfetto/ext/traced/traced.h"
55 #include "perfetto/ext/tracing/core/basic_types.h"
56 #include "perfetto/ext/tracing/core/trace_packet.h"
57 #include "perfetto/ext/tracing/ipc/default_socket.h"
58 #include "perfetto/protozero/proto_utils.h"
59 #include "perfetto/tracing/core/data_source_descriptor.h"
60 #include "perfetto/tracing/core/trace_config.h"
61 #include "perfetto/tracing/core/tracing_service_state.h"
62 #include "src/android_stats/statsd_logging_helper.h"
63 #include "src/perfetto_cmd/config.h"
64 #include "src/perfetto_cmd/packet_writer.h"
65 #include "src/perfetto_cmd/pbtxt_to_pb.h"
66 #include "src/perfetto_cmd/trigger_producer.h"
67 
68 #include "protos/perfetto/common/tracing_service_state.gen.h"
69 
70 namespace perfetto {
71 namespace {
72 
73 perfetto::PerfettoCmd* g_consumer_cmd;
74 
75 uint32_t kOnTraceDataTimeoutMs = 3000;
76 
77 class LoggingErrorReporter : public ErrorReporter {
78  public:
LoggingErrorReporter(std::string file_name,const char * config)79   LoggingErrorReporter(std::string file_name, const char* config)
80       : file_name_(file_name), config_(config) {}
81 
AddError(size_t row,size_t column,size_t length,const std::string & message)82   void AddError(size_t row,
83                 size_t column,
84                 size_t length,
85                 const std::string& message) override {
86     parsed_successfully_ = false;
87     std::string line = ExtractLine(row - 1).ToStdString();
88     if (!line.empty() && line[line.length() - 1] == '\n') {
89       line.erase(line.length() - 1);
90     }
91 
92     std::string guide(column + length, ' ');
93     for (size_t i = column; i < column + length; i++) {
94       guide[i - 1] = i == column ? '^' : '~';
95     }
96     fprintf(stderr, "%s:%zu:%zu error: %s\n", file_name_.c_str(), row, column,
97             message.c_str());
98     fprintf(stderr, "%s\n", line.c_str());
99     fprintf(stderr, "%s\n", guide.c_str());
100   }
101 
Success() const102   bool Success() const { return parsed_successfully_; }
103 
104  private:
ExtractLine(size_t line)105   base::StringView ExtractLine(size_t line) {
106     const char* start = config_;
107     const char* end = config_;
108 
109     for (size_t i = 0; i < line + 1; i++) {
110       start = end;
111       char c;
112       while ((c = *end++) && c != '\n')
113         ;
114     }
115     return base::StringView(start, static_cast<size_t>(end - start));
116   }
117 
118   bool parsed_successfully_ = true;
119   std::string file_name_;
120   const char* config_;
121 };
122 
ParseTraceConfigPbtxt(const std::string & file_name,const std::string & pbtxt,TraceConfig * config)123 bool ParseTraceConfigPbtxt(const std::string& file_name,
124                            const std::string& pbtxt,
125                            TraceConfig* config) {
126   LoggingErrorReporter reporter(file_name, pbtxt.c_str());
127   std::vector<uint8_t> buf = PbtxtToPb(pbtxt, &reporter);
128   if (!reporter.Success())
129     return false;
130   if (!config->ParseFromArray(buf.data(), buf.size()))
131     return false;
132   return true;
133 }
134 
IsUserBuild()135 bool IsUserBuild() {
136 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
137   char value[PROP_VALUE_MAX];
138   if (!__system_property_get("ro.build.type", value)) {
139     PERFETTO_ELOG("Unable to read ro.build.type: assuming user build");
140     return true;
141   }
142   return strcmp(value, "user") == 0;
143 #else
144   return false;
145 #endif  // PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
146 }
147 
ConvertRateLimiterResponseToAtom(RateLimiter::ShouldTraceResponse resp)148 base::Optional<PerfettoStatsdAtom> ConvertRateLimiterResponseToAtom(
149     RateLimiter::ShouldTraceResponse resp) {
150   switch (resp) {
151     case RateLimiter::kNotAllowedOnUserBuild:
152       return PerfettoStatsdAtom::kCmdUserBuildTracingNotAllowed;
153     case RateLimiter::kFailedToInitState:
154       return PerfettoStatsdAtom::kCmdFailedToInitGuardrailState;
155     case RateLimiter::kInvalidState:
156       return PerfettoStatsdAtom::kCmdInvalidGuardrailState;
157     case RateLimiter::kHitUploadLimit:
158       return PerfettoStatsdAtom::kCmdHitUploadLimit;
159     case RateLimiter::kOkToTrace:
160       return base::nullopt;
161   }
162   PERFETTO_FATAL("For GCC");
163 }
164 
165 }  // namespace
166 
167 const char* kStateDir = "/data/misc/perfetto-traces";
168 
PrintUsage(const char * argv0)169 int PerfettoCmd::PrintUsage(const char* argv0) {
170   PERFETTO_ELOG(R"(
171 Usage: %s
172   --background     -d      : Exits immediately and continues tracing in
173                              background
174   --config         -c      : /path/to/trace/config/file or - for stdin
175   --out            -o      : /path/to/out/trace/file or - for stdout
176   --upload                 : Upload field trace (Android only)
177   --dropbox        TAG     : DEPRECATED: Use --upload instead
178                              TAG should always be set to 'perfetto'
179   --no-guardrails          : Ignore guardrails triggered when using --upload
180                              (for testing).
181   --txt                    : Parse config as pbtxt. Not for production use.
182                              Not a stable API.
183   --reset-guardrails       : Resets the state of the guardails and exits
184                              (for testing).
185   --query                  : Queries the service state and prints it as
186                              human-readable text.
187   --query-raw              : Like --query, but prints raw proto-encoded bytes
188                              of tracing_service_state.proto.
189   --save-for-bugreport     : If a trace with bugreport_score > 0 is running, it
190                              saves it into a file. Outputs the path when done.
191   --help           -h
192 
193 
194 light configuration flags: (only when NOT using -c/--config)
195   --time           -t      : Trace duration N[s,m,h] (default: 10s)
196   --buffer         -b      : Ring buffer size N[mb,gb] (default: 32mb)
197   --size           -s      : Max file size N[mb,gb] (default: in-memory ring-buffer only)
198   --app            -a      : Android (atrace) app name
199   ATRACE_CAT               : Record ATRACE_CAT (e.g. wm)
200   FTRACE_GROUP/FTRACE_NAME : Record ftrace event (e.g. sched/sched_switch)
201 
202 statsd-specific flags:
203   --alert-id           : ID of the alert that triggered this trace.
204   --config-id          : ID of the triggering config.
205   --config-uid         : UID of app which registered the config.
206   --subscription-id    : ID of the subscription that triggered this trace.
207 
208 Detach mode. DISCOURAGED, read https://perfetto.dev/docs/concepts/detached-mode :
209   --detach=key          : Detach from the tracing session with the given key.
210   --attach=key [--stop] : Re-attach to the session (optionally stop tracing once reattached).
211   --is_detached=key     : Check if the session can be re-attached (0:Yes, 2:No, 1:Error).
212 )", /* this comment fixes syntax highlighting in some editors */
213                 argv0);
214   return 1;
215 }
216 
Main(int argc,char ** argv)217 int PerfettoCmd::Main(int argc, char** argv) {
218 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
219   umask(0000);  // make sure that file creation is not affected by umask.
220 #endif
221   enum LongOption {
222     OPT_ALERT_ID = 1000,
223     OPT_BUGREPORT,
224     OPT_CONFIG_ID,
225     OPT_CONFIG_UID,
226     OPT_SUBSCRIPTION_ID,
227     OPT_RESET_GUARDRAILS,
228     OPT_PBTXT_CONFIG,
229     OPT_DROPBOX,
230     OPT_UPLOAD,
231     OPT_IGNORE_GUARDRAILS,
232     OPT_DETACH,
233     OPT_ATTACH,
234     OPT_IS_DETACHED,
235     OPT_STOP,
236     OPT_QUERY,
237     OPT_QUERY_RAW,
238     OPT_VERSION,
239   };
240   static const option long_options[] = {
241       {"help", no_argument, nullptr, 'h'},
242       {"config", required_argument, nullptr, 'c'},
243       {"out", required_argument, nullptr, 'o'},
244       {"background", no_argument, nullptr, 'd'},
245       {"time", required_argument, nullptr, 't'},
246       {"buffer", required_argument, nullptr, 'b'},
247       {"size", required_argument, nullptr, 's'},
248       {"app", required_argument, nullptr, 'a'},
249       {"no-guardrails", no_argument, nullptr, OPT_IGNORE_GUARDRAILS},
250       {"txt", no_argument, nullptr, OPT_PBTXT_CONFIG},
251       {"upload", no_argument, nullptr, OPT_UPLOAD},
252       {"dropbox", required_argument, nullptr, OPT_DROPBOX},
253       {"alert-id", required_argument, nullptr, OPT_ALERT_ID},
254       {"config-id", required_argument, nullptr, OPT_CONFIG_ID},
255       {"config-uid", required_argument, nullptr, OPT_CONFIG_UID},
256       {"subscription-id", required_argument, nullptr, OPT_SUBSCRIPTION_ID},
257       {"reset-guardrails", no_argument, nullptr, OPT_RESET_GUARDRAILS},
258       {"detach", required_argument, nullptr, OPT_DETACH},
259       {"attach", required_argument, nullptr, OPT_ATTACH},
260       {"is_detached", required_argument, nullptr, OPT_IS_DETACHED},
261       {"stop", no_argument, nullptr, OPT_STOP},
262       {"query", no_argument, nullptr, OPT_QUERY},
263       {"query-raw", no_argument, nullptr, OPT_QUERY_RAW},
264       {"version", no_argument, nullptr, OPT_VERSION},
265       {"save-for-bugreport", no_argument, nullptr, OPT_BUGREPORT},
266       {nullptr, 0, nullptr, 0}};
267 
268   std::string config_file_name;
269   std::string trace_config_raw;
270   bool background = false;
271   bool ignore_guardrails = false;
272   bool parse_as_pbtxt = false;
273   bool upload_flag = false;
274   TraceConfig::StatsdMetadata statsd_metadata;
275   RateLimiter limiter;
276 
277   ConfigOptions config_options;
278   bool has_config_options = false;
279 
280   for (;;) {
281     int option =
282         getopt_long(argc, argv, "hc:o:dt:b:s:a:", long_options, nullptr);
283 
284     if (option == -1)
285       break;  // EOF.
286 
287     if (option == 'c') {
288       config_file_name = std::string(optarg);
289       if (strcmp(optarg, "-") == 0) {
290         std::istreambuf_iterator<char> begin(std::cin), end;
291         trace_config_raw.assign(begin, end);
292       } else if (strcmp(optarg, ":test") == 0) {
293         TraceConfig test_config;
294         ConfigOptions opts;
295         opts.time = "2s";
296         opts.categories.emplace_back("sched/sched_switch");
297         opts.categories.emplace_back("power/cpu_idle");
298         opts.categories.emplace_back("power/cpu_frequency");
299         opts.categories.emplace_back("power/gpu_frequency");
300         PERFETTO_CHECK(CreateConfigFromOptions(opts, &test_config));
301         trace_config_raw = test_config.SerializeAsString();
302       } else {
303         if (!base::ReadFile(optarg, &trace_config_raw)) {
304           PERFETTO_PLOG("Could not open %s", optarg);
305           return 1;
306         }
307       }
308       continue;
309     }
310 
311     if (option == 'o') {
312       trace_out_path_ = optarg;
313       continue;
314     }
315 
316     if (option == 'd') {
317       background = true;
318       continue;
319     }
320     if (option == 't') {
321       has_config_options = true;
322       config_options.time = std::string(optarg);
323       continue;
324     }
325 
326     if (option == 'b') {
327       has_config_options = true;
328       config_options.buffer_size = std::string(optarg);
329       continue;
330     }
331 
332     if (option == 's') {
333       has_config_options = true;
334       config_options.max_file_size = std::string(optarg);
335       continue;
336     }
337 
338     if (option == 'a') {
339       config_options.atrace_apps.push_back(std::string(optarg));
340       has_config_options = true;
341       continue;
342     }
343 
344     if (option == OPT_UPLOAD) {
345 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
346       upload_flag = true;
347       continue;
348 #else
349       PERFETTO_ELOG("--upload is only supported on Android");
350       return 1;
351 #endif
352     }
353 
354     if (option == OPT_DROPBOX) {
355 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
356       PERFETTO_CHECK(optarg);
357       upload_flag = true;
358       continue;
359 #else
360       PERFETTO_ELOG("--dropbox is only supported on Android");
361       return 1;
362 #endif
363     }
364 
365     if (option == OPT_PBTXT_CONFIG) {
366       parse_as_pbtxt = true;
367       continue;
368     }
369 
370     if (option == OPT_IGNORE_GUARDRAILS) {
371       ignore_guardrails = true;
372       continue;
373     }
374 
375     if (option == OPT_RESET_GUARDRAILS) {
376       PERFETTO_CHECK(limiter.ClearState());
377       PERFETTO_ILOG("Guardrail state cleared");
378       return 0;
379     }
380 
381     if (option == OPT_ALERT_ID) {
382       statsd_metadata.set_triggering_alert_id(atoll(optarg));
383       continue;
384     }
385 
386     if (option == OPT_CONFIG_ID) {
387       statsd_metadata.set_triggering_config_id(atoll(optarg));
388       continue;
389     }
390 
391     if (option == OPT_CONFIG_UID) {
392       statsd_metadata.set_triggering_config_uid(atoi(optarg));
393       continue;
394     }
395 
396     if (option == OPT_SUBSCRIPTION_ID) {
397       statsd_metadata.set_triggering_subscription_id(atoll(optarg));
398       continue;
399     }
400 
401     if (option == OPT_DETACH) {
402       detach_key_ = std::string(optarg);
403       PERFETTO_CHECK(!detach_key_.empty());
404       continue;
405     }
406 
407     if (option == OPT_ATTACH) {
408       attach_key_ = std::string(optarg);
409       PERFETTO_CHECK(!attach_key_.empty());
410       continue;
411     }
412 
413     if (option == OPT_IS_DETACHED) {
414       attach_key_ = std::string(optarg);
415       redetach_once_attached_ = true;
416       PERFETTO_CHECK(!attach_key_.empty());
417       continue;
418     }
419 
420     if (option == OPT_STOP) {
421       stop_trace_once_attached_ = true;
422       continue;
423     }
424 
425     if (option == OPT_QUERY) {
426       query_service_ = true;
427       continue;
428     }
429 
430     if (option == OPT_QUERY_RAW) {
431       query_service_ = true;
432       query_service_output_raw_ = true;
433       continue;
434     }
435 
436     if (option == OPT_VERSION) {
437       printf("%s\n", base::GetVersionString());
438       return 0;
439     }
440 
441     if (option == OPT_BUGREPORT) {
442       bugreport_ = true;
443       continue;
444     }
445 
446     return PrintUsage(argv[0]);
447   }
448 
449   for (ssize_t i = optind; i < argc; i++) {
450     has_config_options = true;
451     config_options.categories.push_back(argv[i]);
452   }
453 
454   if (query_service_ && (is_detach() || is_attach() || background)) {
455     PERFETTO_ELOG("--query cannot be combined with any other argument");
456     return 1;
457   }
458 
459   if (is_detach() && is_attach()) {
460     PERFETTO_ELOG("--attach and --detach are mutually exclusive");
461     return 1;
462   }
463 
464   if (is_detach() && background) {
465     PERFETTO_ELOG("--detach and --background are mutually exclusive");
466     return 1;
467   }
468 
469   if (stop_trace_once_attached_ && !is_attach()) {
470     PERFETTO_ELOG("--stop is supported only in combination with --attach");
471     return 1;
472   }
473 
474   if (bugreport_ &&
475       (is_attach() | is_detach() || query_service_ || has_config_options)) {
476     PERFETTO_ELOG("--save-for-bugreport cannot take any other argument");
477     return 1;
478   }
479 
480   // Parse the trace config. It can be either:
481   // 1) A proto-encoded file/stdin (-c ...).
482   // 2) A proto-text file/stdin (-c ... --txt).
483   // 3) A set of option arguments (-t 10s -s 10m).
484   // The only cases in which a trace config is not expected is --attach.
485   // For this we are just acting on already existing sessions.
486   trace_config_.reset(new TraceConfig());
487 
488   std::vector<std::string> triggers_to_activate;
489   bool parsed = false;
490   const bool will_trace = !is_attach() && !query_service_ && !bugreport_;
491   if (!will_trace) {
492     if ((!trace_config_raw.empty() || has_config_options)) {
493       PERFETTO_ELOG("Cannot specify a trace config with this option");
494       return 1;
495     }
496   } else if (has_config_options) {
497     if (!trace_config_raw.empty()) {
498       PERFETTO_ELOG(
499           "Cannot specify both -c/--config and any of --time, --size, "
500           "--buffer, --app, ATRACE_CAT, FTRACE_EVENT");
501       return 1;
502     }
503     parsed = CreateConfigFromOptions(config_options, trace_config_.get());
504   } else {
505     if (trace_config_raw.empty()) {
506       PERFETTO_ELOG("The TraceConfig is empty");
507       return 1;
508     }
509     PERFETTO_DLOG("Parsing TraceConfig, %zu bytes", trace_config_raw.size());
510     if (parse_as_pbtxt) {
511       parsed = ParseTraceConfigPbtxt(config_file_name, trace_config_raw,
512                                      trace_config_.get());
513     } else {
514       parsed = trace_config_->ParseFromString(trace_config_raw);
515     }
516   }
517 
518   if (parsed) {
519     *trace_config_->mutable_statsd_metadata() = std::move(statsd_metadata);
520     trace_config_raw.clear();
521   } else if (will_trace) {
522     PERFETTO_ELOG("The trace config is invalid, bailing out.");
523     return 1;
524   }
525 
526   if (trace_config_->trace_uuid_lsb() == 0 &&
527       trace_config_->trace_uuid_msb() == 0) {
528     base::Uuid uuid = base::Uuidv4();
529     if (trace_config_->statsd_metadata().triggering_subscription_id()) {
530       uuid.set_lsb(
531           trace_config_->statsd_metadata().triggering_subscription_id());
532     }
533     uuid_ = uuid.ToString();
534     trace_config_->set_trace_uuid_msb(uuid.msb());
535     trace_config_->set_trace_uuid_lsb(uuid.lsb());
536   } else {
537     base::Uuid uuid(trace_config_->trace_uuid_lsb(),
538                     trace_config_->trace_uuid_msb());
539     uuid_ = uuid.ToString();
540   }
541 
542   if (!trace_config_->incident_report_config().destination_package().empty() &&
543       !upload_flag) {
544     PERFETTO_ELOG(
545         "Unexpected IncidentReportConfig without --dropbox / --upload.");
546     return 1;
547   }
548 
549   if (trace_config_->activate_triggers().empty() &&
550       trace_config_->incident_report_config().destination_package().empty() &&
551       !trace_config_->incident_report_config().skip_incidentd() &&
552       upload_flag) {
553     PERFETTO_ELOG(
554         "Missing IncidentReportConfig.destination_package with --dropbox / "
555         "--upload.");
556     return 1;
557   }
558 
559   // Only save to incidentd if both --upload is set and |skip_incidentd| is
560   // absent or false.
561   save_to_incidentd_ =
562       upload_flag && !trace_config_->incident_report_config().skip_incidentd();
563 
564   // Respect the wishes of the config with respect to statsd logging or fall
565   // back on the presence of the --upload flag if not set.
566   switch (trace_config_->statsd_logging()) {
567     case TraceConfig::STATSD_LOGGING_ENABLED:
568       statsd_logging_ = true;
569       break;
570     case TraceConfig::STATSD_LOGGING_DISABLED:
571       statsd_logging_ = false;
572       break;
573     case TraceConfig::STATSD_LOGGING_UNSPECIFIED:
574       statsd_logging_ = upload_flag;
575       break;
576   }
577   trace_config_->set_statsd_logging(statsd_logging_
578                                         ? TraceConfig::STATSD_LOGGING_ENABLED
579                                         : TraceConfig::STATSD_LOGGING_DISABLED);
580 
581   // Set up the output file. Either --out or --upload are expected, with the
582   // only exception of --attach. In this case the output file is passed when
583   // detaching.
584   if (!trace_out_path_.empty() && upload_flag) {
585     PERFETTO_ELOG(
586         "Can't log to a file (--out) and incidentd (--upload) at the same "
587         "time");
588     return 1;
589   }
590 
591   if (!trace_config_->output_path().empty()) {
592     if (!trace_out_path_.empty() || upload_flag) {
593       PERFETTO_ELOG(
594           "Can't pass --out or --upload if output_path is set in the "
595           "trace config");
596       return 1;
597     }
598     if (base::FileExists(trace_config_->output_path())) {
599       PERFETTO_ELOG(
600           "The output_path must not exist, the service cannot overwrite "
601           "existing files for security reasons. Remove %s or use a different "
602           "path.",
603           trace_config_->output_path().c_str());
604       return 1;
605     }
606   }
607 
608   // |activate_triggers| in the trace config is shorthand for trigger_perfetto.
609   // In this case we don't intend to send any trace config to the service,
610   // rather use that as a signal to the cmdline client to connect as a producer
611   // and activate triggers.
612   if (!trace_config_->activate_triggers().empty()) {
613     for (const auto& trigger : trace_config_->activate_triggers()) {
614       triggers_to_activate.push_back(trigger);
615     }
616     trace_config_.reset(new TraceConfig());
617   }
618 
619   bool open_out_file = true;
620   if (!will_trace) {
621     open_out_file = false;
622     if (!trace_out_path_.empty() || upload_flag) {
623       PERFETTO_ELOG("Can't pass an --out file (or --upload) with this option");
624       return 1;
625     }
626   } else if (!triggers_to_activate.empty() ||
627              (trace_config_->write_into_file() &&
628               !trace_config_->output_path().empty())) {
629     open_out_file = false;
630   } else if (trace_out_path_.empty() && !upload_flag) {
631     PERFETTO_ELOG("Either --out or --upload is required");
632     return 1;
633   } else if (is_detach() && !trace_config_->write_into_file()) {
634     // In detached mode we must pass the file descriptor to the service and
635     // let that one write the trace. We cannot use the IPC readback code path
636     // because the client process is about to exit soon after detaching.
637     // We could support detach && !write_into_file, but that would make the
638     // cmdline logic more complex. The feasible configurations are:
639     // 1. Using write_into_file and passing the file path on the --detach call.
640     // 2. Using pure ring-buffer mode, setting write_into_file = false and
641     //    passing the output file path to the --attach call.
642     // This is too complicated and harder to reason about, so we support only 1.
643     // Traceur gets around this by always setting write_into_file and specifying
644     // file_write_period_ms = 1week (which effectively means: write into the
645     // file only at the end of the trace) to achieve ring buffer traces.
646     PERFETTO_ELOG(
647         "TraceConfig's write_into_file must be true when using --detach");
648     return 1;
649   }
650   if (open_out_file) {
651     if (!OpenOutputFile())
652       return 1;
653     if (!trace_config_->write_into_file())
654       packet_writer_ = CreateFilePacketWriter(trace_out_stream_.get());
655   }
656 
657   if (background) {
658     base::Daemonize();
659   }
660 
661   // If we are just activating triggers then we don't need to rate limit,
662   // connect as a consumer or run the trace. So bail out after processing all
663   // the options.
664   if (!triggers_to_activate.empty()) {
665     LogUploadEvent(PerfettoStatsdAtom::kTriggerBegin);
666     LogTriggerEvents(PerfettoTriggerAtom::kCmdTrigger, triggers_to_activate);
667 
668     bool finished_with_success = false;
669     TriggerProducer producer(
670         &task_runner_,
671         [this, &finished_with_success](bool success) {
672           finished_with_success = success;
673           task_runner_.Quit();
674         },
675         &triggers_to_activate);
676     task_runner_.Run();
677     if (finished_with_success) {
678       LogUploadEvent(PerfettoStatsdAtom::kTriggerSuccess);
679     } else {
680       LogUploadEvent(PerfettoStatsdAtom::kTriggerFailure);
681       LogTriggerEvents(PerfettoTriggerAtom::kCmdTriggerFail,
682                        triggers_to_activate);
683     }
684     return finished_with_success ? 0 : 1;
685   }
686 
687   if (query_service_ || bugreport_) {
688     consumer_endpoint_ =
689         ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
690     task_runner_.Run();
691     return 1;  // We can legitimately get here if the service disconnects.
692   }
693 
694   if (trace_config_->compression_type() ==
695       TraceConfig::COMPRESSION_TYPE_DEFLATE) {
696     if (packet_writer_) {
697 #if PERFETTO_BUILDFLAG(PERFETTO_ZLIB)
698       packet_writer_ = CreateZipPacketWriter(std::move(packet_writer_));
699 #else
700       PERFETTO_ELOG("Cannot compress. Zlib not enabled in the build config");
701 #endif
702     } else {
703       PERFETTO_ELOG("Cannot compress when tracing directly to file.");
704     }
705   }
706 
707   RateLimiter::Args args{};
708   args.is_user_build = IsUserBuild();
709   args.is_uploading = save_to_incidentd_;
710   args.current_time = base::GetWallTimeS();
711   args.ignore_guardrails = ignore_guardrails;
712   args.allow_user_build_tracing = trace_config_->allow_user_build_tracing();
713   args.unique_session_name = trace_config_->unique_session_name();
714   args.max_upload_bytes_override =
715       trace_config_->guardrail_overrides().max_upload_per_day_bytes();
716 
717   if (!args.unique_session_name.empty())
718     base::MaybeSetThreadName("p-" + args.unique_session_name);
719 
720   if (args.is_uploading && !args.ignore_guardrails &&
721       (trace_config_->duration_ms() == 0 &&
722        trace_config_->trigger_config().trigger_timeout_ms() == 0)) {
723     PERFETTO_ELOG("Can't trace indefinitely when tracing to Dropbox.");
724     return 1;
725   }
726 
727   expected_duration_ms_ = trace_config_->duration_ms();
728   if (!expected_duration_ms_) {
729     uint32_t timeout_ms = trace_config_->trigger_config().trigger_timeout_ms();
730     uint32_t max_stop_delay_ms = 0;
731     for (const auto& trigger : trace_config_->trigger_config().triggers()) {
732       max_stop_delay_ms = std::max(max_stop_delay_ms, trigger.stop_delay_ms());
733     }
734     expected_duration_ms_ = timeout_ms + max_stop_delay_ms;
735   }
736 
737   if (trace_config_->trigger_config().trigger_timeout_ms() == 0) {
738     LogUploadEvent(PerfettoStatsdAtom::kTraceBegin);
739   } else {
740     LogUploadEvent(PerfettoStatsdAtom::kBackgroundTraceBegin);
741   }
742 
743   auto err_atom = ConvertRateLimiterResponseToAtom(limiter.ShouldTrace(args));
744   if (err_atom) {
745     // TODO(lalitm): remove this once we're ready on server side.
746     LogUploadEvent(PerfettoStatsdAtom::kHitGuardrails);
747     LogUploadEvent(err_atom.value());
748     return 1;
749   }
750 
751   consumer_endpoint_ =
752       ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
753   SetupCtrlCSignalHandler();
754   task_runner_.Run();
755 
756   return limiter.OnTraceDone(args, update_guardrail_state_, bytes_written_) ? 0
757                                                                             : 1;
758 }
759 
OnConnect()760 void PerfettoCmd::OnConnect() {
761   LogUploadEvent(PerfettoStatsdAtom::kOnConnect);
762   if (query_service_) {
763     consumer_endpoint_->QueryServiceState(
764         [this](bool success, const TracingServiceState& svc_state) {
765           PrintServiceState(success, svc_state);
766           fflush(stdout);
767           exit(success ? 0 : 1);
768         });
769     return;
770   }
771 
772   if (bugreport_) {
773     consumer_endpoint_->SaveTraceForBugreport(
774         [](bool success, const std::string& msg) {
775           if (success) {
776             PERFETTO_ILOG("Trace saved into %s", msg.c_str());
777             exit(0);
778           }
779           PERFETTO_ELOG("%s", msg.c_str());
780           exit(1);
781         });
782     return;
783   }
784 
785   if (is_attach()) {
786     consumer_endpoint_->Attach(attach_key_);
787     return;
788   }
789 
790   if (expected_duration_ms_) {
791     PERFETTO_LOG("Connected to the Perfetto traced service, TTL: %ds",
792                  (expected_duration_ms_ + 999) / 1000);
793   } else {
794     PERFETTO_LOG("Connected to the Perfetto traced service, starting tracing");
795   }
796 
797   PERFETTO_DCHECK(trace_config_);
798   trace_config_->set_enable_extra_guardrails(save_to_incidentd_);
799 
800   // Set the statsd logging flag if we're uploading
801 
802   base::ScopedFile optional_fd;
803   if (trace_config_->write_into_file() && trace_config_->output_path().empty())
804     optional_fd.reset(dup(fileno(*trace_out_stream_)));
805 
806   consumer_endpoint_->EnableTracing(*trace_config_, std::move(optional_fd));
807 
808   if (is_detach()) {
809     consumer_endpoint_->Detach(detach_key_);  // Will invoke OnDetach() soon.
810     return;
811   }
812 
813   // Failsafe mechanism to avoid waiting indefinitely if the service hangs.
814   if (expected_duration_ms_) {
815     uint32_t trace_timeout = expected_duration_ms_ + 60000 +
816                              trace_config_->flush_timeout_ms() +
817                              trace_config_->data_source_stop_timeout_ms();
818     task_runner_.PostDelayedTask(std::bind(&PerfettoCmd::OnTimeout, this),
819                                  trace_timeout);
820   }
821 }
822 
OnDisconnect()823 void PerfettoCmd::OnDisconnect() {
824   PERFETTO_LOG("Disconnected from the Perfetto traced service");
825   task_runner_.Quit();
826 }
827 
OnTimeout()828 void PerfettoCmd::OnTimeout() {
829   PERFETTO_ELOG("Timed out while waiting for trace from the service, aborting");
830   LogUploadEvent(PerfettoStatsdAtom::kOnTimeout);
831   task_runner_.Quit();
832 }
833 
CheckTraceDataTimeout()834 void PerfettoCmd::CheckTraceDataTimeout() {
835   if (trace_data_timeout_armed_) {
836     PERFETTO_ELOG("Timed out while waiting for OnTraceData, aborting");
837     FinalizeTraceAndExit();
838   }
839   trace_data_timeout_armed_ = true;
840   task_runner_.PostDelayedTask(
841       std::bind(&PerfettoCmd::CheckTraceDataTimeout, this),
842       kOnTraceDataTimeoutMs);
843 }
844 
OnTraceData(std::vector<TracePacket> packets,bool has_more)845 void PerfettoCmd::OnTraceData(std::vector<TracePacket> packets, bool has_more) {
846   trace_data_timeout_armed_ = false;
847 
848   if (!packet_writer_->WritePackets(packets)) {
849     PERFETTO_ELOG("Failed to write packets");
850     FinalizeTraceAndExit();
851   }
852 
853   if (!has_more)
854     FinalizeTraceAndExit();  // Reached end of trace.
855 }
856 
OnTracingDisabled(const std::string & error)857 void PerfettoCmd::OnTracingDisabled(const std::string& error) {
858   if (!error.empty()) {
859     // Some of these errors (e.g. unique session name already exists) are soft
860     // errors and likely to happen in nominal condition. As such they shouldn't
861     // be marked as "E" in the event log. Hence why LOG and not ELOG here.
862     PERFETTO_LOG("Service error: %s", error.c_str());
863 
864     // Update guardrail state even if we failed. This is for two
865     // reasons:
866     // 1. Keeps compatibility with pre-stats code which used to
867     // ignore errors from the service and always update state.
868     // 2. We want to prevent failure storms and the guardrails help
869     // by preventing tracing too frequently with the same session.
870     update_guardrail_state_ = true;
871     task_runner_.Quit();
872     return;
873   }
874 
875   // Make sure to only log this atom if |error| is empty; traced
876   // would have logged a terminal error atom corresponding to |error|
877   // and we don't want to log anything after that.
878   LogUploadEvent(PerfettoStatsdAtom::kOnTracingDisabled);
879 
880   if (trace_config_->write_into_file()) {
881     // If write_into_file == true, at this point the passed file contains
882     // already all the packets.
883     return FinalizeTraceAndExit();
884   }
885 
886   trace_data_timeout_armed_ = false;
887   CheckTraceDataTimeout();
888 
889   // This will cause a bunch of OnTraceData callbacks. The last one will
890   // save the file and exit.
891   consumer_endpoint_->ReadBuffers();
892 }
893 
FinalizeTraceAndExit()894 void PerfettoCmd::FinalizeTraceAndExit() {
895   LogUploadEvent(PerfettoStatsdAtom::kFinalizeTraceAndExit);
896   packet_writer_.reset();
897 
898   if (trace_out_stream_) {
899     fseek(*trace_out_stream_, 0, SEEK_END);
900     off_t sz = ftell(*trace_out_stream_);
901     if (sz > 0)
902       bytes_written_ = static_cast<size_t>(sz);
903   }
904 
905   if (save_to_incidentd_) {
906 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
907     SaveTraceIntoDropboxAndIncidentOrCrash();
908 #endif
909   } else {
910     trace_out_stream_.reset();
911     if (trace_config_->write_into_file()) {
912       // trace_out_path_ might be empty in the case of --attach.
913       PERFETTO_LOG("Trace written into the output file");
914     } else {
915       PERFETTO_LOG("Wrote %" PRIu64 " bytes into %s", bytes_written_,
916                    trace_out_path_ == "-" ? "stdout" : trace_out_path_.c_str());
917     }
918   }
919 
920   update_guardrail_state_ = true;
921   task_runner_.Quit();
922 }
923 
OpenOutputFile()924 bool PerfettoCmd::OpenOutputFile() {
925   base::ScopedFile fd;
926   if (trace_out_path_.empty()) {
927 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
928     fd = CreateUnlinkedTmpFile();
929 #endif
930   } else if (trace_out_path_ == "-") {
931     fd.reset(dup(fileno(stdout)));
932   } else {
933     fd = base::OpenFile(trace_out_path_, O_RDWR | O_CREAT | O_TRUNC, 0600);
934   }
935   if (!fd) {
936     PERFETTO_PLOG(
937         "Failed to open %s. If you get permission denied in "
938         "/data/misc/perfetto-traces, the file might have been "
939         "created by another user, try deleting it first.",
940         trace_out_path_.c_str());
941     return false;
942   }
943   trace_out_stream_.reset(fdopen(fd.release(), "wb"));
944   PERFETTO_CHECK(trace_out_stream_);
945   return true;
946 }
947 
SetupCtrlCSignalHandler()948 void PerfettoCmd::SetupCtrlCSignalHandler() {
949   base::InstallCtrCHandler([] { g_consumer_cmd->SignalCtrlC(); });
950   task_runner_.AddFileDescriptorWatch(ctrl_c_evt_.fd(), [this] {
951     PERFETTO_LOG("SIGINT/SIGTERM received: disabling tracing.");
952     ctrl_c_evt_.Clear();
953     consumer_endpoint_->Flush(0, [this](bool flush_success) {
954       if (!flush_success)
955         PERFETTO_ELOG("Final flush unsuccessful.");
956       consumer_endpoint_->DisableTracing();
957     });
958   });
959 }
960 
OnDetach(bool success)961 void PerfettoCmd::OnDetach(bool success) {
962   if (!success) {
963     PERFETTO_ELOG("Session detach failed");
964     exit(1);
965   }
966   exit(0);
967 }
968 
OnAttach(bool success,const TraceConfig & trace_config)969 void PerfettoCmd::OnAttach(bool success, const TraceConfig& trace_config) {
970   if (!success) {
971     if (!redetach_once_attached_) {
972       // Print an error message if attach fails, with the exception of the
973       // --is_detached case, where we want to silently return.
974       PERFETTO_ELOG("Session re-attach failed. Check service logs for details");
975     }
976     // Keep this exit code distinguishable from the general error code so
977     // --is_detached can tell the difference between a general error and the
978     // not-detached case.
979     exit(2);
980   }
981 
982   if (redetach_once_attached_) {
983     consumer_endpoint_->Detach(attach_key_);  // Will invoke OnDetach() soon.
984     return;
985   }
986 
987   trace_config_.reset(new TraceConfig(trace_config));
988   PERFETTO_DCHECK(trace_config_->write_into_file());
989 
990   if (stop_trace_once_attached_) {
991     consumer_endpoint_->Flush(0, [this](bool flush_success) {
992       if (!flush_success)
993         PERFETTO_ELOG("Final flush unsuccessful.");
994       consumer_endpoint_->DisableTracing();
995     });
996   }
997 }
998 
OnTraceStats(bool,const TraceStats &)999 void PerfettoCmd::OnTraceStats(bool /*success*/,
1000                                const TraceStats& /*trace_config*/) {
1001   // TODO(eseckler): Support GetTraceStats().
1002 }
1003 
PrintServiceState(bool success,const TracingServiceState & svc_state)1004 void PerfettoCmd::PrintServiceState(bool success,
1005                                     const TracingServiceState& svc_state) {
1006   if (!success) {
1007     PERFETTO_ELOG("Failed to query the service state");
1008     return;
1009   }
1010 
1011   if (query_service_output_raw_) {
1012     std::string str = svc_state.SerializeAsString();
1013     fwrite(str.data(), 1, str.size(), stdout);
1014     return;
1015   }
1016 
1017   printf("Not meant for machine consumption. Use --query-raw for scripts.\n");
1018 
1019   for (const auto& producer : svc_state.producers()) {
1020     printf("producers: {\n");
1021     printf("  id: %d\n", producer.id());
1022     printf("  name: \"%s\" \n", producer.name().c_str());
1023     printf("  uid: %d \n", producer.uid());
1024     printf("  sdk_version: \"%s\" \n", producer.sdk_version().c_str());
1025     printf("}\n");
1026   }
1027 
1028   for (const auto& ds : svc_state.data_sources()) {
1029     printf("data_sources: {\n");
1030     printf("  producer_id: %d\n", ds.producer_id());
1031     printf("  descriptor: {\n");
1032     printf("    name: \"%s\"\n", ds.ds_descriptor().name().c_str());
1033     printf("  }\n");
1034     printf("}\n");
1035   }
1036   printf("tracing_service_version: \"%s\"\n",
1037          svc_state.tracing_service_version().c_str());
1038   printf("num_sessions: %d\n", svc_state.num_sessions());
1039   printf("num_sessions_started: %d\n", svc_state.num_sessions_started());
1040 }
1041 
OnObservableEvents(const ObservableEvents &)1042 void PerfettoCmd::OnObservableEvents(
1043     const ObservableEvents& /*observable_events*/) {}
1044 
LogUploadEvent(PerfettoStatsdAtom atom)1045 void PerfettoCmd::LogUploadEvent(PerfettoStatsdAtom atom) {
1046   if (!statsd_logging_)
1047     return;
1048   base::Uuid uuid(uuid_);
1049   android_stats::MaybeLogUploadEvent(atom, uuid.lsb(), uuid.msb());
1050 }
1051 
LogTriggerEvents(PerfettoTriggerAtom atom,const std::vector<std::string> & trigger_names)1052 void PerfettoCmd::LogTriggerEvents(
1053     PerfettoTriggerAtom atom,
1054     const std::vector<std::string>& trigger_names) {
1055   if (!statsd_logging_)
1056     return;
1057   android_stats::MaybeLogTriggerEvents(atom, trigger_names);
1058 }
1059 
PerfettoCmdMain(int argc,char ** argv)1060 int PERFETTO_EXPORT_ENTRYPOINT PerfettoCmdMain(int argc, char** argv) {
1061   g_consumer_cmd = new perfetto::PerfettoCmd();
1062   return g_consumer_cmd->Main(argc, argv);
1063 }
1064 
1065 }  // namespace perfetto
1066