• 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 <dlfcn.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <sys/stat.h>
25 #include <time.h>
26 #include <unistd.h>
27 
28 #include <fstream>
29 #include <iostream>
30 #include <iterator>
31 #include <sstream>
32 
33 #include "perfetto/base/file_utils.h"
34 #include "perfetto/base/logging.h"
35 #include "perfetto/base/string_view.h"
36 #include "perfetto/base/time.h"
37 #include "perfetto/base/utils.h"
38 #include "perfetto/config/trace_config.pb.h"
39 #include "perfetto/protozero/proto_utils.h"
40 #include "perfetto/traced/traced.h"
41 #include "perfetto/tracing/core/basic_types.h"
42 #include "perfetto/tracing/core/data_source_config.h"
43 #include "perfetto/tracing/core/data_source_descriptor.h"
44 #include "perfetto/tracing/core/trace_config.h"
45 #include "perfetto/tracing/core/trace_packet.h"
46 #include "src/perfetto_cmd/config.h"
47 #include "src/perfetto_cmd/packet_writer.h"
48 #include "src/perfetto_cmd/pbtxt_to_pb.h"
49 #include "src/perfetto_cmd/trigger_producer.h"
50 #include "src/tracing/ipc/default_socket.h"
51 
52 #include "google/protobuf/io/zero_copy_stream_impl_lite.h"
53 
54 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
55 #include <sys/sendfile.h>
56 
57 #include <android/os/DropBoxManager.h>
58 #include <utils/Looper.h>
59 #include <utils/StrongPointer.h>
60 
61 #include "src/android_internal/incident_service.h"
62 #endif  // PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
63 
64 namespace perfetto {
65 namespace {
66 
67 perfetto::PerfettoCmd* g_consumer_cmd;
68 
69 class LoggingErrorReporter : public ErrorReporter {
70  public:
LoggingErrorReporter(std::string file_name,const char * config)71   LoggingErrorReporter(std::string file_name, const char* config)
72       : file_name_(file_name), config_(config) {}
73 
AddError(size_t row,size_t column,size_t length,const std::string & message)74   void AddError(size_t row,
75                 size_t column,
76                 size_t length,
77                 const std::string& message) override {
78     parsed_successfully_ = false;
79     std::string line = ExtractLine(row - 1).ToStdString();
80     if (!line.empty() && line[line.length() - 1] == '\n') {
81       line.erase(line.length() - 1);
82     }
83 
84     std::string guide(column + length, ' ');
85     for (size_t i = column; i < column + length; i++) {
86       guide[i - 1] = i == column ? '^' : '~';
87     }
88     fprintf(stderr, "%s:%zu:%zu error: %s\n", file_name_.c_str(), row, column,
89             message.c_str());
90     fprintf(stderr, "%s\n", line.c_str());
91     fprintf(stderr, "%s\n", guide.c_str());
92   }
93 
Success() const94   bool Success() const { return parsed_successfully_; }
95 
96  private:
ExtractLine(size_t line)97   base::StringView ExtractLine(size_t line) {
98     const char* start = config_;
99     const char* end = config_;
100 
101     for (size_t i = 0; i < line + 1; i++) {
102       start = end;
103       char c;
104       while ((c = *end++) && c != '\n')
105         ;
106     }
107     return base::StringView(start, static_cast<size_t>(end - start));
108   }
109 
110   bool parsed_successfully_ = true;
111   std::string file_name_;
112   const char* config_;
113 };
114 
ParseTraceConfigPbtxt(const std::string & file_name,const std::string & pbtxt,protos::TraceConfig * config)115 bool ParseTraceConfigPbtxt(const std::string& file_name,
116                            const std::string& pbtxt,
117                            protos::TraceConfig* config) {
118   LoggingErrorReporter reporter(file_name, pbtxt.c_str());
119   std::vector<uint8_t> buf = PbtxtToPb(pbtxt, &reporter);
120   if (!reporter.Success())
121     return false;
122   if (!config->ParseFromArray(buf.data(), static_cast<int>(buf.size())))
123     return false;
124   return true;
125 }
126 
127 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
StartIncidentReport(const TraceConfig::IncidentReportConfig & cfg)128 static bool StartIncidentReport(const TraceConfig::IncidentReportConfig& cfg) {
129   using ScopedDlHandle = base::ScopedResource<void*, dlclose, nullptr>;
130 
131   static const char kLibName[] = "libperfetto_android_internal.so";
132   ScopedDlHandle handle(dlopen(kLibName, RTLD_NOW));
133   PERFETTO_CHECK(handle);
134 
135   void* fn = dlsym(*handle, "StartIncidentReport");
136   PERFETTO_CHECK(fn);
137   auto start_incident =
138       reinterpret_cast<decltype(&android_internal::StartIncidentReport)>(fn);
139 
140   return start_incident(cfg.destination_package().c_str(),
141                         cfg.destination_class().c_str(), cfg.privacy_level());
142 }
143 #else
StartIncidentReport(const TraceConfig::IncidentReportConfig &)144 static bool StartIncidentReport(const TraceConfig::IncidentReportConfig&) {
145   PERFETTO_FATAL("should not be called");
146 };
147 #endif
148 
149 }  // namespace
150 
151 // Directory for temporary trace files. Note that this is automatically created
152 // by the system by setting setprop persist.traced.enable=1.
153 const char* kTempDropBoxTraceDir = "/data/misc/perfetto-traces";
154 
155 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
156 // If writing into an incident, the trace is written to a hardcoded location
157 // that is known to incidentd.
158 static const char kIncidentTraceLocation[] =
159     "/data/misc/perfetto-traces/incident-trace";
160 static const char kTempIncidentTraceLocation[] =
161     "/data/misc/perfetto-traces/incident-trace.temp";
162 #endif
163 
164 using protozero::proto_utils::MakeTagLengthDelimited;
165 using protozero::proto_utils::WriteVarInt;
166 
PrintUsage(const char * argv0)167 int PerfettoCmd::PrintUsage(const char* argv0) {
168   PERFETTO_ELOG(R"(
169 Usage: %s
170   --background     -d      : Exits immediately and continues tracing in background
171   --config         -c      : /path/to/trace/config/file or - for stdin
172   --out            -o      : /path/to/out/trace/file or - for stdout
173   --dropbox           TAG  : Upload trace into DropBox using tag TAG
174   --no-guardrails          : Ignore guardrails triggered when using --dropbox (for testing).
175   --txt                    : Parse config as pbtxt. Not a stable API. Not for production use.
176   --reset-guardrails       : Resets the state of the guardails and exits (for testing).
177   --help           -h
178 
179 
180 light configuration flags: (only when NOT using -c/--config)
181   --time           -t      : Trace duration N[s,m,h] (default: 10s)
182   --buffer         -b      : Ring buffer size N[mb,gb] (default: 32mb)
183   --size           -s      : Max file size N[mb,gb] (default: in-memory ring-buffer only)
184   ATRACE_CAT               : Record ATRACE_CAT (e.g. wm)
185   FTRACE_GROUP/FTRACE_NAME : Record ftrace event (e.g. sched/sched_switch)
186   FTRACE_GROUP/*           : Record all events in group (e.g. sched/*)
187 
188 
189 statsd-specific flags:
190   --alert-id           : ID of the alert that triggered this trace.
191   --config-id          : ID of the triggering config.
192   --config-uid         : UID of app which registered the config.
193   --subscription-id    : ID of the subscription that triggered this trace.
194 
195 Detach mode. DISCOURAGED, read https://docs.perfetto.dev/#/detached-mode :
196   --detach=key          : Detach from the tracing session with the given key.
197   --attach=key [--stop] : Re-attach to the session (optionally stop tracing once reattached).
198   --is_detached=key     : Check if the session can be re-attached (0:Yes, 2:No, 1:Error).
199 )",
200                 argv0);
201   return 1;
202 }
203 
Main(int argc,char ** argv)204 int PerfettoCmd::Main(int argc, char** argv) {
205   enum LongOption {
206     OPT_ALERT_ID = 1000,
207     OPT_CONFIG_ID,
208     OPT_CONFIG_UID,
209     OPT_SUBSCRIPTION_ID,
210     OPT_RESET_GUARDRAILS,
211     OPT_PBTXT_CONFIG,
212     OPT_DROPBOX,
213     OPT_ATRACE_APP,
214     OPT_IGNORE_GUARDRAILS,
215     OPT_DETACH,
216     OPT_ATTACH,
217     OPT_IS_DETACHED,
218     OPT_STOP,
219   };
220   static const struct option long_options[] = {
221       {"help", no_argument, nullptr, 'h'},
222       {"config", required_argument, nullptr, 'c'},
223       {"out", required_argument, nullptr, 'o'},
224       {"background", no_argument, nullptr, 'd'},
225       {"time", required_argument, nullptr, 't'},
226       {"buffer", required_argument, nullptr, 'b'},
227       {"size", required_argument, nullptr, 's'},
228       {"no-guardrails", no_argument, nullptr, OPT_IGNORE_GUARDRAILS},
229       {"txt", no_argument, nullptr, OPT_PBTXT_CONFIG},
230       {"dropbox", required_argument, nullptr, OPT_DROPBOX},
231       {"alert-id", required_argument, nullptr, OPT_ALERT_ID},
232       {"config-id", required_argument, nullptr, OPT_CONFIG_ID},
233       {"config-uid", required_argument, nullptr, OPT_CONFIG_UID},
234       {"subscription-id", required_argument, nullptr, OPT_SUBSCRIPTION_ID},
235       {"reset-guardrails", no_argument, nullptr, OPT_RESET_GUARDRAILS},
236       {"detach", required_argument, nullptr, OPT_DETACH},
237       {"attach", required_argument, nullptr, OPT_ATTACH},
238       {"is_detached", required_argument, nullptr, OPT_IS_DETACHED},
239       {"stop", no_argument, nullptr, OPT_STOP},
240       {"app", required_argument, nullptr, OPT_ATRACE_APP},
241       {nullptr, 0, nullptr, 0}};
242 
243   int option_index = 0;
244   std::string config_file_name;
245   std::string trace_config_raw;
246   bool background = false;
247   bool ignore_guardrails = false;
248   bool parse_as_pbtxt = false;
249   perfetto::protos::TraceConfig::StatsdMetadata statsd_metadata;
250   RateLimiter limiter;
251 
252   ConfigOptions config_options;
253   bool has_config_options = false;
254 
255   for (;;) {
256     int option =
257         getopt_long(argc, argv, "hc:o:dt:b:s:", long_options, &option_index);
258 
259     if (option == -1)
260       break;  // EOF.
261 
262     if (option == 'c') {
263       config_file_name = std::string(optarg);
264       if (strcmp(optarg, "-") == 0) {
265         std::istreambuf_iterator<char> begin(std::cin), end;
266         trace_config_raw.assign(begin, end);
267       } else if (strcmp(optarg, ":test") == 0) {
268         // TODO(primiano): temporary for testing only.
269         perfetto::protos::TraceConfig test_config;
270         test_config.add_buffers()->set_size_kb(4096);
271         test_config.set_duration_ms(2000);
272         auto* ds_config = test_config.add_data_sources()->mutable_config();
273         ds_config->set_name("linux.ftrace");
274         ds_config->mutable_ftrace_config()->add_ftrace_events("sched_switch");
275         ds_config->mutable_ftrace_config()->add_ftrace_events("cpu_idle");
276         ds_config->mutable_ftrace_config()->add_ftrace_events("cpu_frequency");
277         ds_config->mutable_ftrace_config()->add_ftrace_events("gpu_frequency");
278         ds_config->set_target_buffer(0);
279         test_config.SerializeToString(&trace_config_raw);
280       } else {
281         if (!base::ReadFile(optarg, &trace_config_raw)) {
282           PERFETTO_PLOG("Could not open %s", optarg);
283           return 1;
284         }
285       }
286       continue;
287     }
288 
289     if (option == 'o') {
290       trace_out_path_ = optarg;
291       continue;
292     }
293 
294     if (option == 'd') {
295       background = true;
296       continue;
297     }
298     if (option == 't') {
299       has_config_options = true;
300       config_options.time = std::string(optarg);
301       continue;
302     }
303 
304     if (option == 'b') {
305       has_config_options = true;
306       config_options.buffer_size = std::string(optarg);
307       continue;
308     }
309 
310     if (option == 's') {
311       has_config_options = true;
312       config_options.max_file_size = std::string(optarg);
313       continue;
314     }
315 
316     if (option == OPT_DROPBOX) {
317 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
318       if (!optarg)
319         PERFETTO_FATAL("optarg is null");
320       dropbox_tag_ = optarg;
321       continue;
322 #else
323       PERFETTO_ELOG("DropBox is only supported with Android tree builds");
324       return 1;
325 #endif
326     }
327 
328     if (option == OPT_PBTXT_CONFIG) {
329       parse_as_pbtxt = true;
330       continue;
331     }
332 
333     if (option == OPT_IGNORE_GUARDRAILS) {
334       ignore_guardrails = true;
335       continue;
336     }
337 
338     if (option == OPT_RESET_GUARDRAILS) {
339       PERFETTO_CHECK(limiter.ClearState());
340       PERFETTO_ILOG("Guardrail state cleared");
341       return 0;
342     }
343 
344     if (option == OPT_ALERT_ID) {
345       statsd_metadata.set_triggering_alert_id(atoll(optarg));
346       continue;
347     }
348 
349     if (option == OPT_CONFIG_ID) {
350       statsd_metadata.set_triggering_config_id(atoll(optarg));
351       continue;
352     }
353 
354     if (option == OPT_CONFIG_UID) {
355       statsd_metadata.set_triggering_config_uid(atoi(optarg));
356       continue;
357     }
358 
359     if (option == OPT_SUBSCRIPTION_ID) {
360       statsd_metadata.set_triggering_subscription_id(atoll(optarg));
361       continue;
362     }
363 
364     if (option == OPT_ATRACE_APP) {
365       config_options.atrace_apps.push_back(std::string(optarg));
366       has_config_options = true;
367       continue;
368     }
369 
370     if (option == OPT_DETACH) {
371       detach_key_ = std::string(optarg);
372       PERFETTO_CHECK(!detach_key_.empty());
373       continue;
374     }
375 
376     if (option == OPT_ATTACH) {
377       attach_key_ = std::string(optarg);
378       PERFETTO_CHECK(!attach_key_.empty());
379       continue;
380     }
381 
382     if (option == OPT_IS_DETACHED) {
383       attach_key_ = std::string(optarg);
384       redetach_once_attached_ = true;
385       PERFETTO_CHECK(!attach_key_.empty());
386       continue;
387     }
388 
389     if (option == OPT_STOP) {
390       stop_trace_once_attached_ = true;
391       continue;
392     }
393 
394     return PrintUsage(argv[0]);
395   }
396 
397   for (ssize_t i = optind; i < argc; i++) {
398     has_config_options = true;
399     config_options.categories.push_back(argv[i]);
400   }
401 
402   if (is_detach() && is_attach()) {
403     PERFETTO_ELOG("--attach and --detach are mutually exclusive");
404     return 1;
405   }
406 
407   if (is_detach() && background) {
408     PERFETTO_ELOG("--detach and --background are mutually exclusive");
409     return 1;
410   }
411 
412   if (stop_trace_once_attached_ && !is_attach()) {
413     PERFETTO_ELOG("--stop is supported only in combination with --attach");
414     return 1;
415   }
416 
417   // Parse the trace config. It can be either:
418   // 1) A proto-encoded file/stdin (-c ...).
419   // 2) A proto-text file/stdin (-c ... --txt).
420   // 3) A set of option arguments (-t 10s -s 10m).
421   // The only cases in which a trace config is not expected is --attach.
422   // For this we are just acting on already existing sessions.
423   perfetto::protos::TraceConfig trace_config_proto;
424   std::vector<std::string> triggers_to_activate;
425   bool parsed = false;
426   if (is_attach()) {
427     if ((!trace_config_raw.empty() || has_config_options)) {
428       PERFETTO_ELOG("Cannot specify a trace config with --attach");
429       return 1;
430     }
431   } else if (has_config_options) {
432     if (!trace_config_raw.empty()) {
433       PERFETTO_ELOG(
434           "Cannot specify both -c/--config and any of --time, --size, "
435           "--buffer, --app, ATRACE_CAT, FTRACE_EVENT");
436       return 1;
437     }
438     parsed = CreateConfigFromOptions(config_options, &trace_config_proto);
439   } else {
440     if (trace_config_raw.empty()) {
441       PERFETTO_ELOG("The TraceConfig is empty");
442       return 1;
443     }
444     PERFETTO_DLOG("Parsing TraceConfig, %zu bytes", trace_config_raw.size());
445     if (parse_as_pbtxt) {
446       parsed = ParseTraceConfigPbtxt(config_file_name, trace_config_raw,
447                                      &trace_config_proto);
448     } else {
449       parsed = trace_config_proto.ParseFromString(trace_config_raw);
450     }
451   }
452 
453   trace_config_.reset(new TraceConfig());
454   if (parsed) {
455     *trace_config_proto.mutable_statsd_metadata() = std::move(statsd_metadata);
456     trace_config_->FromProto(trace_config_proto);
457     trace_config_raw.clear();
458   } else if (!is_attach()) {
459     PERFETTO_ELOG("The trace config is invalid, bailing out.");
460     return 1;
461   }
462 
463   if (!trace_config_->incident_report_config().destination_package().empty()) {
464     if (dropbox_tag_.empty()) {
465       PERFETTO_ELOG("Unexpected IncidentReportConfig without --dropbox.");
466       return 1;
467     }
468   }
469 
470   // Set up the output file. Either --out or --dropbox are expected, with the
471   // only exception of --attach. In this case the output file is passed when
472   // detaching.
473   if (!trace_out_path_.empty() && !dropbox_tag_.empty()) {
474     PERFETTO_ELOG(
475         "Can't log to a file (--out) and DropBox (--dropbox) at the same "
476         "time");
477     return 1;
478   }
479 
480   // |activate_triggers| in the trace config is shorthand for trigger_perfetto.
481   // In this case we don't intend to send any trace config to the service,
482   // rather use that as a signal to the cmdline client to connect as a producer
483   // and activate triggers.
484   if (!trace_config_->activate_triggers().empty()) {
485     for (const auto& trigger : trace_config_->activate_triggers()) {
486       triggers_to_activate.push_back(trigger);
487     }
488     trace_config_.reset(new TraceConfig());
489   }
490 
491   bool open_out_file = true;
492   if (is_attach()) {
493     open_out_file = false;
494     if (!trace_out_path_.empty() || !dropbox_tag_.empty()) {
495       PERFETTO_ELOG("Can't pass an --out file (or --dropbox) to --attach");
496       return 1;
497     }
498   } else if (!triggers_to_activate.empty()) {
499     open_out_file = false;
500   } else if (trace_out_path_.empty() && dropbox_tag_.empty()) {
501     PERFETTO_ELOG("Either --out or --dropbox is required");
502     return 1;
503   } else if (is_detach() && !trace_config_->write_into_file()) {
504     // In detached mode we must pass the file descriptor to the service and
505     // let that one write the trace. We cannot use the IPC readback code path
506     // because the client process is about to exit soon after detaching.
507     PERFETTO_ELOG(
508         "TraceConfig's write_into_file must be true when using --detach");
509     return 1;
510   }
511   if (open_out_file) {
512     if (!OpenOutputFile())
513       return 1;
514     if (!trace_config_->write_into_file())
515       packet_writer_ = CreateFilePacketWriter(trace_out_stream_.get());
516   }
517 
518   if (background) {
519     pid_t pid;
520     switch (pid = fork()) {
521       case -1:
522         PERFETTO_FATAL("fork");
523       case 0: {
524         PERFETTO_CHECK(setsid() != -1);
525         base::ignore_result(chdir("/"));
526         base::ScopedFile null = base::OpenFile("/dev/null", O_RDONLY);
527         PERFETTO_CHECK(null);
528         PERFETTO_CHECK(dup2(*null, STDIN_FILENO) != -1);
529         PERFETTO_CHECK(dup2(*null, STDOUT_FILENO) != -1);
530         PERFETTO_CHECK(dup2(*null, STDERR_FILENO) != -1);
531         // Do not accidentally close stdin/stdout/stderr.
532         if (*null <= 2)
533           null.release();
534         break;
535       }
536       default:
537         printf("%d\n", pid);
538         exit(0);
539     }
540   }
541 
542   // If we are just activating triggers then we don't need to rate limit,
543   // connect as a consumer or run the trace. So bail out after processing all
544   // the options.
545   if (!triggers_to_activate.empty()) {
546     bool finished_with_success = false;
547     TriggerProducer producer(&task_runner_,
548                              [this, &finished_with_success](bool success) {
549                                finished_with_success = success;
550                                task_runner_.Quit();
551                              },
552                              &triggers_to_activate);
553     task_runner_.Run();
554     return finished_with_success ? 0 : 1;
555   }
556 
557   if (trace_config_->compression_type() ==
558       perfetto::TraceConfig::COMPRESSION_TYPE_DEFLATE) {
559     if (packet_writer_) {
560       packet_writer_ = CreateZipPacketWriter(std::move(packet_writer_));
561     } else {
562       PERFETTO_ELOG("Cannot compress when tracing directly to file.");
563     }
564   }
565 
566   RateLimiter::Args args{};
567   args.is_dropbox = !dropbox_tag_.empty();
568   args.current_time = base::GetWallTimeS();
569   args.ignore_guardrails = ignore_guardrails;
570   args.allow_user_build_tracing = trace_config_->allow_user_build_tracing();
571 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_USERDEBUG_BUILD) || \
572     PERFETTO_BUILDFLAG(PERFETTO_STANDALONE_BUILD)
573   args.max_upload_bytes_override =
574       trace_config_->guardrail_overrides().max_upload_per_day_bytes();
575 #endif
576 
577   if (args.is_dropbox && !args.ignore_guardrails &&
578       (trace_config_->duration_ms() == 0 &&
579        trace_config_->trigger_config().trigger_timeout_ms() == 0)) {
580     PERFETTO_ELOG("Can't trace indefinitely when tracing to Dropbox.");
581     return 1;
582   }
583 
584   if (!limiter.ShouldTrace(args))
585     return 1;
586 
587   consumer_endpoint_ =
588       ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
589   SetupCtrlCSignalHandler();
590   task_runner_.Run();
591 
592   return limiter.OnTraceDone(args, did_process_full_trace_, bytes_written_) ? 0
593                                                                             : 1;
594 }
595 
OnConnect()596 void PerfettoCmd::OnConnect() {
597   if (is_attach()) {
598     consumer_endpoint_->Attach(attach_key_);
599     return;
600   }
601 
602   PERFETTO_LOG(
603       "Connected to the Perfetto traced service, starting tracing for %d ms",
604       trace_config_->duration_ms());
605   PERFETTO_DCHECK(trace_config_);
606   trace_config_->set_enable_extra_guardrails(!dropbox_tag_.empty());
607 
608   base::ScopedFile optional_fd;
609   if (trace_config_->write_into_file())
610     optional_fd.reset(dup(fileno(*trace_out_stream_)));
611 
612   consumer_endpoint_->EnableTracing(*trace_config_, std::move(optional_fd));
613 
614   if (is_detach()) {
615     consumer_endpoint_->Detach(detach_key_);  // Will invoke OnDetach() soon.
616     return;
617   }
618 
619   // Failsafe mechanism to avoid waiting indefinitely if the service hangs.
620   if (trace_config_->duration_ms()) {
621     uint32_t trace_timeout = trace_config_->duration_ms() + 10000 +
622                              trace_config_->flush_timeout_ms();
623     task_runner_.PostDelayedTask(std::bind(&PerfettoCmd::OnTimeout, this),
624                                  trace_timeout);
625   }
626 }
627 
OnDisconnect()628 void PerfettoCmd::OnDisconnect() {
629   PERFETTO_LOG("Disconnected from the Perfetto traced service");
630   task_runner_.Quit();
631 }
632 
OnTimeout()633 void PerfettoCmd::OnTimeout() {
634   PERFETTO_ELOG("Timed out while waiting for trace from the service, aborting");
635   task_runner_.Quit();
636 }
637 
OnTraceData(std::vector<TracePacket> packets,bool has_more)638 void PerfettoCmd::OnTraceData(std::vector<TracePacket> packets, bool has_more) {
639   if (!packet_writer_->WritePackets(packets)) {
640     PERFETTO_ELOG("Failed to write packets");
641     FinalizeTraceAndExit();
642   }
643 
644   if (!has_more)
645     FinalizeTraceAndExit();  // Reached end of trace.
646 }
647 
OnTracingDisabled()648 void PerfettoCmd::OnTracingDisabled() {
649   if (trace_config_->write_into_file()) {
650     // If write_into_file == true, at this point the passed file contains
651     // already all the packets.
652     return FinalizeTraceAndExit();
653   }
654   // This will cause a bunch of OnTraceData callbacks. The last one will
655   // save the file and exit.
656   consumer_endpoint_->ReadBuffers();
657 }
658 
FinalizeTraceAndExit()659 void PerfettoCmd::FinalizeTraceAndExit() {
660   packet_writer_.reset();
661 
662   if (trace_out_stream_) {
663     fseek(*trace_out_stream_, 0, SEEK_END);
664     off_t sz = ftell(*trace_out_stream_);
665     if (sz > 0)
666       bytes_written_ = static_cast<size_t>(sz);
667   }
668 
669   if (dropbox_tag_.empty()) {
670     trace_out_stream_.reset();
671     did_process_full_trace_ = true;
672     if (trace_config_->write_into_file()) {
673       // trace_out_path_ might be empty in the case of --attach.
674       PERFETTO_LOG("Trace written into the output file");
675     } else {
676       PERFETTO_LOG("Wrote %" PRIu64 " bytes into %s", bytes_written_,
677                    trace_out_path_ == "-" ? "stdout" : trace_out_path_.c_str());
678     }
679     task_runner_.Quit();
680     return;
681   }
682 
683   // Otherwise, write to Dropbox unless there's a special override in the
684   // incident report config.
685   if (!trace_config_->incident_report_config().skip_dropbox()) {
686     SaveOutputToDropboxOrCrash();
687   }
688 
689   // Optionally save the trace as an incident. This is either in addition to, or
690   // instead of, the Dropbox write.
691   if (!trace_config_->incident_report_config().destination_package().empty()) {
692     SaveOutputToIncidentTraceOrCrash();
693 
694     // Ask incidentd to create a report, which will read the file we just wrote.
695     PERFETTO_CHECK(
696         StartIncidentReport(trace_config_->incident_report_config()));
697   }
698 
699   did_process_full_trace_ = true;
700   task_runner_.Quit();
701 }
702 
SaveOutputToDropboxOrCrash()703 void PerfettoCmd::SaveOutputToDropboxOrCrash() {
704 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
705   if (bytes_written_ == 0) {
706     PERFETTO_LOG("Skipping write to dropbox. Empty trace.");
707     return;
708   }
709   android::sp<android::os::DropBoxManager> dropbox =
710       new android::os::DropBoxManager();
711   PERFETTO_CHECK(fseek(*trace_out_stream_, 0, SEEK_SET) == 0);
712   // DropBox takes ownership of the file descriptor, so give it a duplicate.
713   // Also we need to give it a read-only copy of the fd or will hit a SELinux
714   // violation (about system_server ending up with a writable FD to our dir).
715   char fdpath[64];
716   sprintf(fdpath, "/proc/self/fd/%d", fileno(*trace_out_stream_));
717   base::ScopedFile read_only_fd(base::OpenFile(fdpath, O_RDONLY));
718   PERFETTO_CHECK(read_only_fd);
719   android::binder::Status status =
720       dropbox->addFile(android::String16(dropbox_tag_.c_str()),
721                        read_only_fd.release(), 0 /* flags */);
722   if (status.isOk()) {
723     PERFETTO_LOG("Wrote %" PRIu64
724                  " bytes (before compression) into DropBox with tag %s",
725                  bytes_written_, dropbox_tag_.c_str());
726   } else {
727     PERFETTO_FATAL("DropBox upload failed: %s", status.toString8().c_str());
728   }
729 #endif
730 }
731 
732 // Open a staging file (unlinking the previous instance), copy the trace
733 // contents over, then rename to a final hardcoded path. Such tracing sessions
734 // should not normally overlap. We do not use unique unique filenames to avoid
735 // creating an unbounded amount of files in case of errors.
SaveOutputToIncidentTraceOrCrash()736 void PerfettoCmd::SaveOutputToIncidentTraceOrCrash() {
737 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
738   if (bytes_written_ == 0) {
739     PERFETTO_LOG("Skipping incident report. Empty trace.");
740     return;
741   }
742 
743   PERFETTO_CHECK(unlink(kTempIncidentTraceLocation) == 0 || errno == ENOENT);
744 
745   // SELinux constrains the set of readers.
746   base::ScopedFile staging_fd =
747       base::OpenFile(kTempIncidentTraceLocation, O_CREAT | O_RDWR, 0666);
748   PERFETTO_CHECK(staging_fd);
749 
750   // Set the desired permissions even if under a umask.
751   PERFETTO_CHECK(fchmod(*staging_fd, 0666) == 0);
752 
753   off_t offset = 0;
754   PERFETTO_CHECK(sendfile(*staging_fd, fileno(*trace_out_stream_), &offset,
755                           bytes_written_) == bytes_written_);
756 
757   staging_fd.reset();
758   PERFETTO_CHECK(rename(kTempIncidentTraceLocation, kIncidentTraceLocation) ==
759                  0);
760 // Note: not calling fsync(2), as we're not interested in the file being
761 // consistent in case of a crash.
762 #endif
763 }
764 
OpenOutputFile()765 bool PerfettoCmd::OpenOutputFile() {
766   base::ScopedFile fd;
767   if (!dropbox_tag_.empty()) {
768 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
769     // If we are tracing to DropBox, there's no need to make a
770     // filesystem-visible temporary file.
771     // TODO(skyostil): Fall back to base::TempFile for older devices.
772     fd = base::OpenFile(kTempDropBoxTraceDir, O_TMPFILE | O_RDWR, 0600);
773     if (!fd) {
774       PERFETTO_PLOG("Could not create a temporary trace file in %s",
775                     kTempDropBoxTraceDir);
776       return false;
777     }
778 #else
779     PERFETTO_FATAL("Tracing to Dropbox requires the Android build.");
780 #endif
781   } else if (trace_out_path_ == "-") {
782     fd.reset(dup(STDOUT_FILENO));
783   } else {
784     fd = base::OpenFile(trace_out_path_, O_RDWR | O_CREAT | O_TRUNC, 0600);
785   }
786   if (!fd) {
787     PERFETTO_PLOG(
788         "Failed to open %s. If you get permission denied in "
789         "/data/misc/perfetto-traces, the file might have been "
790         "created by another user, try deleting it first.",
791         trace_out_path_.c_str());
792     return false;
793   }
794   trace_out_stream_.reset(fdopen(fd.release(), "wb"));
795   PERFETTO_CHECK(trace_out_stream_);
796   return true;
797 }
798 
SetupCtrlCSignalHandler()799 void PerfettoCmd::SetupCtrlCSignalHandler() {
800   // Setup signal handler.
801   struct sigaction sa {};
802 
803 // Glibc headers for sa_sigaction trigger this.
804 #pragma GCC diagnostic push
805 #if defined(__clang__)
806 #pragma GCC diagnostic ignored "-Wdisabled-macro-expansion"
807 #endif
808   sa.sa_handler = [](int) { g_consumer_cmd->SignalCtrlC(); };
809   sa.sa_flags = static_cast<decltype(sa.sa_flags)>(SA_RESETHAND | SA_RESTART);
810 #pragma GCC diagnostic pop
811   sigaction(SIGINT, &sa, nullptr);
812   sigaction(SIGTERM, &sa, nullptr);
813 
814   task_runner_.AddFileDescriptorWatch(ctrl_c_evt_.fd(), [this] {
815     PERFETTO_LOG("SIGINT/SIGTERM received: disabling tracing.");
816     ctrl_c_evt_.Clear();
817     consumer_endpoint_->Flush(0, [this](bool flush_success) {
818       if (!flush_success)
819         PERFETTO_ELOG("Final flush unsuccessful.");
820       consumer_endpoint_->DisableTracing();
821     });
822   });
823 }
824 
OnDetach(bool success)825 void PerfettoCmd::OnDetach(bool success) {
826   if (!success) {
827     PERFETTO_ELOG("Session detach failed");
828     exit(1);
829   }
830   exit(0);
831 }
832 
OnAttach(bool success,const TraceConfig & trace_config)833 void PerfettoCmd::OnAttach(bool success, const TraceConfig& trace_config) {
834   if (!success) {
835     if (!redetach_once_attached_) {
836       // Print an error message if attach fails, with the exception of the
837       // --is_detached case, where we want to silently return.
838       PERFETTO_ELOG("Session re-attach failed. Check service logs for details");
839     }
840     // Keep this exit code distinguishable from the general error code so
841     // --is_detached can tell the difference between a general error and the
842     // not-detached case.
843     exit(2);
844   }
845 
846   if (redetach_once_attached_) {
847     consumer_endpoint_->Detach(attach_key_);  // Will invoke OnDetach() soon.
848     return;
849   }
850 
851   trace_config_.reset(new TraceConfig(trace_config));
852   PERFETTO_DCHECK(trace_config_->write_into_file());
853 
854   if (stop_trace_once_attached_) {
855     consumer_endpoint_->Flush(0, [this](bool flush_success) {
856       if (!flush_success)
857         PERFETTO_ELOG("Final flush unsuccessful.");
858       consumer_endpoint_->DisableTracing();
859     });
860   }
861 }
862 
OnTraceStats(bool,const TraceStats &)863 void PerfettoCmd::OnTraceStats(bool /*success*/,
864                                const TraceStats& /*trace_config*/) {
865   // TODO(eseckler): Support GetTraceStats().
866 }
867 
OnObservableEvents(const ObservableEvents &)868 void PerfettoCmd::OnObservableEvents(
869     const ObservableEvents& /*observable_events*/) {}
870 
871 int __attribute__((visibility("default")))
PerfettoCmdMain(int argc,char ** argv)872 PerfettoCmdMain(int argc, char** argv) {
873   g_consumer_cmd = new perfetto::PerfettoCmd();
874   return g_consumer_cmd->Main(argc, argv);
875 }
876 
877 }  // namespace perfetto
878