xref: /aosp_15_r20/external/perfetto/src/perfetto_cmd/perfetto_cmd.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
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 <fcntl.h>
20 #include <stdio.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <time.h>
24 
25 #include <algorithm>
26 #include <array>
27 #include <atomic>
28 #include <chrono>
29 #include <cinttypes>
30 #include <cstdint>
31 #include <cstdlib>
32 #include <cstring>
33 #include <functional>
34 #include <iostream>
35 #include <iterator>
36 #include <memory>
37 #include <mutex>
38 #include <optional>
39 #include <random>
40 #include <string>
41 #include <thread>
42 #include <utility>
43 #include <vector>
44 
45 #include "perfetto/base/build_config.h"
46 #include "perfetto/base/compiler.h"
47 #include "perfetto/base/logging.h"
48 #include "perfetto/base/proc_utils.h"         // IWYU pragma: keep
49 #include "perfetto/ext/base/android_utils.h"  // IWYU pragma: keep
50 #include "perfetto/ext/base/ctrl_c_handler.h"
51 #include "perfetto/ext/base/file_utils.h"
52 #include "perfetto/ext/base/getopt.h"  // IWYU pragma: keep
53 #include "perfetto/ext/base/no_destructor.h"
54 #include "perfetto/ext/base/pipe.h"
55 #include "perfetto/ext/base/scoped_file.h"
56 #include "perfetto/ext/base/string_splitter.h"
57 #include "perfetto/ext/base/string_utils.h"
58 #include "perfetto/ext/base/string_view.h"
59 #include "perfetto/ext/base/thread_task_runner.h"
60 #include "perfetto/ext/base/thread_utils.h"
61 #include "perfetto/ext/base/utils.h"
62 #include "perfetto/ext/base/uuid.h"
63 #include "perfetto/ext/base/version.h"
64 #include "perfetto/ext/base/waitable_event.h"
65 #include "perfetto/ext/traced/traced.h"
66 #include "perfetto/ext/tracing/core/basic_types.h"
67 #include "perfetto/ext/tracing/core/trace_packet.h"
68 #include "perfetto/ext/tracing/core/tracing_service.h"
69 #include "perfetto/ext/tracing/ipc/consumer_ipc_client.h"
70 #include "perfetto/tracing/core/flush_flags.h"
71 #include "perfetto/tracing/core/forward_decls.h"
72 #include "perfetto/tracing/core/trace_config.h"
73 #include "perfetto/tracing/default_socket.h"
74 #include "protos/perfetto/common/data_source_descriptor.gen.h"
75 #include "src/android_stats/perfetto_atoms.h"
76 #include "src/android_stats/statsd_logging_helper.h"
77 #include "src/perfetto_cmd/bugreport_path.h"
78 #include "src/perfetto_cmd/config.h"
79 #include "src/perfetto_cmd/packet_writer.h"
80 #include "src/perfetto_cmd/trigger_producer.h"
81 #include "src/trace_config_utils/txt_to_pb.h"
82 
83 #include "protos/perfetto/common/ftrace_descriptor.gen.h"
84 #include "protos/perfetto/common/tracing_service_state.gen.h"
85 #include "protos/perfetto/common/track_event_descriptor.gen.h"
86 
87 // For dup() (and _setmode() on windows).
88 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
89 #include <fcntl.h>
90 #include <io.h>
91 #else
92 #include <unistd.h>
93 #endif
94 
95 namespace perfetto {
96 namespace {
97 
98 std::atomic<perfetto::PerfettoCmd*> g_perfetto_cmd;
99 
100 const uint32_t kOnTraceDataTimeoutMs = 3000;
101 const uint32_t kCloneTimeoutMs = 30000;
102 
ParseTraceConfigPbtxt(const std::string & file_name,const std::string & pbtxt,TraceConfig * config)103 bool ParseTraceConfigPbtxt(const std::string& file_name,
104                            const std::string& pbtxt,
105                            TraceConfig* config) {
106   auto res = TraceConfigTxtToPb(pbtxt, file_name);
107   if (!res.ok()) {
108     fprintf(stderr, "%s\n", res.status().c_message());
109     return false;
110   }
111   if (!config->ParseFromArray(res->data(), res->size()))
112     return false;
113   return true;
114 }
115 
ArgsAppend(std::string * str,const std::string & arg)116 void ArgsAppend(std::string* str, const std::string& arg) {
117   str->append(arg);
118   str->append("\0", 1);
119 }
120 }  // namespace
121 
122 const char* kStateDir = "/data/misc/perfetto-traces";
123 
PerfettoCmd()124 PerfettoCmd::PerfettoCmd() {
125   // Only the main thread instance on the main thread will receive ctrl-c.
126   PerfettoCmd* set_if_null = nullptr;
127   g_perfetto_cmd.compare_exchange_strong(set_if_null, this);
128 }
129 
~PerfettoCmd()130 PerfettoCmd::~PerfettoCmd() {
131   PerfettoCmd* self = this;
132   if (g_perfetto_cmd.compare_exchange_strong(self, nullptr)) {
133     if (ctrl_c_handler_installed_) {
134       task_runner_.RemoveFileDescriptorWatch(ctrl_c_evt_.fd());
135     }
136   }
137 }
138 
PrintUsage(const char * argv0)139 void PerfettoCmd::PrintUsage(const char* argv0) {
140   fprintf(stderr, R"(
141 Usage: %s
142   --background     -d      : Exits immediately and continues in the background.
143                              Prints the PID of the bg process. The printed PID
144                              can used to gracefully terminate the tracing
145                              session by issuing a `kill -TERM $PRINTED_PID`.
146   --background-wait -D     : Like --background, but waits (up to 30s) for all
147                              data sources to be started before exiting. Exit
148                              code is zero if a successful acknowledgement is
149                              received, non-zero otherwise (error or timeout).
150   --clone TSID             : Creates a read-only clone of an existing tracing
151                              session, identified by its ID (see --query).
152   --clone-by-name NAME     : Creates a read-only clone of an existing tracing
153                              session, identified by its unique_session_name in
154                              the config.
155   --clone-for-bugreport    : Can only be used with --clone. It disables the
156                              trace_filter on the cloned session.
157   --config         -c      : /path/to/trace/config/file or - for stdin
158   --out            -o      : /path/to/out/trace/file or - for stdout
159                              If using CLONE_SNAPSHOT triggers, each snapshot
160                              will be saved in a new file with a counter suffix
161                              (e.g., file.0, file.1, file.2).
162   --txt                    : Parse config as pbtxt. Not for production use.
163                              Not a stable API.
164   --query [--long]         : Queries the service state and prints it as
165                              human-readable text. --long allows the output to
166                              extend past 80 chars.
167   --query-raw              : Like --query, but prints raw proto-encoded bytes
168                              of tracing_service_state.proto.
169   --help           -h
170 
171 Light configuration flags: (only when NOT using -c/--config)
172   --time           -t      : Trace duration N[s,m,h] (default: 10s)
173   --buffer         -b      : Ring buffer size N[mb,gb] (default: 32mb)
174   --size           -s      : Max file size N[mb,gb]
175                             (default: in-memory ring-buffer only)
176   --app            -a      : Android (atrace) app name
177   FTRACE_GROUP/FTRACE_NAME : Record ftrace event (e.g. sched/sched_switch)
178   ATRACE_CAT               : Record ATRACE_CAT (e.g. wm) (Android only)
179 
180 Statsd-specific and other Android-only flags:
181   --alert-id           : ID of the alert that triggered this trace.
182   --config-id          : ID of the triggering config.
183   --config-uid         : UID of app which registered the config.
184   --subscription-id    : ID of the subscription that triggered this trace.
185   --upload             : Upload trace.
186   --dropbox        TAG : DEPRECATED: Use --upload instead
187                          TAG should always be set to 'perfetto'.
188   --save-for-bugreport : If a trace with bugreport_score > 0 is running, it
189                          saves it into a file. Outputs the path when done.
190   --no-guardrails      : Ignore guardrails triggered when using --upload
191                          (testing only).
192   --reset-guardrails   : Resets the state of the guardails and exits
193                          (testing only).
194 
195 Detach mode. DISCOURAGED, read https://perfetto.dev/docs/concepts/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
198                           once reattached).
199   --is_detached=key     : Check if the session can be re-attached.
200                           Exit code:  0:Yes, 2:No, 1:Error.
201 )", /* this comment fixes syntax highlighting in some editors */
202           argv0);
203 }
204 
ParseCmdlineAndMaybeDaemonize(int argc,char ** argv)205 std::optional<int> PerfettoCmd::ParseCmdlineAndMaybeDaemonize(int argc,
206                                                               char** argv) {
207 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
208   umask(0000);  // make sure that file creation is not affected by umask.
209 #endif
210   enum LongOption {
211     OPT_ALERT_ID = 1000,
212     OPT_BUGREPORT,
213     OPT_BUGREPORT_ALL,
214     OPT_CLONE,
215     OPT_CLONE_BY_NAME,
216     OPT_CLONE_SKIP_FILTER,
217     OPT_CONFIG_ID,
218     OPT_CONFIG_UID,
219     OPT_SUBSCRIPTION_ID,
220     OPT_RESET_GUARDRAILS,
221     OPT_PBTXT_CONFIG,
222     OPT_DROPBOX,
223     OPT_UPLOAD,
224     OPT_IGNORE_GUARDRAILS,
225     OPT_DETACH,
226     OPT_ATTACH,
227     OPT_IS_DETACHED,
228     OPT_STOP,
229     OPT_QUERY,
230     OPT_LONG,
231     OPT_QUERY_RAW,
232     OPT_VERSION,
233   };
234   static const option long_options[] = {
235       {"help", no_argument, nullptr, 'h'},
236       {"config", required_argument, nullptr, 'c'},
237       {"out", required_argument, nullptr, 'o'},
238       {"background", no_argument, nullptr, 'd'},
239       {"background-wait", no_argument, nullptr, 'D'},
240       {"time", required_argument, nullptr, 't'},
241       {"buffer", required_argument, nullptr, 'b'},
242       {"size", required_argument, nullptr, 's'},
243       {"app", required_argument, nullptr, 'a'},
244       {"no-guardrails", no_argument, nullptr, OPT_IGNORE_GUARDRAILS},
245       {"txt", no_argument, nullptr, OPT_PBTXT_CONFIG},
246       {"upload", no_argument, nullptr, OPT_UPLOAD},
247       {"dropbox", required_argument, nullptr, OPT_DROPBOX},
248       {"alert-id", required_argument, nullptr, OPT_ALERT_ID},
249       {"config-id", required_argument, nullptr, OPT_CONFIG_ID},
250       {"config-uid", required_argument, nullptr, OPT_CONFIG_UID},
251       {"subscription-id", required_argument, nullptr, OPT_SUBSCRIPTION_ID},
252       {"reset-guardrails", no_argument, nullptr, OPT_RESET_GUARDRAILS},
253       {"detach", required_argument, nullptr, OPT_DETACH},
254       {"attach", required_argument, nullptr, OPT_ATTACH},
255       {"clone", required_argument, nullptr, OPT_CLONE},
256       {"clone-by-name", required_argument, nullptr, OPT_CLONE_BY_NAME},
257       {"clone-for-bugreport", no_argument, nullptr, OPT_CLONE_SKIP_FILTER},
258       {"is_detached", required_argument, nullptr, OPT_IS_DETACHED},
259       {"stop", no_argument, nullptr, OPT_STOP},
260       {"query", no_argument, nullptr, OPT_QUERY},
261       {"long", no_argument, nullptr, OPT_LONG},
262       {"query-raw", no_argument, nullptr, OPT_QUERY_RAW},
263       {"version", no_argument, nullptr, OPT_VERSION},
264       {"save-for-bugreport", no_argument, nullptr, OPT_BUGREPORT},
265       {"save-all-for-bugreport", no_argument, nullptr, OPT_BUGREPORT_ALL},
266       {nullptr, 0, nullptr, 0}};
267 
268   std::string config_file_name;
269   std::string trace_config_raw;
270   bool parse_as_pbtxt = false;
271   TraceConfig::StatsdMetadata statsd_metadata;
272 
273   ConfigOptions config_options;
274   bool has_config_options = false;
275 
276   if (argc <= 1) {
277     PrintUsage(argv[0]);
278     return 1;
279   }
280 
281   // getopt is not thread safe and cmdline parsing requires a mutex for the case
282   // of concurrent cmdline parsing for bugreport snapshots.
283   static base::NoDestructor<std::mutex> getopt_mutex;
284   std::unique_lock<std::mutex> getopt_lock(getopt_mutex.ref());
285 
286   optind = 1;  // Reset getopt state. It's reused by the snapshot thread.
287   for (;;) {
288     int option =
289         getopt_long(argc, argv, "hc:o:dDt:b:s:a:", long_options, nullptr);
290 
291     if (option == -1)
292       break;  // EOF.
293 
294     if (option == 'c') {
295       config_file_name = std::string(optarg);
296       if (strcmp(optarg, "-") == 0) {
297 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
298         // We don't want the runtime to replace "\n" with "\r\n" on `std::cin`.
299         _setmode(_fileno(stdin), _O_BINARY);
300 #endif
301         std::istreambuf_iterator<char> begin(std::cin), end;
302         trace_config_raw.assign(begin, end);
303       } else if (strcmp(optarg, ":test") == 0) {
304         TraceConfig test_config;
305         ConfigOptions opts;
306         opts.time = "2s";
307         opts.categories.emplace_back("sched/sched_switch");
308         opts.categories.emplace_back("power/cpu_idle");
309         opts.categories.emplace_back("power/cpu_frequency");
310         opts.categories.emplace_back("power/gpu_frequency");
311         PERFETTO_CHECK(CreateConfigFromOptions(opts, &test_config));
312         trace_config_raw = test_config.SerializeAsString();
313       } else if (strcmp(optarg, ":mem") == 0) {
314         // This is used by OnCloneSnapshotTriggerReceived(), which passes the
315         // original trace config as a member field. This is needed because, in
316         // the new PerfettoCmd instance, we need to know upfront trace config
317         // fields that affect the behaviour of perfetto_cmd, e.g., the guardrail
318         // overrides, the unique_session_name, the reporter API package etc.
319         PERFETTO_CHECK(!snapshot_config_.empty());
320         trace_config_raw = snapshot_config_;
321       } else {
322         if (!base::ReadFile(optarg, &trace_config_raw)) {
323 #if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
324           PERFETTO_PLOG(
325               "Could not open %s. If this is a permission denied error, try "
326               "placing the config in /data/misc/perfetto-configs: Perfetto "
327               "should always be able to access this directory.",
328               optarg);
329 #else
330           PERFETTO_PLOG("Could not open %s", optarg);
331 #endif
332           return 1;
333         }
334       }
335       continue;
336     }
337 
338     if (option == 'o') {
339       trace_out_path_ = optarg;
340       continue;
341     }
342 
343     if (option == 'd') {
344       background_ = true;
345       continue;
346     }
347 
348     if (option == 'D') {
349       background_ = true;
350       background_wait_ = true;
351       continue;
352     }
353 
354     if (option == OPT_CLONE) {
355       clone_tsid_ = static_cast<TracingSessionID>(atoll(optarg));
356       continue;
357     }
358 
359     if (option == OPT_CLONE_BY_NAME) {
360       clone_name_ = optarg;
361       continue;
362     }
363 
364     if (option == OPT_CLONE_SKIP_FILTER) {
365       clone_for_bugreport_ = true;
366       continue;
367     }
368 
369     if (option == 't') {
370       has_config_options = true;
371       config_options.time = std::string(optarg);
372       continue;
373     }
374 
375     if (option == 'b') {
376       has_config_options = true;
377       config_options.buffer_size = std::string(optarg);
378       continue;
379     }
380 
381     if (option == 's') {
382       has_config_options = true;
383       config_options.max_file_size = std::string(optarg);
384       continue;
385     }
386 
387     if (option == 'a') {
388       config_options.atrace_apps.push_back(std::string(optarg));
389       has_config_options = true;
390       continue;
391     }
392 
393     if (option == OPT_UPLOAD) {
394 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
395       upload_flag_ = true;
396       continue;
397 #else
398       PERFETTO_ELOG("--upload is only supported on Android");
399       return 1;
400 #endif
401     }
402 
403     if (option == OPT_DROPBOX) {
404 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
405       PERFETTO_CHECK(optarg);
406       upload_flag_ = true;
407       continue;
408 #else
409       PERFETTO_ELOG("--dropbox is only supported on Android");
410       return 1;
411 #endif
412     }
413 
414     if (option == OPT_PBTXT_CONFIG) {
415       parse_as_pbtxt = true;
416       continue;
417     }
418 
419     if (option == OPT_IGNORE_GUARDRAILS) {
420       ignore_guardrails_ = true;
421       continue;
422     }
423 
424     if (option == OPT_RESET_GUARDRAILS) {
425       PERFETTO_ILOG(
426           "Guardrails no longer exist in perfetto_cmd; this option only exists "
427           "for backwards compatability.");
428       return 0;
429     }
430 
431     if (option == OPT_ALERT_ID) {
432       statsd_metadata.set_triggering_alert_id(atoll(optarg));
433       continue;
434     }
435 
436     if (option == OPT_CONFIG_ID) {
437       statsd_metadata.set_triggering_config_id(atoll(optarg));
438       continue;
439     }
440 
441     if (option == OPT_CONFIG_UID) {
442       statsd_metadata.set_triggering_config_uid(atoi(optarg));
443       continue;
444     }
445 
446     if (option == OPT_SUBSCRIPTION_ID) {
447       statsd_metadata.set_triggering_subscription_id(atoll(optarg));
448       continue;
449     }
450 
451     if (option == OPT_DETACH) {
452       detach_key_ = std::string(optarg);
453       PERFETTO_CHECK(!detach_key_.empty());
454       continue;
455     }
456 
457     if (option == OPT_ATTACH) {
458       attach_key_ = std::string(optarg);
459       PERFETTO_CHECK(!attach_key_.empty());
460       continue;
461     }
462 
463     if (option == OPT_IS_DETACHED) {
464       attach_key_ = std::string(optarg);
465       redetach_once_attached_ = true;
466       PERFETTO_CHECK(!attach_key_.empty());
467       continue;
468     }
469 
470     if (option == OPT_STOP) {
471       stop_trace_once_attached_ = true;
472       continue;
473     }
474 
475     if (option == OPT_QUERY) {
476       query_service_ = true;
477       continue;
478     }
479 
480     if (option == OPT_LONG) {
481       query_service_long_ = true;
482       continue;
483     }
484 
485     if (option == OPT_QUERY_RAW) {
486       query_service_ = true;
487       query_service_output_raw_ = true;
488       continue;
489     }
490 
491     if (option == OPT_VERSION) {
492       printf("%s\n", base::GetVersionString());
493       return 0;
494     }
495 
496     if (option == OPT_BUGREPORT) {
497       bugreport_ = true;
498       continue;
499     }
500 
501     if (option == OPT_BUGREPORT_ALL) {
502       clone_all_bugreport_traces_ = true;
503       continue;
504     }
505 
506     PrintUsage(argv[0]);
507     return 1;
508   }
509 
510   for (ssize_t i = optind; i < argc; i++) {
511     has_config_options = true;
512     config_options.categories.push_back(argv[i]);
513   }
514   getopt_lock.unlock();
515 
516   if (query_service_ && (is_detach() || is_attach() || background_)) {
517     PERFETTO_ELOG("--query cannot be combined with any other argument");
518     return 1;
519   }
520 
521   if (query_service_long_ && !query_service_) {
522     PERFETTO_ELOG("--long can only be used with --query");
523     return 1;
524   }
525 
526   if (is_detach() && is_attach()) {
527     PERFETTO_ELOG("--attach and --detach are mutually exclusive");
528     return 1;
529   }
530 
531   if (is_detach() && background_) {
532     PERFETTO_ELOG("--detach and --background are mutually exclusive");
533     return 1;
534   }
535 
536   if (stop_trace_once_attached_ && !is_attach()) {
537     PERFETTO_ELOG("--stop is supported only in combination with --attach");
538     return 1;
539   }
540 
541   if ((bugreport_ || clone_all_bugreport_traces_) &&
542       (is_attach() || is_detach() || query_service_ || has_config_options ||
543        background_wait_)) {
544     PERFETTO_ELOG("--save-for-bugreport cannot take any other argument");
545     return 1;
546   }
547 
548   if (clone_tsid_ && !clone_name_.empty()) {
549     PERFETTO_ELOG("--clone and --clone-by-name are mutually exclusive");
550     return 1;
551   }
552 
553   if (clone_for_bugreport_ && !is_clone()) {
554     PERFETTO_ELOG("--clone-for-bugreport requires --clone or --clone-by-name");
555     return 1;
556   }
557 
558   // --save-for-bugreport is the equivalent of:
559   // --clone kBugreportSessionId -o /data/misc/perfetto-traces/bugreport/...
560   if (bugreport_ && trace_out_path_.empty()) {
561     PERFETTO_LOG("Invoked perfetto with --save-for-bugreport");
562     clone_tsid_ = kBugreportSessionId;
563     clone_for_bugreport_ = true;
564     trace_out_path_ = GetBugreportTracePath();
565   }
566 
567   // Parse the trace config. It can be either:
568   // 1) A proto-encoded file/stdin (-c ...).
569   // 2) A proto-text file/stdin (-c ... --txt).
570   // 3) A set of option arguments (-t 10s -s 10m).
571   // The only cases in which a trace config is not expected is --attach.
572   // For this we are just acting on already existing sessions.
573   trace_config_.reset(new TraceConfig());
574 
575   bool parsed = false;
576   bool cfg_could_be_txt = false;
577   const bool will_trace_or_trigger =
578       !is_attach() && !query_service_ && !clone_all_bugreport_traces_;
579   if (!will_trace_or_trigger) {
580     if ((!trace_config_raw.empty() || has_config_options)) {
581       PERFETTO_ELOG("Cannot specify a trace config with this option");
582       return 1;
583     }
584   } else if (has_config_options) {
585     if (!trace_config_raw.empty()) {
586       PERFETTO_ELOG(
587           "Cannot specify both -c/--config and any of --time, --size, "
588           "--buffer, --app, ATRACE_CAT, FTRACE_EVENT");
589       return 1;
590     }
591     parsed = CreateConfigFromOptions(config_options, trace_config_.get());
592   } else {
593     if (trace_config_raw.empty() && !is_clone()) {
594       PERFETTO_ELOG("The TraceConfig is empty");
595       return 1;
596     }
597     PERFETTO_DLOG("Parsing TraceConfig, %zu bytes", trace_config_raw.size());
598     if (parse_as_pbtxt) {
599       parsed = ParseTraceConfigPbtxt(config_file_name, trace_config_raw,
600                                      trace_config_.get());
601     } else {
602       parsed = trace_config_->ParseFromString(trace_config_raw);
603       cfg_could_be_txt =
604           !parsed && std::all_of(trace_config_raw.begin(),
605                                  trace_config_raw.end(), [](char c) {
606                                    // This is equiv to: isprint(c) || isspace(x)
607                                    // but doesn't depend on and load the locale.
608                                    return (c >= 32 && c <= 126) ||
609                                           (c >= 9 && c <= 13);
610                                  });
611     }
612   }
613 
614   if (parsed) {
615     *trace_config_->mutable_statsd_metadata() = std::move(statsd_metadata);
616     trace_config_raw.clear();
617   } else if (will_trace_or_trigger && !is_clone()) {
618     PERFETTO_ELOG("The trace config is invalid, bailing out.");
619     if (cfg_could_be_txt) {
620       PERFETTO_ELOG(
621           "Looks like you are passing a textual config but I'm expecting a "
622           "proto-encoded binary config.");
623       PERFETTO_ELOG("Try adding --txt to the cmdline.");
624     }
625     return 1;
626   }
627 
628   if (trace_config_->trace_uuid_lsb() == 0 &&
629       trace_config_->trace_uuid_msb() == 0) {
630     base::Uuid uuid = base::Uuidv4();
631     if (trace_config_->statsd_metadata().triggering_subscription_id()) {
632       uuid.set_lsb(
633           trace_config_->statsd_metadata().triggering_subscription_id());
634     }
635     uuid_ = uuid.ToString();
636     trace_config_->set_trace_uuid_msb(uuid.msb());
637     trace_config_->set_trace_uuid_lsb(uuid.lsb());
638   } else {
639     base::Uuid uuid(trace_config_->trace_uuid_lsb(),
640                     trace_config_->trace_uuid_msb());
641     uuid_ = uuid.ToString();
642   }
643 
644   const auto& delay = trace_config_->cmd_trace_start_delay();
645   if (delay.has_max_delay_ms() != delay.has_min_delay_ms()) {
646     PERFETTO_ELOG("cmd_trace_start_delay field is only partially specified.");
647     return 1;
648   }
649 
650   bool has_incidentd_package =
651       !trace_config_->incident_report_config().destination_package().empty();
652   if (has_incidentd_package && !upload_flag_) {
653     PERFETTO_ELOG(
654         "Unexpected IncidentReportConfig without --dropbox / --upload.");
655     return 1;
656   }
657 
658   bool has_android_reporter_package = !trace_config_->android_report_config()
659                                            .reporter_service_package()
660                                            .empty();
661   if (has_android_reporter_package && !upload_flag_) {
662     PERFETTO_ELOG(
663         "Unexpected AndroidReportConfig without --dropbox / --upload.");
664     return 1;
665   }
666 
667   if (has_incidentd_package && has_android_reporter_package) {
668     PERFETTO_ELOG(
669         "Only one of IncidentReportConfig and AndroidReportConfig "
670         "allowed in the same config.");
671     return 1;
672   }
673 
674   // If the upload flag is set, we can only be doing one of three things:
675   // 1. Reporting to either incidentd or Android framework.
676   // 2. Skipping incidentd/Android report because it was explicitly
677   //    specified in the config.
678   // 3. Activating triggers.
679   bool incidentd_valid =
680       has_incidentd_package ||
681       trace_config_->incident_report_config().skip_incidentd();
682   bool android_report_valid =
683       has_android_reporter_package ||
684       trace_config_->android_report_config().skip_report();
685   bool has_triggers = !trace_config_->activate_triggers().empty();
686   if (upload_flag_ && !incidentd_valid && !android_report_valid &&
687       !has_triggers) {
688     PERFETTO_ELOG(
689         "One of IncidentReportConfig, AndroidReportConfig or activate_triggers "
690         "must be specified with --dropbox / --upload.");
691     return 1;
692   }
693 
694   // Only save to incidentd if:
695   // 1) |destination_package| is set
696   // 2) |skip_incidentd| is absent or false.
697   // 3) we are not simply activating triggers.
698   save_to_incidentd_ =
699       has_incidentd_package &&
700       !trace_config_->incident_report_config().skip_incidentd() &&
701       !has_triggers;
702 
703   // Only report to the Andorid framework if:
704   // 1) |reporter_service_package| is set
705   // 2) |skip_report| is absent or false.
706   // 3) we are not simply activating triggers.
707   report_to_android_framework_ =
708       has_android_reporter_package &&
709       !trace_config_->android_report_config().skip_report() && !has_triggers;
710 
711   // Respect the wishes of the config with respect to statsd logging or fall
712   // back on the presence of the --upload flag if not set.
713   switch (trace_config_->statsd_logging()) {
714     case TraceConfig::STATSD_LOGGING_ENABLED:
715       statsd_logging_ = true;
716       break;
717     case TraceConfig::STATSD_LOGGING_DISABLED:
718       statsd_logging_ = false;
719       break;
720     case TraceConfig::STATSD_LOGGING_UNSPECIFIED:
721       statsd_logging_ = upload_flag_;
722       break;
723   }
724   trace_config_->set_statsd_logging(statsd_logging_
725                                         ? TraceConfig::STATSD_LOGGING_ENABLED
726                                         : TraceConfig::STATSD_LOGGING_DISABLED);
727 
728   // Set up the output file. Either --out or --upload are expected, with the
729   // only exception of --attach. In this case the output file is passed when
730   // detaching.
731   if (!trace_out_path_.empty() && upload_flag_) {
732     PERFETTO_ELOG(
733         "Can't log to a file (--out) and incidentd (--upload) at the same "
734         "time");
735     return 1;
736   }
737 
738   if (!trace_config_->output_path().empty()) {
739     if (!trace_out_path_.empty() || upload_flag_) {
740       PERFETTO_ELOG(
741           "Can't pass --out or --upload if output_path is set in the "
742           "trace config");
743       return 1;
744     }
745     if (base::FileExists(trace_config_->output_path())) {
746       PERFETTO_ELOG(
747           "The output_path must not exist, the service cannot overwrite "
748           "existing files for security reasons. Remove %s or use a different "
749           "path.",
750           trace_config_->output_path().c_str());
751       return 1;
752     }
753   }
754 
755   // |activate_triggers| in the trace config is shorthand for trigger_perfetto.
756   // In this case we don't intend to send any trace config to the service,
757   // rather use that as a signal to the cmdline client to connect as a producer
758   // and activate triggers.
759   if (has_triggers) {
760     for (const auto& trigger : trace_config_->activate_triggers()) {
761       triggers_to_activate_.push_back(trigger);
762     }
763     trace_config_.reset(new TraceConfig());
764   }
765 
766   bool open_out_file = true;
767   if (!will_trace_or_trigger) {
768     open_out_file = false;
769     if (!trace_out_path_.empty() || upload_flag_) {
770       PERFETTO_ELOG("Can't pass an --out file (or --upload) with this option");
771       return 1;
772     }
773   } else if (!triggers_to_activate_.empty() ||
774              (trace_config_->write_into_file() &&
775               !trace_config_->output_path().empty())) {
776     open_out_file = false;
777   } else if (trace_out_path_.empty() && !upload_flag_) {
778     PERFETTO_ELOG("Either --out or --upload is required");
779     return 1;
780   } else if (is_detach() && !trace_config_->write_into_file()) {
781     // In detached mode we must pass the file descriptor to the service and
782     // let that one write the trace. We cannot use the IPC readback code path
783     // because the client process is about to exit soon after detaching.
784     // We could support detach && !write_into_file, but that would make the
785     // cmdline logic more complex. The feasible configurations are:
786     // 1. Using write_into_file and passing the file path on the --detach call.
787     // 2. Using pure ring-buffer mode, setting write_into_file = false and
788     //    passing the output file path to the --attach call.
789     // This is too complicated and harder to reason about, so we support only 1.
790     // Traceur gets around this by always setting write_into_file and specifying
791     // file_write_period_ms = 1week (which effectively means: write into the
792     // file only at the end of the trace) to achieve ring buffer traces.
793     PERFETTO_ELOG(
794         "TraceConfig's write_into_file must be true when using --detach");
795     return 1;
796   }
797   if (open_out_file) {
798     if (!OpenOutputFile())
799       return 1;
800     if (!trace_config_->write_into_file())
801       packet_writer_.emplace(trace_out_stream_.get());
802   }
803 
804   bool will_trace_indefinitely =
805       trace_config_->duration_ms() == 0 &&
806       trace_config_->trigger_config().trigger_timeout_ms() == 0;
807   if (will_trace_indefinitely && save_to_incidentd_ && !ignore_guardrails_) {
808     PERFETTO_ELOG("Can't trace indefinitely when tracing to Incidentd.");
809     return 1;
810   }
811 
812   if (will_trace_indefinitely && report_to_android_framework_ &&
813       !ignore_guardrails_) {
814     PERFETTO_ELOG(
815         "Can't trace indefinitely when reporting to Android framework.");
816     return 1;
817   }
818 
819   if (background_) {
820     if (background_wait_) {
821 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
822       background_wait_pipe_ = base::Pipe::Create(base::Pipe::kRdNonBlock);
823 #endif
824     }
825 
826     PERFETTO_CHECK(snapshot_threads_.empty());  // No threads before Daemonize.
827     base::Daemonize([this]() -> int {
828       background_wait_pipe_.wr.reset();
829 
830       if (background_wait_) {
831         return WaitOnBgProcessPipe();
832       }
833 
834       return 0;
835     });
836     background_wait_pipe_.rd.reset();
837   }
838 
839   return std::nullopt;  // Continues in ConnectToServiceRunAndMaybeNotify()
840                         // below.
841 }
842 
NotifyBgProcessPipe(BgProcessStatus status)843 void PerfettoCmd::NotifyBgProcessPipe(BgProcessStatus status) {
844 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
845   if (!background_wait_pipe_.wr) {
846     return;
847   }
848   static_assert(sizeof status == 1, "Enum bigger than one byte");
849   PERFETTO_EINTR(write(background_wait_pipe_.wr.get(), &status, 1));
850   background_wait_pipe_.wr.reset();
851 #else   // PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
852   base::ignore_result(status);
853 #endif  //! PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
854 }
855 
WaitOnBgProcessPipe()856 PerfettoCmd::BgProcessStatus PerfettoCmd::WaitOnBgProcessPipe() {
857 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
858   base::ScopedPlatformHandle fd = std::move(background_wait_pipe_.rd);
859   PERFETTO_CHECK(fd);
860 
861   BgProcessStatus msg;
862   static_assert(sizeof msg == 1, "Enum bigger than one byte");
863   std::array<pollfd, 1> pollfds = {pollfd{fd.get(), POLLIN, 0}};
864 
865   int ret = PERFETTO_EINTR(poll(&pollfds[0], pollfds.size(), 30000 /*ms*/));
866   PERFETTO_CHECK(ret >= 0);
867   if (ret == 0) {
868     fprintf(stderr, "Timeout waiting for all data sources to start\n");
869     return kBackgroundTimeout;
870   }
871   ssize_t read_ret = PERFETTO_EINTR(read(fd.get(), &msg, 1));
872   PERFETTO_CHECK(read_ret >= 0);
873   if (read_ret == 0) {
874     fprintf(stderr, "Background process didn't report anything\n");
875     return kBackgroundOtherError;
876   }
877 
878   if (msg != kBackgroundOk) {
879     fprintf(stderr, "Background process failed, BgProcessStatus=%d\n",
880             static_cast<int>(msg));
881     return msg;
882   }
883 #endif  //! PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
884 
885   return kBackgroundOk;
886 }
887 
ConnectToServiceRunAndMaybeNotify()888 int PerfettoCmd::ConnectToServiceRunAndMaybeNotify() {
889   int exit_code = ConnectToServiceAndRun();
890 
891   NotifyBgProcessPipe(exit_code == 0 ? kBackgroundOk : kBackgroundOtherError);
892 
893   return exit_code;
894 }
895 
ConnectToServiceAndRun()896 int PerfettoCmd::ConnectToServiceAndRun() {
897   // If we are just activating triggers then we don't need to rate limit,
898   // connect as a consumer or run the trace. So bail out after processing all
899   // the options.
900   if (!triggers_to_activate_.empty()) {
901     bool finished_with_success = false;
902     auto weak_this = weak_factory_.GetWeakPtr();
903     TriggerProducer producer(
904         &task_runner_,
905         [weak_this, &finished_with_success](bool success) {
906           if (!weak_this)
907             return;
908           finished_with_success = success;
909           weak_this->task_runner_.Quit();
910         },
911         &triggers_to_activate_);
912     task_runner_.Run();
913     return finished_with_success ? 0 : 1;
914   }  // if (triggers_to_activate_)
915 
916   if (query_service_) {
917     consumer_endpoint_ =
918         ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
919     task_runner_.Run();
920     return 1;  // We can legitimately get here if the service disconnects.
921   }
922 
923   if (!trace_config_->unique_session_name().empty())
924     base::MaybeSetThreadName("p-" + trace_config_->unique_session_name());
925 
926   expected_duration_ms_ = trace_config_->duration_ms();
927   if (!expected_duration_ms_) {
928     uint32_t timeout_ms = trace_config_->trigger_config().trigger_timeout_ms();
929     uint32_t max_stop_delay_ms = 0;
930     for (const auto& trigger : trace_config_->trigger_config().triggers()) {
931       max_stop_delay_ms = std::max(max_stop_delay_ms, trigger.stop_delay_ms());
932     }
933     expected_duration_ms_ = timeout_ms + max_stop_delay_ms;
934   }
935 
936   const auto& delay = trace_config_->cmd_trace_start_delay();
937   if (delay.has_min_delay_ms()) {
938     PERFETTO_DCHECK(delay.has_max_delay_ms());
939     std::random_device r;
940     std::minstd_rand minstd(r());
941     std::uniform_int_distribution<uint32_t> dist(delay.min_delay_ms(),
942                                                  delay.max_delay_ms());
943     std::this_thread::sleep_for(std::chrono::milliseconds(dist(minstd)));
944   }
945 
946   if (is_clone()) {
947     if (!snapshot_trigger_info_.has_value()) {
948       LogUploadEvent(PerfettoStatsdAtom::kCmdCloneTraceBegin);
949     } else {
950       LogUploadEvent(PerfettoStatsdAtom::kCmdCloneTriggerTraceBegin,
951                      snapshot_trigger_info_->trigger_name);
952     }
953   } else if (trace_config_->trigger_config().trigger_timeout_ms() == 0) {
954     LogUploadEvent(PerfettoStatsdAtom::kTraceBegin);
955   } else {
956     LogUploadEvent(PerfettoStatsdAtom::kBackgroundTraceBegin);
957   }
958 
959 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
960   if (!background_ && !is_detach() && !upload_flag_ &&
961       triggers_to_activate_.empty() && !isatty(STDIN_FILENO) &&
962       !isatty(STDERR_FILENO) && getenv("TERM")) {
963     fprintf(stderr,
964             "Warning: No PTY. CTRL+C won't gracefully stop the trace. If you "
965             "are running perfetto via adb shell, use the -tt arg (adb shell "
966             "-t perfetto ...) or consider using the helper script "
967             "tools/record_android_trace from the Perfetto repository.\n\n");
968   }
969 #endif
970 
971   consumer_endpoint_ =
972       ConsumerIPCClient::Connect(GetConsumerSocket(), this, &task_runner_);
973   SetupCtrlCSignalHandler();
974   task_runner_.Run();
975 
976   return tracing_succeeded_ ? 0 : 1;
977 }
978 
OnConnect()979 void PerfettoCmd::OnConnect() {
980   connected_ = true;
981   LogUploadEvent(PerfettoStatsdAtom::kOnConnect);
982 
983   uint32_t events_mask = 0;
984   if (GetTriggerMode(*trace_config_) ==
985       TraceConfig::TriggerConfig::CLONE_SNAPSHOT) {
986     events_mask |= ObservableEvents::TYPE_CLONE_TRIGGER_HIT;
987   }
988   if (background_wait_) {
989     events_mask |= ObservableEvents::TYPE_ALL_DATA_SOURCES_STARTED;
990   }
991   if (events_mask) {
992     consumer_endpoint_->ObserveEvents(events_mask);
993   }
994 
995   if (query_service_) {
996     consumer_endpoint_->QueryServiceState(
997         {}, [this](bool success, const TracingServiceState& svc_state) {
998           PrintServiceState(success, svc_state);
999           fflush(stdout);
1000           exit(success ? 0 : 1);
1001         });
1002     return;
1003   }
1004 
1005   if (clone_all_bugreport_traces_) {
1006     ConsumerEndpoint::QueryServiceStateArgs args;
1007     // Reduces the size of the IPC reply skipping data sources and producers.
1008     args.sessions_only = true;
1009     auto weak_this = weak_factory_.GetWeakPtr();
1010     consumer_endpoint_->QueryServiceState(
1011         args, [weak_this](bool success, const TracingServiceState& svc_state) {
1012           if (weak_this)
1013             weak_this->CloneAllBugreportTraces(success, svc_state);
1014         });
1015     return;
1016   }
1017 
1018   if (is_attach()) {
1019     consumer_endpoint_->Attach(attach_key_);
1020     return;
1021   }
1022 
1023   if (is_clone()) {
1024     task_runner_.PostDelayedTask(std::bind(&PerfettoCmd::OnTimeout, this),
1025                                  kCloneTimeoutMs);
1026     ConsumerEndpoint::CloneSessionArgs args;
1027     args.skip_trace_filter = clone_for_bugreport_;
1028     args.for_bugreport = clone_for_bugreport_;
1029     if (clone_tsid_.has_value()) {
1030       args.tsid = *clone_tsid_;
1031     } else if (!clone_name_.empty()) {
1032       args.unique_session_name = clone_name_;
1033     }
1034     if (snapshot_trigger_info_.has_value()) {
1035       args.clone_trigger_name = snapshot_trigger_info_->trigger_name;
1036       args.clone_trigger_producer_name = snapshot_trigger_info_->producer_name;
1037       args.clone_trigger_trusted_producer_uid =
1038           snapshot_trigger_info_->producer_uid;
1039       args.clone_trigger_boot_time_ns = snapshot_trigger_info_->boot_time_ns;
1040     }
1041     consumer_endpoint_->CloneSession(std::move(args));
1042     return;
1043   }
1044 
1045   if (expected_duration_ms_) {
1046     PERFETTO_LOG("Connected to the Perfetto traced service, TTL: %ds",
1047                  (expected_duration_ms_ + 999) / 1000);
1048   } else {
1049     PERFETTO_LOG("Connected to the Perfetto traced service, starting tracing");
1050   }
1051 
1052   PERFETTO_DCHECK(trace_config_);
1053   trace_config_->set_enable_extra_guardrails(
1054       (save_to_incidentd_ || report_to_android_framework_) &&
1055       !ignore_guardrails_);
1056 
1057   // Set the statsd logging flag if we're uploading
1058 
1059   base::ScopedFile optional_fd;
1060   if (trace_config_->write_into_file() && trace_config_->output_path().empty())
1061     optional_fd.reset(dup(fileno(*trace_out_stream_)));
1062 
1063   consumer_endpoint_->EnableTracing(*trace_config_, std::move(optional_fd));
1064 
1065   if (is_detach()) {
1066     consumer_endpoint_->Detach(detach_key_);  // Will invoke OnDetach() soon.
1067     return;
1068   }
1069 
1070   // Failsafe mechanism to avoid waiting indefinitely if the service hangs.
1071   // Note: when using prefer_suspend_clock_for_duration the actual duration
1072   // might be < expected_duration_ms_ measured in in wall time. But this is fine
1073   // because the resulting timeout will be conservative (it will be accut
1074   // if the device never suspends, and will be more lax if it does).
1075   if (expected_duration_ms_) {
1076     uint32_t trace_timeout = expected_duration_ms_ + 60000 +
1077                              trace_config_->flush_timeout_ms() +
1078                              trace_config_->data_source_stop_timeout_ms();
1079     task_runner_.PostDelayedTask(std::bind(&PerfettoCmd::OnTimeout, this),
1080                                  trace_timeout);
1081   }
1082 }
1083 
OnDisconnect()1084 void PerfettoCmd::OnDisconnect() {
1085   if (connected_) {
1086     PERFETTO_LOG("Disconnected from the traced service");
1087   } else {
1088 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1089     static const char kDocUrl[] =
1090         "https://perfetto.dev/docs/quickstart/android-tracing";
1091 #else
1092     static const char kDocUrl[] =
1093         "https://perfetto.dev/docs/quickstart/linux-tracing";
1094 #endif
1095     PERFETTO_LOG(
1096         "Could not connect to the traced socket %s. Ensure traced is "
1097         "running or use tracebox. See %s.",
1098         GetConsumerSocket(), kDocUrl);
1099   }
1100 
1101   connected_ = false;
1102   task_runner_.Quit();
1103 }
1104 
OnTimeout()1105 void PerfettoCmd::OnTimeout() {
1106   PERFETTO_ELOG("Timed out while waiting for trace from the service, aborting");
1107   LogUploadEvent(PerfettoStatsdAtom::kOnTimeout);
1108   task_runner_.Quit();
1109 }
1110 
CheckTraceDataTimeout()1111 void PerfettoCmd::CheckTraceDataTimeout() {
1112   if (trace_data_timeout_armed_) {
1113     PERFETTO_ELOG("Timed out while waiting for OnTraceData, aborting");
1114     FinalizeTraceAndExit();
1115   }
1116   trace_data_timeout_armed_ = true;
1117   task_runner_.PostDelayedTask(
1118       std::bind(&PerfettoCmd::CheckTraceDataTimeout, this),
1119       kOnTraceDataTimeoutMs);
1120 }
1121 
OnTraceData(std::vector<TracePacket> packets,bool has_more)1122 void PerfettoCmd::OnTraceData(std::vector<TracePacket> packets, bool has_more) {
1123   trace_data_timeout_armed_ = false;
1124 
1125   PERFETTO_CHECK(packet_writer_.has_value());
1126   if (!packet_writer_->WritePackets(packets)) {
1127     PERFETTO_ELOG("Failed to write packets");
1128     FinalizeTraceAndExit();
1129   }
1130 
1131   if (!has_more)
1132     FinalizeTraceAndExit();  // Reached end of trace.
1133 }
1134 
OnTracingDisabled(const std::string & error)1135 void PerfettoCmd::OnTracingDisabled(const std::string& error) {
1136   ReadbackTraceDataAndQuit(error);
1137 }
1138 
ReadbackTraceDataAndQuit(const std::string & error)1139 void PerfettoCmd::ReadbackTraceDataAndQuit(const std::string& error) {
1140   if (!error.empty()) {
1141     // Some of these errors (e.g. unique session name already exists) are soft
1142     // errors and likely to happen in nominal condition. As such they shouldn't
1143     // be marked as "E" in the event log. Hence why LOG and not ELOG here.
1144     PERFETTO_LOG("Service error: %s", error.c_str());
1145 
1146     // In case of errors don't leave a partial file around. This happens
1147     // frequently in the case of --save-for-bugreport if there is no eligible
1148     // trace. See also b/279753347 .
1149     if (bytes_written_ == 0 && !trace_out_path_.empty() &&
1150         trace_out_path_ != "-") {
1151       remove(trace_out_path_.c_str());
1152     }
1153 
1154     // Even though there was a failure, we mark this as success for legacy
1155     // reasons: when guardrails used to exist in perfetto_cmd, this codepath
1156     // would still cause guardrails to be written and the exit code to be 0.
1157     //
1158     // We want to preserve that semantic and the easiest way to do that would
1159     // be to set |tracing_succeeded_| to true.
1160     tracing_succeeded_ = true;
1161     task_runner_.Quit();
1162     return;
1163   }
1164 
1165   // Make sure to only log this atom if |error| is empty; traced
1166   // would have logged a terminal error atom corresponding to |error|
1167   // and we don't want to log anything after that.
1168   LogUploadEvent(PerfettoStatsdAtom::kOnTracingDisabled);
1169 
1170   if (trace_config_->write_into_file()) {
1171     // If write_into_file == true, at this point the passed file contains
1172     // already all the packets.
1173     return FinalizeTraceAndExit();
1174   }
1175 
1176   trace_data_timeout_armed_ = false;
1177   CheckTraceDataTimeout();
1178 
1179   // This will cause a bunch of OnTraceData callbacks. The last one will
1180   // save the file and exit.
1181   consumer_endpoint_->ReadBuffers();
1182 }
1183 
FinalizeTraceAndExit()1184 void PerfettoCmd::FinalizeTraceAndExit() {
1185   LogUploadEvent(PerfettoStatsdAtom::kFinalizeTraceAndExit);
1186   packet_writer_.reset();
1187 
1188   if (trace_out_stream_) {
1189     fseek(*trace_out_stream_, 0, SEEK_END);
1190     off_t sz = ftell(*trace_out_stream_);
1191     if (sz > 0)
1192       bytes_written_ = static_cast<size_t>(sz);
1193   }
1194 
1195   if (save_to_incidentd_) {
1196 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1197     SaveTraceIntoIncidentOrCrash();
1198 #endif
1199   } else if (report_to_android_framework_) {
1200 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1201     ReportTraceToAndroidFrameworkOrCrash();
1202 #endif
1203   } else {
1204     trace_out_stream_.reset();
1205     if (trace_config_->write_into_file()) {
1206       // trace_out_path_ might be empty in the case of --attach.
1207       PERFETTO_LOG("Trace written into the output file");
1208     } else {
1209       PERFETTO_LOG("Wrote %" PRIu64 " bytes into %s", bytes_written_,
1210                    trace_out_path_ == "-" ? "stdout" : trace_out_path_.c_str());
1211     }
1212   }
1213 
1214   tracing_succeeded_ = true;
1215   task_runner_.Quit();
1216 }
1217 
OpenOutputFile()1218 bool PerfettoCmd::OpenOutputFile() {
1219   base::ScopedFile fd;
1220   if (trace_out_path_.empty()) {
1221 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
1222     fd = CreateUnlinkedTmpFile();
1223 #endif
1224   } else if (trace_out_path_ == "-") {
1225     fd.reset(dup(fileno(stdout)));
1226   } else {
1227     fd = base::OpenFile(trace_out_path_, O_RDWR | O_CREAT | O_TRUNC, 0600);
1228   }
1229   if (!fd) {
1230     PERFETTO_PLOG(
1231         "Failed to open %s. If you get permission denied in "
1232         "/data/misc/perfetto-traces, the file might have been "
1233         "created by another user, try deleting it first.",
1234         trace_out_path_.c_str());
1235     return false;
1236   }
1237   trace_out_stream_.reset(fdopen(fd.release(), "wb"));
1238   PERFETTO_CHECK(trace_out_stream_);
1239   return true;
1240 }
1241 
SetupCtrlCSignalHandler()1242 void PerfettoCmd::SetupCtrlCSignalHandler() {
1243   // Only the main thread instance should handle CTRL+C.
1244   if (g_perfetto_cmd != this)
1245     return;
1246   ctrl_c_handler_installed_ = true;
1247   base::InstallCtrlCHandler([] {
1248     if (PerfettoCmd* main_thread = g_perfetto_cmd.load())
1249       main_thread->SignalCtrlC();
1250   });
1251   auto weak_this = weak_factory_.GetWeakPtr();
1252   task_runner_.AddFileDescriptorWatch(ctrl_c_evt_.fd(), [weak_this] {
1253     if (!weak_this)
1254       return;
1255     PERFETTO_LOG("SIGINT/SIGTERM received: disabling tracing.");
1256     weak_this->ctrl_c_evt_.Clear();
1257     weak_this->consumer_endpoint_->Flush(
1258         0,
1259         [weak_this](bool flush_success) {
1260           if (!weak_this)
1261             return;
1262           if (!flush_success)
1263             PERFETTO_ELOG("Final flush unsuccessful.");
1264           weak_this->consumer_endpoint_->DisableTracing();
1265         },
1266         FlushFlags(FlushFlags::Initiator::kPerfettoCmd,
1267                    FlushFlags::Reason::kTraceStop));
1268   });
1269 }
1270 
OnDetach(bool success)1271 void PerfettoCmd::OnDetach(bool success) {
1272   if (!success) {
1273     PERFETTO_ELOG("Session detach failed");
1274     exit(1);
1275   }
1276   exit(0);
1277 }
1278 
OnAttach(bool success,const TraceConfig & trace_config)1279 void PerfettoCmd::OnAttach(bool success, const TraceConfig& trace_config) {
1280   if (!success) {
1281     if (!redetach_once_attached_) {
1282       // Print an error message if attach fails, with the exception of the
1283       // --is_detached case, where we want to silently return.
1284       PERFETTO_ELOG("Session re-attach failed. Check service logs for details");
1285     }
1286     // Keep this exit code distinguishable from the general error code so
1287     // --is_detached can tell the difference between a general error and the
1288     // not-detached case.
1289     exit(2);
1290   }
1291 
1292   if (redetach_once_attached_) {
1293     consumer_endpoint_->Detach(attach_key_);  // Will invoke OnDetach() soon.
1294     return;
1295   }
1296 
1297   trace_config_.reset(new TraceConfig(trace_config));
1298   PERFETTO_DCHECK(trace_config_->write_into_file());
1299 
1300   if (stop_trace_once_attached_) {
1301     auto weak_this = weak_factory_.GetWeakPtr();
1302     consumer_endpoint_->Flush(
1303         0,
1304         [weak_this](bool flush_success) {
1305           if (!weak_this)
1306             return;
1307           if (!flush_success)
1308             PERFETTO_ELOG("Final flush unsuccessful.");
1309           weak_this->consumer_endpoint_->DisableTracing();
1310         },
1311         FlushFlags(FlushFlags::Initiator::kPerfettoCmd,
1312                    FlushFlags::Reason::kTraceStop));
1313   }
1314 }
1315 
OnTraceStats(bool,const TraceStats &)1316 void PerfettoCmd::OnTraceStats(bool /*success*/,
1317                                const TraceStats& /*trace_config*/) {
1318   // TODO(eseckler): Support GetTraceStats().
1319 }
1320 
OnSessionCloned(const OnSessionClonedArgs & args)1321 void PerfettoCmd::OnSessionCloned(const OnSessionClonedArgs& args) {
1322   PERFETTO_DLOG("Cloned tracing session %" PRIu64 ", name=\"%s\", success=%d",
1323                 clone_tsid_.value_or(0), clone_name_.c_str(), args.success);
1324   std::string full_error;
1325   if (!args.success) {
1326     std::string name;
1327     if (clone_tsid_.has_value()) {
1328       name = std::to_string(*clone_tsid_);
1329     } else {
1330       name = "\"" + clone_name_ + "\"";
1331     }
1332     full_error = "Failed to clone tracing session " + name + ": " + args.error;
1333   }
1334 
1335   // This is used with --save-all-for-bugreport, to pause all cloning threads
1336   // so that they first issue the clone and then proceed only after the service
1337   // has seen all the clone requests.
1338   if (on_session_cloned_) {
1339     std::function<void()> on_session_cloned(nullptr);
1340     std::swap(on_session_cloned, on_session_cloned_);
1341     on_session_cloned();
1342   }
1343 
1344   // Kick off the readback and file finalization (as if we started tracing and
1345   // reached the duration_ms timeout).
1346   uuid_ = args.uuid.ToString();
1347 
1348   // Log the new UUID with the clone tag.
1349   if (!snapshot_trigger_info_.has_value()) {
1350     LogUploadEvent(PerfettoStatsdAtom::kCmdOnSessionClone);
1351   } else {
1352     LogUploadEvent(PerfettoStatsdAtom::kCmdOnTriggerSessionClone,
1353                    snapshot_trigger_info_->trigger_name);
1354   }
1355   ReadbackTraceDataAndQuit(full_error);
1356 }
1357 
PrintServiceState(bool success,const TracingServiceState & svc_state)1358 void PerfettoCmd::PrintServiceState(bool success,
1359                                     const TracingServiceState& svc_state) {
1360   if (!success) {
1361     PERFETTO_ELOG("Failed to query the service state");
1362     return;
1363   }
1364 
1365   if (query_service_output_raw_) {
1366     std::string str = svc_state.SerializeAsString();
1367     fwrite(str.data(), 1, str.size(), stdout);
1368     return;
1369   }
1370 
1371   printf(
1372       "\x1b[31mNot meant for machine consumption. Use --query-raw for "
1373       "scripts.\x1b[0m\n\n");
1374   printf(
1375       "Service: %s\n"
1376       "Tracing sessions: %d (started: %d)\n",
1377       svc_state.tracing_service_version().c_str(), svc_state.num_sessions(),
1378       svc_state.num_sessions_started());
1379 
1380   printf(R"(
1381 
1382 PRODUCER PROCESSES CONNECTED:
1383 
1384 ID     PID      UID      FLAGS  NAME                                       SDK
1385 ==     ===      ===      =====  ====                                       ===
1386 )");
1387   for (const auto& producer : svc_state.producers()) {
1388     base::StackString<8> status("%s", producer.frozen() ? "F" : "");
1389     printf("%-6d %-8d %-8d %-6s %-42s %s\n", producer.id(), producer.pid(),
1390            producer.uid(), status.c_str(), producer.name().c_str(),
1391            producer.sdk_version().c_str());
1392   }
1393 
1394   printf(R"(
1395 
1396 DATA SOURCES REGISTERED:
1397 
1398 NAME                                     PRODUCER                     DETAILS
1399 ===                                      ========                     ========
1400 )");
1401   for (const auto& ds : svc_state.data_sources()) {
1402     char producer_id_and_name[128]{};
1403     const int ds_producer_id = ds.producer_id();
1404     for (const auto& producer : svc_state.producers()) {
1405       if (producer.id() == ds_producer_id) {
1406         base::SprintfTrunc(producer_id_and_name, sizeof(producer_id_and_name),
1407                            "%s (%d)", producer.name().c_str(), ds_producer_id);
1408         break;
1409       }
1410     }
1411 
1412     printf("%-40s %-28s ", ds.ds_descriptor().name().c_str(),
1413            producer_id_and_name);
1414     // Print the category names for clients using the track event SDK.
1415     std::string cats;
1416     if (!ds.ds_descriptor().track_event_descriptor_raw().empty()) {
1417       const std::string& raw = ds.ds_descriptor().track_event_descriptor_raw();
1418       protos::gen::TrackEventDescriptor desc;
1419       if (desc.ParseFromArray(raw.data(), raw.size())) {
1420         for (const auto& cat : desc.available_categories()) {
1421           cats.append(cats.empty() ? "" : ",");
1422           cats.append(cat.name());
1423         }
1424       }
1425     } else if (!ds.ds_descriptor().ftrace_descriptor_raw().empty()) {
1426       const std::string& raw = ds.ds_descriptor().ftrace_descriptor_raw();
1427       protos::gen::FtraceDescriptor desc;
1428       if (desc.ParseFromArray(raw.data(), raw.size())) {
1429         for (const auto& cat : desc.atrace_categories()) {
1430           cats.append(cats.empty() ? "" : ",");
1431           cats.append(cat.name());
1432         }
1433       }
1434     }
1435     const size_t kCatsShortLen = 40;
1436     if (!query_service_long_ && cats.length() > kCatsShortLen) {
1437       cats = cats.substr(0, kCatsShortLen);
1438       cats.append("... (use --long to expand)");
1439     }
1440     printf("%s\n", cats.c_str());
1441   }  // for data_sources()
1442 
1443   if (svc_state.supports_tracing_sessions()) {
1444     printf(R"(
1445 
1446 TRACING SESSIONS:
1447 
1448 ID      UID     STATE      BUF (#) KB   DUR (s)   #DS  STARTED  NAME
1449 ===     ===     =====      ==========   =======   ===  =======  ====
1450 )");
1451     for (const auto& sess : svc_state.tracing_sessions()) {
1452       uint32_t buf_tot_kb = 0;
1453       for (uint32_t kb : sess.buffer_size_kb())
1454         buf_tot_kb += kb;
1455       int sec =
1456           static_cast<int>((sess.start_realtime_ns() / 1000000000) % 86400);
1457       int h = sec / 3600;
1458       int m = (sec - (h * 3600)) / 60;
1459       int s = (sec - h * 3600 - m * 60);
1460       printf("%-7" PRIu64 " %-7d %-10s (%d) %-8u %-9u %-4u %02d:%02d:%02d %s\n",
1461              sess.id(), sess.consumer_uid(), sess.state().c_str(),
1462              sess.buffer_size_kb_size(), buf_tot_kb, sess.duration_ms() / 1000,
1463              sess.num_data_sources(), h, m, s,
1464              sess.unique_session_name().c_str());
1465     }  // for tracing_sessions()
1466 
1467     int sessions_listed = static_cast<int>(svc_state.tracing_sessions().size());
1468     if (sessions_listed != svc_state.num_sessions() &&
1469         base::GetCurrentUserId() != 0) {
1470       printf(
1471           "\n"
1472           "NOTE: Some tracing sessions are not reported in the list above.\n"
1473           "This is likely because they are owned by a different UID.\n"
1474           "If you want to list all session, run again this command as root.\n");
1475     }
1476   }  // if (supports_tracing_sessions)
1477 }
1478 
OnObservableEvents(const ObservableEvents & observable_events)1479 void PerfettoCmd::OnObservableEvents(
1480     const ObservableEvents& observable_events) {
1481   if (observable_events.all_data_sources_started()) {
1482     NotifyBgProcessPipe(kBackgroundOk);
1483   }
1484   if (observable_events.has_clone_trigger_hit()) {
1485     int64_t tsid = observable_events.clone_trigger_hit().tracing_session_id();
1486     SnapshotTriggerInfo trigger = {
1487         observable_events.clone_trigger_hit().boot_time_ns(),
1488         observable_events.clone_trigger_hit().trigger_name(),
1489         observable_events.clone_trigger_hit().producer_name(),
1490         static_cast<uid_t>(
1491             observable_events.clone_trigger_hit().producer_uid())};
1492     OnCloneSnapshotTriggerReceived(static_cast<TracingSessionID>(tsid),
1493                                    trigger);
1494   }
1495 }
1496 
OnCloneSnapshotTriggerReceived(TracingSessionID tsid,const SnapshotTriggerInfo & trigger)1497 void PerfettoCmd::OnCloneSnapshotTriggerReceived(
1498     TracingSessionID tsid,
1499     const SnapshotTriggerInfo& trigger) {
1500   std::string cmdline;
1501   cmdline.reserve(128);
1502   ArgsAppend(&cmdline, "perfetto");
1503   ArgsAppend(&cmdline, "--config");
1504   ArgsAppend(&cmdline,
1505              ":mem");  // Use the copied config from `snapshot_config_`.
1506   ArgsAppend(&cmdline, "--clone");
1507   ArgsAppend(&cmdline, std::to_string(tsid));
1508   if (upload_flag_) {
1509     ArgsAppend(&cmdline, "--upload");
1510   } else if (!trace_out_path_.empty()) {
1511     ArgsAppend(&cmdline, "--out");
1512     ArgsAppend(&cmdline,
1513                trace_out_path_ + "." + std::to_string(snapshot_count_++));
1514   } else {
1515     PERFETTO_FATAL("Cannot use CLONE_SNAPSHOT with the current cmdline args");
1516   }
1517   CloneSessionOnThread(tsid, cmdline, kSingleExtraThread, trigger, nullptr);
1518 }
1519 
CloneSessionOnThread(TracingSessionID tsid,const std::string & cmdline,CloneThreadMode thread_mode,const std::optional<SnapshotTriggerInfo> & trigger,std::function<void ()> on_clone_callback)1520 void PerfettoCmd::CloneSessionOnThread(
1521     TracingSessionID tsid,
1522     const std::string& cmdline,
1523     CloneThreadMode thread_mode,
1524     const std::optional<SnapshotTriggerInfo>& trigger,
1525     std::function<void()> on_clone_callback) {
1526   PERFETTO_DLOG("Creating snapshot for tracing session %" PRIu64, tsid);
1527 
1528   // Only the main thread instance should be handling snapshots.
1529   // We should never end up in a state where each secondary PerfettoCmd
1530   // instance handles other snapshots and creates other threads.
1531   PERFETTO_CHECK(g_perfetto_cmd == this);
1532 
1533   if (snapshot_threads_.empty() || thread_mode == kNewThreadPerRequest) {
1534     // The destructor of the main-thread's PerfettoCmdMain will destroy and
1535     // join the threads that we are crating here.
1536     snapshot_threads_.emplace_back(
1537         base::ThreadTaskRunner::CreateAndStart("snapshot"));
1538   }
1539 
1540   // We need to pass a copy of the trace config to the new PerfettoCmd instance
1541   // because the trace config defines a bunch of properties that are used by the
1542   // cmdline client (reporter API package, guardrails, etc).
1543   std::string trace_config_copy = trace_config_->SerializeAsString();
1544 
1545   snapshot_threads_.back().PostTask(
1546       [tsid, cmdline, trace_config_copy, trigger, on_clone_callback] {
1547         int argc = 0;
1548         char* argv[32];
1549         // `splitter` needs to live on the stack for the whole scope as it owns
1550         // the underlying string storage that gets std::moved to PerfettoCmd.
1551         base::StringSplitter splitter(std::move(cmdline), '\0');
1552         while (splitter.Next()) {
1553           argv[argc++] = splitter.cur_token();
1554           PERFETTO_CHECK(static_cast<size_t>(argc) < base::ArraySize(argv));
1555         }
1556         perfetto::PerfettoCmd cmd;
1557         cmd.snapshot_config_ = std::move(trace_config_copy);
1558         cmd.snapshot_trigger_info_ = trigger;
1559         cmd.on_session_cloned_ = on_clone_callback;
1560         auto cmdline_res = cmd.ParseCmdlineAndMaybeDaemonize(argc, argv);
1561         PERFETTO_CHECK(!cmdline_res.has_value());  // No daemonization expected.
1562         int res = cmd.ConnectToServiceRunAndMaybeNotify();
1563         if (res)
1564           PERFETTO_ELOG("Cloning session %" PRIu64 " failed (%d)", tsid, res);
1565       });
1566 }
1567 
CloneAllBugreportTraces(bool success,const TracingServiceState & service_state)1568 void PerfettoCmd::CloneAllBugreportTraces(
1569     bool success,
1570     const TracingServiceState& service_state) {
1571   if (!success)
1572     PERFETTO_FATAL("Failed to list active tracing sessions");
1573 
1574   struct SessionToClone {
1575     int32_t bugreport_score;
1576     TracingSessionID tsid;
1577     std::string fname;  // Before deduping logic.
1578     bool operator<(const SessionToClone& other) const {
1579       return bugreport_score > other.bugreport_score;  // High score first.
1580     }
1581   };
1582   std::vector<SessionToClone> sessions;
1583   for (const auto& session : service_state.tracing_sessions()) {
1584     if (session.bugreport_score() <= 0 || !session.is_started())
1585       continue;
1586     std::string fname;
1587     if (!session.bugreport_filename().empty()) {
1588       fname = session.bugreport_filename();
1589     } else {
1590       fname = "systrace.pftrace";
1591     }
1592     sessions.emplace_back(
1593         SessionToClone{session.bugreport_score(), session.id(), fname});
1594   }  // for(session)
1595 
1596   if (sessions.empty()) {
1597     PERFETTO_LOG("No tracing sessions eligible for bugreport were found.");
1598     exit(0);
1599   }
1600 
1601   // First clone all sessions, synchronize, then read them back into files.
1602   // The `sync_fn` below will be executed on each thread inside OnSessionCloned
1603   // before proceeding with the readback. The logic below delays the readback
1604   // of all threads, until the service has acked all the clone requests.
1605   // The tracing service is single-threaded and data readbacks can take several
1606   // seconds. This is to minimize the global clone time and avoid that that
1607   // several sessions stomp on each other.
1608   const size_t num_sessions = sessions.size();
1609 
1610   // sync_point needs to be a shared_ptr to deal with the case where the main
1611   // thread runs in the middle of the Notify() and the Wait() and destroys the
1612   // WaitableEvent before some thread gets to the Wait().
1613   auto sync_point = std::make_shared<base::WaitableEvent>();
1614 
1615   std::function<void()> sync_fn = [sync_point, num_sessions] {
1616     sync_point->Notify();
1617     sync_point->Wait(num_sessions);
1618   };
1619 
1620   // Clone the sessions in order, starting with the highest score first.
1621   std::sort(sessions.begin(), sessions.end());
1622   for (auto it = sessions.begin(); it != sessions.end(); ++it) {
1623     std::string actual_fname = it->fname;
1624     size_t dupes = static_cast<size_t>(std::count_if(
1625         sessions.begin(), it,
1626         [&](const SessionToClone& o) { return o.fname == it->fname; }));
1627     if (dupes > 0) {
1628       std::string suffix = "_" + std::to_string(dupes);
1629       const size_t last_dot = actual_fname.find_last_of('.');
1630       if (last_dot != std::string::npos) {
1631         actual_fname.replace(last_dot, 1, suffix + ".");
1632       } else {
1633         actual_fname.append(suffix);
1634       }
1635     }  // if (dupes > 0)
1636 
1637     // Clone the tracing session into the bugreport file.
1638     std::string out_path = GetBugreportTraceDir() + "/" + actual_fname;
1639     remove(out_path.c_str());
1640     PERFETTO_LOG("Cloning tracing session %" PRIu64 " with score %d into %s",
1641                  it->tsid, it->bugreport_score, out_path.c_str());
1642     std::string cmdline;
1643     cmdline.reserve(128);
1644     ArgsAppend(&cmdline, "perfetto");
1645     ArgsAppend(&cmdline, "--clone");
1646     ArgsAppend(&cmdline, std::to_string(it->tsid));
1647     ArgsAppend(&cmdline, "--clone-for-bugreport");
1648     ArgsAppend(&cmdline, "--out");
1649     ArgsAppend(&cmdline, out_path);
1650     CloneSessionOnThread(it->tsid, cmdline, kNewThreadPerRequest, std::nullopt,
1651                          sync_fn);
1652   }  // for(sessions)
1653 
1654   PERFETTO_DLOG("Issuing %zu CloneSession requests", num_sessions);
1655   sync_point->Wait(num_sessions);
1656   PERFETTO_DLOG("All %zu sessions have acked the clone request", num_sessions);
1657 
1658   // After all sessions are done, quit.
1659   // Note that there is no risk that thd.PostTask() will interleave with the
1660   // sequence of tasks that PerfettoCmd involves, there is no race here.
1661   // There are two TaskRunners here, nested into each other:
1662   // 1) The "outer" ThreadTaskRunner, created by `thd`. This will see only one
1663   //    task ever, which is "run perfetto_cmd until completion".
1664   // 2) Internally PerfettoCmd creates its own UnixTaskRunner, which creates
1665   //    a nested TaskRunner that takes control of the execution. This returns
1666   //    only once TaskRunner::Quit() is called, in its epilogue.
1667   auto done_count = std::make_shared<std::atomic<size_t>>(num_sessions);
1668   for (auto& thd : snapshot_threads_) {
1669     thd.PostTask([done_count] {
1670       if (done_count->fetch_sub(1) == 1) {
1671         PERFETTO_DLOG("All sessions cloned. quitting");
1672         exit(0);
1673       }
1674     });
1675   }
1676 }
1677 
LogUploadEvent(PerfettoStatsdAtom atom)1678 void PerfettoCmd::LogUploadEvent(PerfettoStatsdAtom atom) {
1679   if (!statsd_logging_)
1680     return;
1681   base::Uuid uuid(uuid_);
1682   android_stats::MaybeLogUploadEvent(atom, uuid.lsb(), uuid.msb());
1683 }
1684 
LogUploadEvent(PerfettoStatsdAtom atom,const std::string & trigger_name)1685 void PerfettoCmd::LogUploadEvent(PerfettoStatsdAtom atom,
1686                                  const std::string& trigger_name) {
1687   if (!statsd_logging_)
1688     return;
1689   base::Uuid uuid(uuid_);
1690   android_stats::MaybeLogUploadEvent(atom, uuid.lsb(), uuid.msb(),
1691                                      trigger_name);
1692 }
1693 
LogTriggerEvents(PerfettoTriggerAtom atom,const std::vector<std::string> & trigger_names)1694 void PerfettoCmd::LogTriggerEvents(
1695     PerfettoTriggerAtom atom,
1696     const std::vector<std::string>& trigger_names) {
1697   if (!statsd_logging_)
1698     return;
1699   android_stats::MaybeLogTriggerEvents(atom, trigger_names);
1700 }
1701 
PerfettoCmdMain(int argc,char ** argv)1702 int PERFETTO_EXPORT_ENTRYPOINT PerfettoCmdMain(int argc, char** argv) {
1703   perfetto::PerfettoCmd cmd;
1704   auto opt_res = cmd.ParseCmdlineAndMaybeDaemonize(argc, argv);
1705   if (opt_res.has_value())
1706     return *opt_res;
1707   return cmd.ConnectToServiceRunAndMaybeNotify();
1708 }
1709 
1710 }  // namespace perfetto
1711