blob: 7d001d61262f558cc221bfbfa78e1703f46fdf5e [file] [log] [blame]
Lalit Maganti79f2d7b2018-01-23 18:27:33 +00001/*
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
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000017#include <unistd.h>
Primiano Tucci106605c2019-01-08 21:12:58 +000018
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000019#include <chrono>
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000020#include <functional>
Primiano Tucci106605c2019-01-08 21:12:58 +000021#include <initializer_list>
Lalit Maganti3f5705c2018-03-09 12:09:44 +000022#include <random>
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000023#include <thread>
24
Primiano Tuccife922332018-03-22 16:15:04 -070025#include "perfetto/base/build_config.h"
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000026#include "perfetto/base/logging.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010027#include "perfetto/ext/base/file_utils.h"
28#include "perfetto/ext/base/pipe.h"
Primiano Tuccie094eec2020-03-18 16:58:21 +000029#include "perfetto/ext/base/scoped_file.h"
Primiano Tucci9c41ceb2020-04-14 13:23:01 +010030#include "perfetto/ext/base/string_utils.h"
Primiano Tuccie094eec2020-03-18 16:58:21 +000031#include "perfetto/ext/base/subprocess.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010032#include "perfetto/ext/base/temp_file.h"
Primiano Tucci9c41ceb2020-04-14 13:23:01 +010033#include "perfetto/ext/ipc/basic_types.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010034#include "perfetto/ext/traced/traced.h"
Primiano Tucci9c41ceb2020-04-14 13:23:01 +010035#include "perfetto/ext/tracing/core/commit_data_request.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010036#include "perfetto/ext/tracing/core/trace_packet.h"
Stephen Nuskoac0c1972019-06-25 13:57:13 +010037#include "perfetto/ext/tracing/ipc/default_socket.h"
Primiano Tucci0f2f3b42019-05-21 19:37:01 +010038#include "perfetto/protozero/scattered_heap_buffer.h"
Primiano Tucci9c41ceb2020-04-14 13:23:01 +010039#include "perfetto/tracing/core/tracing_service_state.h"
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000040#include "src/base/test/test_task_runner.h"
Primiano Tuccie094eec2020-03-18 16:58:21 +000041#include "src/base/test/utils.h"
Primiano Tuccic1855302018-12-06 10:36:55 +000042#include "src/traced/probes/ftrace/ftrace_controller.h"
43#include "src/traced/probes/ftrace/ftrace_procfs.h"
Primiano Tucci919ca1e2019-08-21 20:26:58 +020044#include "test/gtest_and_gmock.h"
Lalit Magantic4c3ceb2018-03-29 20:38:13 +010045#include "test/test_helper.h"
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000046
Primiano Tuccife502c42019-12-11 01:00:27 +000047#include "protos/perfetto/config/power/android_power_config.pbzero.h"
48#include "protos/perfetto/config/test_config.gen.h"
49#include "protos/perfetto/config/trace_config.gen.h"
50#include "protos/perfetto/trace/ftrace/ftrace.gen.h"
51#include "protos/perfetto/trace/ftrace/ftrace_event.gen.h"
52#include "protos/perfetto/trace/ftrace/ftrace_event_bundle.gen.h"
53#include "protos/perfetto/trace/power/battery_counters.gen.h"
54#include "protos/perfetto/trace/test_event.gen.h"
55#include "protos/perfetto/trace/trace.gen.h"
56#include "protos/perfetto/trace/trace_packet.gen.h"
57#include "protos/perfetto/trace/trace_packet.pbzero.h"
58#include "protos/perfetto/trace/trigger.gen.h"
59
Lalit Maganti79f2d7b2018-01-23 18:27:33 +000060namespace perfetto {
61
Primiano Tuccic1855302018-12-06 10:36:55 +000062namespace {
63
Primiano Tucci106605c2019-01-08 21:12:58 +000064using ::testing::ContainsRegex;
Primiano Tucci9c41ceb2020-04-14 13:23:01 +010065using ::testing::ElementsAreArray;
Primiano Tucci106605c2019-01-08 21:12:58 +000066using ::testing::HasSubstr;
67
Primiano Tucci79e4dcb2020-04-08 09:51:02 +010068constexpr size_t kBuiltinPackets = 8;
69
Stephen Nusko49c5a3c2019-04-17 13:36:09 +010070std::string RandomTraceFileName() {
71#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
72 constexpr char kSysTmpPath[] = "/data/misc/perfetto-traces";
73#else
74 constexpr char kSysTmpPath[] = "/tmp";
75#endif
76 static int suffix = 0;
77
78 std::string path;
79 path.assign(kSysTmpPath);
80 path.append("/trace-");
81 path.append(std::to_string(base::GetBootTimeNs().count()));
82 path.append("-");
83 path.append(std::to_string(suffix++));
84 return path;
85}
86
Stephen Nusko87a12a82019-07-24 17:56:46 +010087// This class is a reference to a child process that has in essence been execv
88// to the requested binary. The process will start and then wait for Run()
89// before proceeding. We use this to fork new processes before starting any
Hector Dearman5145e502019-09-18 16:52:24 +010090// additional threads in the parent process (otherwise you would risk
Stephen Nusko87a12a82019-07-24 17:56:46 +010091// deadlocks), but pause the forked processes until remaining setup (including
92// any necessary threads) in the parent process is complete.
93class Exec {
94 public:
Primiano Tuccie094eec2020-03-18 16:58:21 +000095 // Starts the forked process that was created. If not null then |stderr_out|
96 // will contain the stderr of the process.
Stephen Nusko87a12a82019-07-24 17:56:46 +010097 int Run(std::string* stderr_out = nullptr) {
98 // We can't be the child process.
Primiano Tuccie094eec2020-03-18 16:58:21 +000099 PERFETTO_CHECK(getpid() != subprocess_.pid());
100 // Will cause the entrypoint to continue.
101 PERFETTO_CHECK(write(*sync_pipe_.wr, "1", 1) == 1);
102 sync_pipe_.wr.reset();
103 subprocess_.Wait();
Stephen Nusko87a12a82019-07-24 17:56:46 +0100104
Stephen Nusko87a12a82019-07-24 17:56:46 +0100105 if (stderr_out) {
Primiano Tuccie094eec2020-03-18 16:58:21 +0000106 *stderr_out = std::move(subprocess_.output());
Stephen Nusko87a12a82019-07-24 17:56:46 +0100107 } else {
Primiano Tuccie094eec2020-03-18 16:58:21 +0000108 PERFETTO_LOG("Child proc %d exited with stderr: \"%s\"",
109 subprocess_.pid(), subprocess_.output().c_str());
Stephen Nusko87a12a82019-07-24 17:56:46 +0100110 }
Primiano Tuccie094eec2020-03-18 16:58:21 +0000111 return subprocess_.returncode();
Stephen Nusko87a12a82019-07-24 17:56:46 +0100112 }
113
114 private:
Primiano Tuccie094eec2020-03-18 16:58:21 +0000115 Exec(const std::string& argv0,
116 std::initializer_list<std::string> args,
117 std::string input = "") {
118 subprocess_.args.stderr_mode = base::Subprocess::kBuffer;
119 subprocess_.args.stdout_mode = base::Subprocess::kDevNull;
120 subprocess_.args.input = input;
Stephen Nusko87a12a82019-07-24 17:56:46 +0100121
Stephen Nusko87a12a82019-07-24 17:56:46 +0100122#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
Primiano Tuccie094eec2020-03-18 16:58:21 +0000123 constexpr bool kUseSystemBinaries = false;
Stephen Nusko87a12a82019-07-24 17:56:46 +0100124#else
Primiano Tuccie094eec2020-03-18 16:58:21 +0000125 constexpr bool kUseSystemBinaries = true;
Stephen Nusko87a12a82019-07-24 17:56:46 +0100126#endif
Primiano Tuccie094eec2020-03-18 16:58:21 +0000127
128 std::vector<std::string>& cmd = subprocess_.args.exec_cmd;
129 if (kUseSystemBinaries) {
130 cmd.push_back("/system/bin/" + argv0);
131 cmd.insert(cmd.end(), args.begin(), args.end());
132 } else {
133 subprocess_.args.env.push_back(
134 std::string("PERFETTO_PRODUCER_SOCK_NAME=") +
135 TestHelper::GetProducerSocketName());
136 subprocess_.args.env.push_back(
137 std::string("PERFETTO_CONSUMER_SOCK_NAME=") +
138 TestHelper::GetConsumerSocketName());
139 cmd.push_back(base::GetCurExecutableDir() + "/" + argv0);
140 cmd.insert(cmd.end(), args.begin(), args.end());
141 }
142
143 if (access(cmd[0].c_str(), F_OK)) {
144 PERFETTO_FATAL(
145 "Cannot find %s. Make sure that the target has been built and, on "
146 "Android, pushed to the device.",
147 cmd[0].c_str());
148 }
149
150 // This pipe blocks the execution of the child process until the main test
151 // process calls Run(). There are two conflicting problems here:
152 // 1) We can't fork() subprocesses too late, because the test spawns threads
153 // for hosting the service. fork+threads = bad (see aosp/1089744).
154 // 2) We can't run the subprocess too early, because we need to wait that
155 // the service threads are ready before trying to connect from the child
156 // process.
157 sync_pipe_ = base::Pipe::Create();
158 int sync_pipe_rd = *sync_pipe_.rd;
159 subprocess_.args.preserve_fds.push_back(sync_pipe_rd);
160
161 // This lambda will be called on the forked child process after having
162 // setup pipe redirection and closed all FDs, right before the exec().
163 // The Subprocesss harness will take care of closing also |sync_pipe_.wr|.
164 subprocess_.args.entrypoint_for_testing = [sync_pipe_rd] {
165 // Don't add any logging here, all file descriptors are closed and trying
166 // to log will likely cause undefined behaviors.
167 char ignored = 0;
168 PERFETTO_CHECK(PERFETTO_EINTR(read(sync_pipe_rd, &ignored, 1)) > 0);
Ryan704bc822020-03-31 02:31:13 +0100169 PERFETTO_CHECK(close(sync_pipe_rd) == 0 || errno == EINTR);
Primiano Tuccie094eec2020-03-18 16:58:21 +0000170 };
171
172 subprocess_.Start();
173 sync_pipe_.rd.reset();
Stephen Nusko87a12a82019-07-24 17:56:46 +0100174 }
175
176 friend class PerfettoCmdlineTest;
Primiano Tuccie094eec2020-03-18 16:58:21 +0000177 base::Subprocess subprocess_;
178 base::Pipe sync_pipe_;
Stephen Nusko87a12a82019-07-24 17:56:46 +0100179};
180
Primiano Tuccic1855302018-12-06 10:36:55 +0000181class PerfettoTest : public ::testing::Test {
182 public:
183 void SetUp() override {
184 // TODO(primiano): refactor this, it's copy/pasted in three places now.
185 size_t index = 0;
186 constexpr auto kTracingPaths = FtraceController::kTracingPaths;
187 while (!ftrace_procfs_ && kTracingPaths[index]) {
188 ftrace_procfs_ = FtraceProcfs::Create(kTracingPaths[index++]);
189 }
Primiano Tuccic1855302018-12-06 10:36:55 +0000190 }
191
192 std::unique_ptr<FtraceProcfs> ftrace_procfs_;
193};
194
Primiano Tucci106605c2019-01-08 21:12:58 +0000195class PerfettoCmdlineTest : public ::testing::Test {
196 public:
Stephen Nusko87a12a82019-07-24 17:56:46 +0100197 void SetUp() override { exec_allowed_ = true; }
Primiano Tucci106605c2019-01-08 21:12:58 +0000198
199 void TearDown() override {}
200
Stephen Nusko87a12a82019-07-24 17:56:46 +0100201 void StartServiceIfRequiredNoNewExecsAfterThis() {
202 exec_allowed_ = false;
203 test_helper_.StartServiceIfRequired();
Hector Dearman696ff772019-04-23 18:38:53 +0100204 }
205
Stephen Nusko87a12a82019-07-24 17:56:46 +0100206 FakeProducer* ConnectFakeProducer() {
207 return test_helper_.ConnectFakeProducer();
Hector Dearman696ff772019-04-23 18:38:53 +0100208 }
209
Stephen Nusko87a12a82019-07-24 17:56:46 +0100210 std::function<void()> WrapTask(const std::function<void()>& function) {
211 return test_helper_.WrapTask(function);
Primiano Tucci106605c2019-01-08 21:12:58 +0000212 }
213
Stephen Nusko87a12a82019-07-24 17:56:46 +0100214 void WaitForProducerSetup() { test_helper_.WaitForProducerSetup(); }
215
216 void WaitForProducerEnabled() { test_helper_.WaitForProducerEnabled(); }
217
218 // Creates a process that represents the perfetto binary that will
219 // start when Run() is called. |args| will be passed as part of
220 // the command line and |std_in| will be piped into std::cin.
221 Exec ExecPerfetto(std::initializer_list<std::string> args,
222 std::string std_in = "") {
223 // You can not fork after you've started the service due to risk of
224 // deadlocks.
225 PERFETTO_CHECK(exec_allowed_);
Primiano Tuccie094eec2020-03-18 16:58:21 +0000226 return Exec("perfetto", std::move(args), std::move(std_in));
Stephen Nusko87a12a82019-07-24 17:56:46 +0100227 }
228
229 // Creates a process that represents the trigger_perfetto binary that will
230 // start when Run() is called. |args| will be passed as part of
231 // the command line and |std_in| will be piped into std::cin.
232 Exec ExecTrigger(std::initializer_list<std::string> args,
233 std::string std_in = "") {
234 // You can not fork after you've started the service due to risk of
235 // deadlocks.
236 PERFETTO_CHECK(exec_allowed_);
Primiano Tuccie094eec2020-03-18 16:58:21 +0000237 return Exec("trigger_perfetto", std::move(args), std::move(std_in));
Stephen Nusko87a12a82019-07-24 17:56:46 +0100238 }
239
240 // Tests are allowed to freely use these variables.
Primiano Tucci106605c2019-01-08 21:12:58 +0000241 std::string stderr_;
242 base::TestTaskRunner task_runner_;
Stephen Nusko87a12a82019-07-24 17:56:46 +0100243
244 private:
245 bool exec_allowed_;
Primiano Tucci106605c2019-01-08 21:12:58 +0000246 TestHelper test_helper_{&task_runner_};
247};
248
Primiano Tuccic1855302018-12-06 10:36:55 +0000249} // namespace
250
Lalit Magantid0e76792018-02-12 14:25:01 +0000251// If we're building on Android and starting the daemons ourselves,
252// create the sockets in a world-writable location.
Oystein Eftevaagff729592018-02-12 14:24:06 -0800253#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && \
254 PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000255#define TEST_PRODUCER_SOCK_NAME "/data/local/tmp/traced_producer"
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000256#else
Florian Mayerc29e0d32018-04-04 15:55:46 +0100257#define TEST_PRODUCER_SOCK_NAME ::perfetto::GetProducerSocket()
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000258#endif
259
Primiano Tuccife922332018-03-22 16:15:04 -0700260#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
Primiano Tuccic1855302018-12-06 10:36:55 +0000261#define TreeHuggerOnly(x) x
Lalit Maganti7d3e30a2018-02-16 10:20:36 +0000262#else
Primiano Tuccic1855302018-12-06 10:36:55 +0000263#define TreeHuggerOnly(x) DISABLED_##x
Lalit Maganti7d3e30a2018-02-16 10:20:36 +0000264#endif
Primiano Tuccic1855302018-12-06 10:36:55 +0000265
Eric Seckler326a3d32020-02-04 11:24:56 +0000266// TODO(b/73453011): reenable on more platforms (including standalone Android).
Primiano Tuccic1855302018-12-06 10:36:55 +0000267TEST_F(PerfettoTest, TreeHuggerOnly(TestFtraceProducer)) {
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000268 base::TestTaskRunner task_runner;
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000269
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100270 TestHelper helper(&task_runner);
271 helper.StartServiceIfRequired();
Lalit Magantidd95ef92018-03-23 09:42:48 +0000272
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100273#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
Lalit Maganti9782f492020-01-10 18:13:13 +0000274 ProbesProducerThread probes(TEST_PRODUCER_SOCK_NAME);
275 probes.Connect();
Lalit Magantidd95ef92018-03-23 09:42:48 +0000276#endif
277
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100278 helper.ConnectConsumer();
Lalit Maganti36557d82018-04-11 14:36:17 +0100279 helper.WaitForConsumerConnect();
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100280
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000281 TraceConfig trace_config;
Lalit Magantibfc3d3e2018-03-22 20:28:38 +0000282 trace_config.add_buffers()->set_size_kb(1024);
283 trace_config.set_duration_ms(3000);
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000284
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000285 auto* ds_config = trace_config.add_data_sources()->mutable_config();
Primiano Tucci578d7842018-03-29 15:27:05 +0100286 ds_config->set_name("linux.ftrace");
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000287 ds_config->set_target_buffer(0);
288
Primiano Tuccife502c42019-12-11 01:00:27 +0000289 protos::gen::FtraceConfig ftrace_config;
Primiano Tucci0f2f3b42019-05-21 19:37:01 +0100290 ftrace_config.add_ftrace_events("sched_switch");
291 ftrace_config.add_ftrace_events("bar");
292 ds_config->set_ftrace_config_raw(ftrace_config.SerializeAsString());
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000293
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100294 helper.StartTracing(trace_config);
Lalit Maganti36557d82018-04-11 14:36:17 +0100295 helper.WaitForTracingDisabled();
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100296
Lalit Maganti36557d82018-04-11 14:36:17 +0100297 helper.ReadData();
298 helper.WaitForReadData();
299
300 const auto& packets = helper.trace();
301 ASSERT_GT(packets.size(), 0u);
302
303 for (const auto& packet : packets) {
Primiano Tucci07e104d2018-04-03 20:45:35 +0200304 for (int ev = 0; ev < packet.ftrace_events().event_size(); ev++) {
Primiano Tuccife502c42019-12-11 01:00:27 +0000305 ASSERT_TRUE(packet.ftrace_events()
306 .event()[static_cast<size_t>(ev)]
307 .has_sched_switch());
Primiano Tucci07e104d2018-04-03 20:45:35 +0200308 }
Lalit Maganti36557d82018-04-11 14:36:17 +0100309 }
Lalit Magantidd95ef92018-03-23 09:42:48 +0000310}
311
Eric Seckler326a3d32020-02-04 11:24:56 +0000312// TODO(b/73453011): reenable on more platforms (including standalone Android).
Primiano Tuccic1855302018-12-06 10:36:55 +0000313TEST_F(PerfettoTest, TreeHuggerOnly(TestFtraceFlush)) {
314 base::TestTaskRunner task_runner;
315
316 TestHelper helper(&task_runner);
317 helper.StartServiceIfRequired();
318
319#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
Lalit Maganti9782f492020-01-10 18:13:13 +0000320 ProbesProducerThread probes(TEST_PRODUCER_SOCK_NAME);
321 probes.Connect();
Primiano Tucci0ea9a372018-12-03 20:21:42 +0100322#endif
Primiano Tuccic1855302018-12-06 10:36:55 +0000323
324 helper.ConnectConsumer();
325 helper.WaitForConsumerConnect();
326
327 const uint32_t kTestTimeoutMs = 30000;
328 TraceConfig trace_config;
Ryan Savitskie3235e82020-02-03 18:11:51 +0000329 trace_config.add_buffers()->set_size_kb(32);
Primiano Tuccic1855302018-12-06 10:36:55 +0000330 trace_config.set_duration_ms(kTestTimeoutMs);
331
332 auto* ds_config = trace_config.add_data_sources()->mutable_config();
333 ds_config->set_name("linux.ftrace");
334
Primiano Tuccife502c42019-12-11 01:00:27 +0000335 protos::gen::FtraceConfig ftrace_config;
Primiano Tucci0f2f3b42019-05-21 19:37:01 +0100336 ftrace_config.add_ftrace_events("print");
337 ds_config->set_ftrace_config_raw(ftrace_config.SerializeAsString());
Primiano Tuccic1855302018-12-06 10:36:55 +0000338
339 helper.StartTracing(trace_config);
340
341 // Do a first flush just to synchronize with the producer. The problem here
342 // is that, on a Linux workstation, the producer can take several seconds just
343 // to get to the point where ftrace is ready. We use the flush ack as a
344 // synchronization point.
345 helper.FlushAndWait(kTestTimeoutMs);
346
347 EXPECT_TRUE(ftrace_procfs_->IsTracingEnabled());
348 const char kMarker[] = "just_one_event";
349 EXPECT_TRUE(ftrace_procfs_->WriteTraceMarker(kMarker));
350
351 // This is the real flush we are testing.
352 helper.FlushAndWait(kTestTimeoutMs);
353
354 helper.DisableTracing();
355 helper.WaitForTracingDisabled(kTestTimeoutMs);
356
357 helper.ReadData();
358 helper.WaitForReadData();
359
360 int marker_found = 0;
361 for (const auto& packet : helper.trace()) {
362 for (int i = 0; i < packet.ftrace_events().event_size(); i++) {
Primiano Tuccife502c42019-12-11 01:00:27 +0000363 const auto& ev = packet.ftrace_events().event()[static_cast<size_t>(i)];
Primiano Tuccic1855302018-12-06 10:36:55 +0000364 if (ev.has_print() && ev.print().buf().find(kMarker) != std::string::npos)
365 marker_found++;
366 }
367 }
368 ASSERT_EQ(marker_found, 1);
369}
370
Eric Seckler326a3d32020-02-04 11:24:56 +0000371// TODO(b/73453011): reenable on more platforms (including standalone Android).
Primiano Tuccic1855302018-12-06 10:36:55 +0000372TEST_F(PerfettoTest, TreeHuggerOnly(TestBatteryTracing)) {
Primiano Tucci0ea9a372018-12-03 20:21:42 +0100373 base::TestTaskRunner task_runner;
374
375 TestHelper helper(&task_runner);
376 helper.StartServiceIfRequired();
377
378#if PERFETTO_BUILDFLAG(PERFETTO_START_DAEMONS)
Lalit Maganti9782f492020-01-10 18:13:13 +0000379 ProbesProducerThread probes(TEST_PRODUCER_SOCK_NAME);
380 probes.Connect();
Florian Mayer42802492018-12-13 11:00:16 +0000381#else
382 base::ignore_result(TEST_PRODUCER_SOCK_NAME);
Primiano Tucci0ea9a372018-12-03 20:21:42 +0100383#endif
384
385 helper.ConnectConsumer();
386 helper.WaitForConsumerConnect();
387
388 TraceConfig trace_config;
389 trace_config.add_buffers()->set_size_kb(128);
390 trace_config.set_duration_ms(3000);
391
392 auto* ds_config = trace_config.add_data_sources()->mutable_config();
393 ds_config->set_name("android.power");
394 ds_config->set_target_buffer(0);
Primiano Tucci0f2f3b42019-05-21 19:37:01 +0100395
396 using protos::pbzero::AndroidPowerConfig;
397 protozero::HeapBuffered<AndroidPowerConfig> power_config;
Primiano Tucci0ea9a372018-12-03 20:21:42 +0100398 power_config->set_battery_poll_ms(250);
Primiano Tucci0f2f3b42019-05-21 19:37:01 +0100399 power_config->add_battery_counters(
400 AndroidPowerConfig::BATTERY_COUNTER_CHARGE);
401 power_config->add_battery_counters(
402 AndroidPowerConfig::BATTERY_COUNTER_CAPACITY_PERCENT);
403 ds_config->set_android_power_config_raw(power_config.SerializeAsString());
Primiano Tucci0ea9a372018-12-03 20:21:42 +0100404
405 helper.StartTracing(trace_config);
406 helper.WaitForTracingDisabled();
407
408 helper.ReadData();
409 helper.WaitForReadData();
410
411 const auto& packets = helper.trace();
412 ASSERT_GT(packets.size(), 0u);
413
414 bool has_battery_packet = false;
415 for (const auto& packet : packets) {
416 if (!packet.has_battery())
417 continue;
418 has_battery_packet = true;
Primiano Tucci61804c02018-12-14 11:34:44 +0000419 // Unfortunately we cannot make any assertions on the charge counter.
420 // On some devices it can reach negative values (b/64685329).
Primiano Tucci0ea9a372018-12-03 20:21:42 +0100421 EXPECT_GE(packet.battery().capacity_percent(), 0);
422 EXPECT_LE(packet.battery().capacity_percent(), 100);
423 }
424
425 ASSERT_TRUE(has_battery_packet);
426}
427
Primiano Tuccic1855302018-12-06 10:36:55 +0000428TEST_F(PerfettoTest, TestFakeProducer) {
Lalit Magantidd95ef92018-03-23 09:42:48 +0000429 base::TestTaskRunner task_runner;
430
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100431 TestHelper helper(&task_runner);
432 helper.StartServiceIfRequired();
Lalit Maganti36557d82018-04-11 14:36:17 +0100433 helper.ConnectFakeProducer();
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100434 helper.ConnectConsumer();
Lalit Maganti36557d82018-04-11 14:36:17 +0100435 helper.WaitForConsumerConnect();
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000436
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000437 TraceConfig trace_config;
Lalit Magantibfc3d3e2018-03-22 20:28:38 +0000438 trace_config.add_buffers()->set_size_kb(1024);
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000439 trace_config.set_duration_ms(200);
440
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000441 auto* ds_config = trace_config.add_data_sources()->mutable_config();
442 ds_config->set_name("android.perfetto.FakeProducer");
443 ds_config->set_target_buffer(0);
444
Hector Dearman685f7522019-03-12 14:28:56 +0000445 static constexpr size_t kNumPackets = 11;
Lalit Maganti3f5705c2018-03-09 12:09:44 +0000446 static constexpr uint32_t kRandomSeed = 42;
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100447 static constexpr uint32_t kMsgSize = 1024;
Lalit Maganti3f5705c2018-03-09 12:09:44 +0000448 ds_config->mutable_for_testing()->set_seed(kRandomSeed);
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100449 ds_config->mutable_for_testing()->set_message_count(kNumPackets);
450 ds_config->mutable_for_testing()->set_message_size(kMsgSize);
Lalit Maganti36557d82018-04-11 14:36:17 +0100451 ds_config->mutable_for_testing()->set_send_batch_on_register(true);
Lalit Maganti3f5705c2018-03-09 12:09:44 +0000452
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100453 helper.StartTracing(trace_config);
Lalit Maganti36557d82018-04-11 14:36:17 +0100454 helper.WaitForTracingDisabled();
Lalit Maganti3f5705c2018-03-09 12:09:44 +0000455
Lalit Maganti36557d82018-04-11 14:36:17 +0100456 helper.ReadData();
457 helper.WaitForReadData();
Lalit Magantibfc3d3e2018-03-22 20:28:38 +0000458
Lalit Maganti36557d82018-04-11 14:36:17 +0100459 const auto& packets = helper.trace();
460 ASSERT_EQ(packets.size(), kNumPackets);
461
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100462 std::minstd_rand0 rnd_engine(kRandomSeed);
Lalit Maganti36557d82018-04-11 14:36:17 +0100463 for (const auto& packet : packets) {
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100464 ASSERT_TRUE(packet.has_for_testing());
465 ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
Lalit Maganti36557d82018-04-11 14:36:17 +0100466 }
Lalit Maganti79f2d7b2018-01-23 18:27:33 +0000467}
468
Primiano Tuccic1855302018-12-06 10:36:55 +0000469TEST_F(PerfettoTest, VeryLargePackets) {
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100470 base::TestTaskRunner task_runner;
471
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100472 TestHelper helper(&task_runner);
473 helper.StartServiceIfRequired();
Lalit Maganti36557d82018-04-11 14:36:17 +0100474 helper.ConnectFakeProducer();
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100475 helper.ConnectConsumer();
Lalit Maganti36557d82018-04-11 14:36:17 +0100476 helper.WaitForConsumerConnect();
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100477
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100478 TraceConfig trace_config;
479 trace_config.add_buffers()->set_size_kb(4096 * 10);
Lalit Maganti36557d82018-04-11 14:36:17 +0100480 trace_config.set_duration_ms(500);
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100481
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100482 auto* ds_config = trace_config.add_data_sources()->mutable_config();
483 ds_config->set_name("android.perfetto.FakeProducer");
484 ds_config->set_target_buffer(0);
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100485
Hector Dearman685f7522019-03-12 14:28:56 +0000486 static constexpr size_t kNumPackets = 7;
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100487 static constexpr uint32_t kRandomSeed = 42;
488 static constexpr uint32_t kMsgSize = 1024 * 1024 - 42;
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100489 ds_config->mutable_for_testing()->set_seed(kRandomSeed);
490 ds_config->mutable_for_testing()->set_message_count(kNumPackets);
491 ds_config->mutable_for_testing()->set_message_size(kMsgSize);
Lalit Maganti36557d82018-04-11 14:36:17 +0100492 ds_config->mutable_for_testing()->set_send_batch_on_register(true);
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100493
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100494 helper.StartTracing(trace_config);
Lalit Maganti36557d82018-04-11 14:36:17 +0100495 helper.WaitForTracingDisabled();
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100496
Lalit Maganti36557d82018-04-11 14:36:17 +0100497 helper.ReadData();
Sami Kyostilab35c6742020-02-12 16:06:45 +0000498 helper.WaitForReadData(/* read_count */ 0, /* timeout_ms */ 10000);
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100499
Lalit Maganti36557d82018-04-11 14:36:17 +0100500 const auto& packets = helper.trace();
501 ASSERT_EQ(packets.size(), kNumPackets);
502
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100503 std::minstd_rand0 rnd_engine(kRandomSeed);
Lalit Maganti36557d82018-04-11 14:36:17 +0100504 for (const auto& packet : packets) {
Lalit Magantic4c3ceb2018-03-29 20:38:13 +0100505 ASSERT_TRUE(packet.has_for_testing());
506 ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
507 size_t msg_size = packet.for_testing().str().size();
508 ASSERT_EQ(kMsgSize, msg_size);
509 for (size_t i = 0; i < msg_size; i++)
510 ASSERT_EQ(i < msg_size - 1 ? '.' : 0, packet.for_testing().str()[i]);
Lalit Maganti36557d82018-04-11 14:36:17 +0100511 }
Primiano Tucci5ae66da2018-03-28 15:57:34 +0100512}
513
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100514TEST_F(PerfettoTest, DetachAndReattach) {
515 base::TestTaskRunner task_runner;
516
517 TraceConfig trace_config;
518 trace_config.add_buffers()->set_size_kb(1024);
Primiano Tucci5a175452018-12-22 11:48:48 +0100519 trace_config.set_duration_ms(10000); // Max timeout, session is ended before.
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100520 auto* ds_config = trace_config.add_data_sources()->mutable_config();
521 ds_config->set_name("android.perfetto.FakeProducer");
Hector Dearman685f7522019-03-12 14:28:56 +0000522 static constexpr size_t kNumPackets = 11;
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100523 ds_config->mutable_for_testing()->set_message_count(kNumPackets);
524 ds_config->mutable_for_testing()->set_message_size(32);
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100525
526 // Enable tracing and detach as soon as it gets started.
527 TestHelper helper(&task_runner);
528 helper.StartServiceIfRequired();
Primiano Tucci5a175452018-12-22 11:48:48 +0100529 auto* fake_producer = helper.ConnectFakeProducer();
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100530 helper.ConnectConsumer();
531 helper.WaitForConsumerConnect();
532 helper.StartTracing(trace_config);
533
534 // Detach.
535 helper.DetachConsumer("key");
536
Primiano Tucci5a175452018-12-22 11:48:48 +0100537 // Write data while detached.
538 helper.WaitForProducerEnabled();
539 auto on_data_written = task_runner.CreateCheckpoint("data_written");
540 fake_producer->ProduceEventBatch(helper.WrapTask(on_data_written));
541 task_runner.RunUntilCheckpoint("data_written");
542
543 // Then reattach the consumer.
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100544 helper.ConnectConsumer();
545 helper.WaitForConsumerConnect();
546 helper.AttachConsumer("key");
Primiano Tucci5a175452018-12-22 11:48:48 +0100547
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100548 helper.DisableTracing();
549 helper.WaitForTracingDisabled();
550
551 helper.ReadData();
552 helper.WaitForReadData();
553 const auto& packets = helper.trace();
554 ASSERT_EQ(packets.size(), kNumPackets);
555}
556
557// Tests that a detached trace session is automatically cleaned up if the
558// consumer doesn't re-attach before its expiration time.
559TEST_F(PerfettoTest, ReattachFailsAfterTimeout) {
560 base::TestTaskRunner task_runner;
561
562 TraceConfig trace_config;
563 trace_config.add_buffers()->set_size_kb(1024);
564 trace_config.set_duration_ms(250);
565 trace_config.set_write_into_file(true);
566 trace_config.set_file_write_period_ms(100000);
567 auto* ds_config = trace_config.add_data_sources()->mutable_config();
568 ds_config->set_name("android.perfetto.FakeProducer");
569 ds_config->mutable_for_testing()->set_message_count(1);
570 ds_config->mutable_for_testing()->set_message_size(32);
571 ds_config->mutable_for_testing()->set_send_batch_on_register(true);
572
573 // Enable tracing and detach as soon as it gets started.
574 TestHelper helper(&task_runner);
575 helper.StartServiceIfRequired();
576 helper.ConnectFakeProducer();
577 helper.ConnectConsumer();
578 helper.WaitForConsumerConnect();
579
580 auto pipe_pair = base::Pipe::Create();
581 helper.StartTracing(trace_config, std::move(pipe_pair.wr));
582
583 // Detach.
584 helper.DetachConsumer("key");
585
586 // Use the file EOF (write end closed) as a way to detect when the trace
587 // session is ended.
588 char buf[1024];
589 while (PERFETTO_EINTR(read(*pipe_pair.rd, buf, sizeof(buf))) > 0) {
590 }
591
592 // Give some margin for the tracing service to destroy the session.
593 usleep(250000);
594
595 // Reconnect and find out that it's too late and the session is gone.
596 helper.ConnectConsumer();
597 helper.WaitForConsumerConnect();
598 EXPECT_FALSE(helper.AttachConsumer("key"));
599}
600
Eric Seckler526921b2020-02-18 11:44:30 +0000601TEST_F(PerfettoTest, TestProducerProvidedSMB) {
Eric Seckler326a3d32020-02-04 11:24:56 +0000602 base::TestTaskRunner task_runner;
603
604 TestHelper helper(&task_runner);
605 helper.CreateProducerProvidedSmb();
606
Eric Seckler526921b2020-02-18 11:44:30 +0000607 protos::gen::TestConfig test_config;
608 test_config.set_seed(42);
609 test_config.set_message_count(1);
610 test_config.set_message_size(1024);
611 test_config.set_send_batch_on_register(true);
612
613 // Write a first batch before connection.
614 helper.ProduceStartupEventBatch(test_config);
615
Eric Seckler326a3d32020-02-04 11:24:56 +0000616 helper.StartServiceIfRequired();
617 helper.ConnectFakeProducer();
618 helper.ConnectConsumer();
619 helper.WaitForConsumerConnect();
620
621 TraceConfig trace_config;
622 trace_config.add_buffers()->set_size_kb(1024);
623 trace_config.set_duration_ms(200);
624
625 auto* ds_config = trace_config.add_data_sources()->mutable_config();
626 ds_config->set_name("android.perfetto.FakeProducer");
627 ds_config->set_target_buffer(0);
Eric Seckler526921b2020-02-18 11:44:30 +0000628 *ds_config->mutable_for_testing() = test_config;
Eric Seckler326a3d32020-02-04 11:24:56 +0000629
Eric Seckler526921b2020-02-18 11:44:30 +0000630 // The data source is configured to emit another batch when it is started via
631 // send_batch_on_register in the TestConfig.
Eric Seckler326a3d32020-02-04 11:24:56 +0000632 helper.StartTracing(trace_config);
633 helper.WaitForTracingDisabled();
634
635 EXPECT_TRUE(helper.IsShmemProvidedByProducer());
636
637 helper.ReadData();
638 helper.WaitForReadData();
639
640 const auto& packets = helper.trace();
Eric Seckler526921b2020-02-18 11:44:30 +0000641 // We should have produced two batches, one before the producer connected and
642 // another one when the data source was started.
643 ASSERT_EQ(packets.size(), 2u);
Eric Seckler326a3d32020-02-04 11:24:56 +0000644 ASSERT_TRUE(packets[0].has_for_testing());
Eric Seckler526921b2020-02-18 11:44:30 +0000645 ASSERT_TRUE(packets[1].has_for_testing());
Eric Seckler326a3d32020-02-04 11:24:56 +0000646}
647
Primiano Tucci9c41ceb2020-04-14 13:23:01 +0100648// Regression test for b/153142114.
649TEST_F(PerfettoTest, QueryServiceStateLargeResponse) {
650 base::TestTaskRunner task_runner;
651
652 TestHelper helper(&task_runner);
653 helper.StartServiceIfRequired();
Primiano Tucci9c41ceb2020-04-14 13:23:01 +0100654 helper.ConnectConsumer();
655 helper.WaitForConsumerConnect();
656
Primiano Tuccibbe68be2020-04-16 22:17:12 +0100657 FakeProducer* producer = helper.ConnectFakeProducer();
Primiano Tucci9c41ceb2020-04-14 13:23:01 +0100658
659 // Register 5 data sources with very large descriptors. Each descriptor will
660 // max out the IPC message size, so that the service has no other choice
661 // than chunking them.
662 std::map<std::string, std::string> ds_expected;
663 for (int i = 0; i < 5; i++) {
664 DataSourceDescriptor dsd;
665 std::string name = "big_ds_" + std::to_string(i);
666 dsd.set_name(name);
667 std::string descriptor(ipc::kIPCBufferSize - 64, (' ' + i) % 64);
668 dsd.set_track_event_descriptor_raw(descriptor);
669 ds_expected[name] = std::move(descriptor);
670 producer->RegisterDataSource(dsd);
671 }
672
Primiano Tuccibbe68be2020-04-16 22:17:12 +0100673 // Linearize the producer with the service. We need to make sure that all the
674 // RegisterDataSource() calls above have been seen by the service before
675 // continuing.
676 helper.SyncAndWaitProducer();
Primiano Tucci9c41ceb2020-04-14 13:23:01 +0100677
678 // Now invoke QueryServiceState() and wait for the reply. The service will
679 // send 6 (1 + 5) IPCs which will be merged together in
680 // producer_ipc_client_impl.cc.
681 auto svc_state = helper.QueryServiceStateAndWait();
682
683 ASSERT_GE(svc_state.producers().size(), 1u);
684
685 std::map<std::string, std::string> ds_found;
686 for (const auto& ds : svc_state.data_sources()) {
687 if (!base::StartsWith(ds.ds_descriptor().name(), "big_ds_"))
688 continue;
689 ds_found[ds.ds_descriptor().name()] =
690 ds.ds_descriptor().track_event_descriptor_raw();
691 }
692 EXPECT_THAT(ds_found, ElementsAreArray(ds_expected));
693}
694
Primiano Tucci106605c2019-01-08 21:12:58 +0000695// Disable cmdline tests on sanitizets because they use fork() and that messes
696// up leak / races detections, which has been fixed only recently (see
697// https://github.com/google/sanitizers/issues/836 ).
698#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
699 defined(MEMORY_SANITIZER) || defined(LEAK_SANITIZER)
700#define NoSanitizers(X) DISABLED_##X
701#else
702#define NoSanitizers(X) X
703#endif
704
705TEST_F(PerfettoCmdlineTest, NoSanitizers(InvalidCases)) {
706 std::string cfg("duration_ms: 100");
707
Stephen Nusko87a12a82019-07-24 17:56:46 +0100708 auto invalid_arg = ExecPerfetto({"--invalid-arg"});
709 auto empty_config = ExecPerfetto({"-c", "-", "-o", "-"}, "");
Primiano Tucci106605c2019-01-08 21:12:58 +0000710
Stephen Nusko87a12a82019-07-24 17:56:46 +0100711 // Cannot make assertions on --dropbox because on standalone builds it fails
712 // prematurely due to lack of dropbox.
713 auto missing_dropbox =
714 ExecPerfetto({"-c", "-", "--txt", "-o", "-", "--dropbox=foo"}, cfg);
715 auto either_out_or_dropbox = ExecPerfetto({"-c", "-", "--txt"}, cfg);
716
717 // Disallow mixing simple and file config.
718 auto simple_and_file_1 =
719 ExecPerfetto({"-o", "-", "-c", "-", "-t", "2s"}, cfg);
720 auto simple_and_file_2 =
721 ExecPerfetto({"-o", "-", "-c", "-", "-b", "2m"}, cfg);
722 auto simple_and_file_3 =
723 ExecPerfetto({"-o", "-", "-c", "-", "-s", "2m"}, cfg);
724
725 // Invalid --attach / --detach cases.
726 auto invalid_stop =
727 ExecPerfetto({"-c", "-", "--txt", "-o", "-", "--stop"}, cfg);
728 auto attach_and_config_1 =
729 ExecPerfetto({"-c", "-", "--txt", "-o", "-", "--attach=foo"}, cfg);
730 auto attach_and_config_2 =
731 ExecPerfetto({"-t", "2s", "-o", "-", "--attach=foo"}, cfg);
732 auto attach_needs_argument = ExecPerfetto({"--attach"}, cfg);
733 auto detach_needs_argument =
734 ExecPerfetto({"-t", "2s", "-o", "-", "--detach"}, cfg);
735 auto detach_without_out_or_dropbox =
736 ExecPerfetto({"-t", "2s", "--detach=foo"}, cfg);
737
738 // Cannot trace and use --query.
739 auto trace_and_query_1 = ExecPerfetto({"-t", "2s", "--query"}, cfg);
740 auto trace_and_query_2 = ExecPerfetto({"-c", "-", "--query"}, cfg);
741
742 // Ensure all Exec:: calls have been saved to prevent deadlocks.
743 StartServiceIfRequiredNoNewExecsAfterThis();
744
745 EXPECT_EQ(1, invalid_arg.Run(&stderr_));
746
747 EXPECT_EQ(1, empty_config.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000748 EXPECT_THAT(stderr_, HasSubstr("TraceConfig is empty"));
749
750 // Cannot make assertions on --dropbox because on standalone builds it fails
751 // prematurely due to lack of dropbox.
Stephen Nusko87a12a82019-07-24 17:56:46 +0100752 EXPECT_EQ(1, missing_dropbox.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000753
Stephen Nusko87a12a82019-07-24 17:56:46 +0100754 EXPECT_EQ(1, either_out_or_dropbox.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000755 EXPECT_THAT(stderr_, HasSubstr("Either --out or --dropbox"));
756
757 // Disallow mixing simple and file config.
Stephen Nusko87a12a82019-07-24 17:56:46 +0100758 EXPECT_EQ(1, simple_and_file_1.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000759 EXPECT_THAT(stderr_, HasSubstr("Cannot specify both -c"));
760
Stephen Nusko87a12a82019-07-24 17:56:46 +0100761 EXPECT_EQ(1, simple_and_file_2.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000762 EXPECT_THAT(stderr_, HasSubstr("Cannot specify both -c"));
763
Stephen Nusko87a12a82019-07-24 17:56:46 +0100764 EXPECT_EQ(1, simple_and_file_3.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000765 EXPECT_THAT(stderr_, HasSubstr("Cannot specify both -c"));
766
767 // Invalid --attach / --detach cases.
Stephen Nusko87a12a82019-07-24 17:56:46 +0100768 EXPECT_EQ(1, invalid_stop.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000769 EXPECT_THAT(stderr_, HasSubstr("--stop is supported only in combination"));
770
Stephen Nusko87a12a82019-07-24 17:56:46 +0100771 EXPECT_EQ(1, attach_and_config_1.Run(&stderr_));
Primiano Tucci2854a0a2019-06-03 14:51:18 +0100772 EXPECT_THAT(stderr_, HasSubstr("Cannot specify a trace config"));
Primiano Tucci106605c2019-01-08 21:12:58 +0000773
Stephen Nusko87a12a82019-07-24 17:56:46 +0100774 EXPECT_EQ(1, attach_and_config_2.Run(&stderr_));
Primiano Tucci2854a0a2019-06-03 14:51:18 +0100775 EXPECT_THAT(stderr_, HasSubstr("Cannot specify a trace config"));
Primiano Tucci106605c2019-01-08 21:12:58 +0000776
Stephen Nusko87a12a82019-07-24 17:56:46 +0100777 EXPECT_EQ(1, attach_needs_argument.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000778 EXPECT_THAT(stderr_, ContainsRegex("option.*--attach.*requires an argument"));
779
Stephen Nusko87a12a82019-07-24 17:56:46 +0100780 EXPECT_EQ(1, detach_needs_argument.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000781 EXPECT_THAT(stderr_, ContainsRegex("option.*--detach.*requires an argument"));
782
Stephen Nusko87a12a82019-07-24 17:56:46 +0100783 EXPECT_EQ(1, detach_without_out_or_dropbox.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000784 EXPECT_THAT(stderr_, HasSubstr("--out or --dropbox is required"));
Primiano Tucci2854a0a2019-06-03 14:51:18 +0100785
Stephen Nusko87a12a82019-07-24 17:56:46 +0100786 // Cannot trace and use --query.
787 EXPECT_EQ(1, trace_and_query_1.Run(&stderr_));
Primiano Tucci2854a0a2019-06-03 14:51:18 +0100788 EXPECT_THAT(stderr_, HasSubstr("Cannot specify a trace config"));
789
Stephen Nusko87a12a82019-07-24 17:56:46 +0100790 EXPECT_EQ(1, trace_and_query_2.Run(&stderr_));
Primiano Tucci2854a0a2019-06-03 14:51:18 +0100791 EXPECT_THAT(stderr_, HasSubstr("Cannot specify a trace config"));
Primiano Tucci106605c2019-01-08 21:12:58 +0000792}
793
794TEST_F(PerfettoCmdlineTest, NoSanitizers(TxtConfig)) {
795 std::string cfg("duration_ms: 100");
Stephen Nusko87a12a82019-07-24 17:56:46 +0100796 auto perfetto = ExecPerfetto({"-c", "-", "--txt", "-o", "-"}, cfg);
797 StartServiceIfRequiredNoNewExecsAfterThis();
798 EXPECT_EQ(0, perfetto.Run(&stderr_)) << stderr_;
Primiano Tucci106605c2019-01-08 21:12:58 +0000799}
800
801TEST_F(PerfettoCmdlineTest, NoSanitizers(SimpleConfig)) {
Stephen Nusko87a12a82019-07-24 17:56:46 +0100802 auto perfetto = ExecPerfetto({"-o", "-", "-c", "-", "-t", "100ms"});
803 StartServiceIfRequiredNoNewExecsAfterThis();
804 EXPECT_EQ(0, perfetto.Run(&stderr_)) << stderr_;
Primiano Tucci106605c2019-01-08 21:12:58 +0000805}
806
807TEST_F(PerfettoCmdlineTest, NoSanitizers(DetachAndAttach)) {
Stephen Nusko87a12a82019-07-24 17:56:46 +0100808 auto attach_to_not_existing = ExecPerfetto({"--attach=not_existent"});
Primiano Tucci106605c2019-01-08 21:12:58 +0000809
810 std::string cfg("duration_ms: 10000; write_into_file: true");
Stephen Nusko87a12a82019-07-24 17:56:46 +0100811 auto detach_valid_stop =
812 ExecPerfetto({"-o", "-", "-c", "-", "--txt", "--detach=valid_stop"}, cfg);
813 auto stop_valid_stop = ExecPerfetto({"--attach=valid_stop", "--stop"});
814
815 StartServiceIfRequiredNoNewExecsAfterThis();
816
817 EXPECT_NE(0, attach_to_not_existing.Run(&stderr_));
818 EXPECT_THAT(stderr_, HasSubstr("Session re-attach failed"));
819
820 EXPECT_EQ(0, detach_valid_stop.Run(&stderr_)) << stderr_;
821 EXPECT_EQ(0, stop_valid_stop.Run(&stderr_));
Primiano Tucci106605c2019-01-08 21:12:58 +0000822}
823
Stephen Nuskoe8238112019-04-09 18:37:00 +0100824TEST_F(PerfettoCmdlineTest, NoSanitizers(StartTracingTrigger)) {
825 // See |message_count| and |message_size| in the TraceConfig above.
826 constexpr size_t kMessageCount = 11;
827 constexpr size_t kMessageSize = 32;
Primiano Tuccife502c42019-12-11 01:00:27 +0000828 protos::gen::TraceConfig trace_config;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100829 trace_config.add_buffers()->set_size_kb(1024);
830 auto* ds_config = trace_config.add_data_sources()->mutable_config();
831 ds_config->set_name("android.perfetto.FakeProducer");
832 ds_config->mutable_for_testing()->set_message_count(kMessageCount);
833 ds_config->mutable_for_testing()->set_message_size(kMessageSize);
834 auto* trigger_cfg = trace_config.mutable_trigger_config();
835 trigger_cfg->set_trigger_mode(
Primiano Tuccife502c42019-12-11 01:00:27 +0000836 protos::gen::TraceConfig::TriggerConfig::START_TRACING);
Stephen Nuskoe8238112019-04-09 18:37:00 +0100837 trigger_cfg->set_trigger_timeout_ms(15000);
838 auto* trigger = trigger_cfg->add_triggers();
839 trigger->set_name("trigger_name");
840 // |stop_delay_ms| must be long enough that we can write the packets in
841 // before the trace finishes. This has to be long enough for the slowest
842 // emulator. But as short as possible to prevent the test running a long
843 // time.
844 trigger->set_stop_delay_ms(500);
845
Stephen Nusko87a12a82019-07-24 17:56:46 +0100846 // We have to construct all the processes we want to fork before we start the
847 // service with |StartServiceIfRequired()|. this is because it is unsafe
848 // (could deadlock) to fork after we've spawned some threads which might
849 // printf (and thus hold locks).
Stephen Nusko49c5a3c2019-04-17 13:36:09 +0100850 const std::string path = RandomTraceFileName();
Stephen Nusko87a12a82019-07-24 17:56:46 +0100851 auto perfetto_proc = ExecPerfetto(
852 {
853 "-o",
854 path,
855 "-c",
856 "-",
857 },
858 trace_config.SerializeAsString());
859
860 auto trigger_proc = ExecTrigger({"trigger_name"});
861
862 // Start the service and connect a simple fake producer.
863 StartServiceIfRequiredNoNewExecsAfterThis();
864
865 auto* fake_producer = ConnectFakeProducer();
866 EXPECT_TRUE(fake_producer);
867
868 // Start a background thread that will deliver the config now that we've
869 // started the service. See |perfetto_proc| above for the args passed.
870 std::thread background_trace([&perfetto_proc]() {
871 std::string stderr_str;
872 EXPECT_EQ(0, perfetto_proc.Run(&stderr_str)) << stderr_str;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100873 });
874
Stephen Nusko87a12a82019-07-24 17:56:46 +0100875 WaitForProducerSetup();
876 EXPECT_EQ(0, trigger_proc.Run(&stderr_));
Stephen Nuskoe8238112019-04-09 18:37:00 +0100877
878 // Wait for the producer to start, and then write out 11 packets.
Stephen Nusko87a12a82019-07-24 17:56:46 +0100879 WaitForProducerEnabled();
880 auto on_data_written = task_runner_.CreateCheckpoint("data_written");
881 fake_producer->ProduceEventBatch(WrapTask(on_data_written));
882 task_runner_.RunUntilCheckpoint("data_written");
Stephen Nuskoe8238112019-04-09 18:37:00 +0100883 background_trace.join();
884
885 std::string trace_str;
886 base::ReadFile(path, &trace_str);
Primiano Tuccife502c42019-12-11 01:00:27 +0000887 protos::gen::Trace trace;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100888 ASSERT_TRUE(trace.ParseFromString(trace_str));
Primiano Tucci79e4dcb2020-04-08 09:51:02 +0100889 EXPECT_EQ(static_cast<int>(kBuiltinPackets + kMessageCount),
Primiano Tucci919ca1e2019-08-21 20:26:58 +0200890 trace.packet_size());
Stephen Nuskoe8238112019-04-09 18:37:00 +0100891 for (const auto& packet : trace.packet()) {
Primiano Tuccife502c42019-12-11 01:00:27 +0000892 if (packet.has_trace_config()) {
Stephen Nuskoe8238112019-04-09 18:37:00 +0100893 // Ensure the trace config properly includes the trigger mode we set.
Primiano Tuccife502c42019-12-11 01:00:27 +0000894 auto kStartTrig = protos::gen::TraceConfig::TriggerConfig::START_TRACING;
895 EXPECT_EQ(kStartTrig,
Stephen Nuskoe8238112019-04-09 18:37:00 +0100896 packet.trace_config().trigger_config().trigger_mode());
Primiano Tuccife502c42019-12-11 01:00:27 +0000897 } else if (packet.has_trigger()) {
Stephen Nuskoe8238112019-04-09 18:37:00 +0100898 // validate that the triggers are properly added to the trace.
899 EXPECT_EQ("trigger_name", packet.trigger().trigger_name());
Primiano Tuccife502c42019-12-11 01:00:27 +0000900 } else if (packet.has_for_testing()) {
Stephen Nuskoe8238112019-04-09 18:37:00 +0100901 // Make sure that the data size is correctly set based on what we
902 // requested.
903 EXPECT_EQ(kMessageSize, packet.for_testing().str().size());
904 }
905 }
906}
907
908TEST_F(PerfettoCmdlineTest, NoSanitizers(StopTracingTrigger)) {
909 // See |message_count| and |message_size| in the TraceConfig above.
910 constexpr size_t kMessageCount = 11;
911 constexpr size_t kMessageSize = 32;
Primiano Tuccife502c42019-12-11 01:00:27 +0000912 protos::gen::TraceConfig trace_config;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100913 trace_config.add_buffers()->set_size_kb(1024);
914 auto* ds_config = trace_config.add_data_sources()->mutable_config();
915 ds_config->set_name("android.perfetto.FakeProducer");
916 ds_config->mutable_for_testing()->set_message_count(kMessageCount);
917 ds_config->mutable_for_testing()->set_message_size(kMessageSize);
918 auto* trigger_cfg = trace_config.mutable_trigger_config();
919 trigger_cfg->set_trigger_mode(
Primiano Tuccife502c42019-12-11 01:00:27 +0000920 protos::gen::TraceConfig::TriggerConfig::STOP_TRACING);
Stephen Nuskoe8238112019-04-09 18:37:00 +0100921 trigger_cfg->set_trigger_timeout_ms(15000);
922 auto* trigger = trigger_cfg->add_triggers();
923 trigger->set_name("trigger_name");
924 // |stop_delay_ms| must be long enough that we can write the packets in
925 // before the trace finishes. This has to be long enough for the slowest
926 // emulator. But as short as possible to prevent the test running a long
927 // time.
928 trigger->set_stop_delay_ms(500);
929 trigger = trigger_cfg->add_triggers();
930 trigger->set_name("trigger_name_3");
931 trigger->set_stop_delay_ms(60000);
932
Stephen Nusko87a12a82019-07-24 17:56:46 +0100933 // We have to construct all the processes we want to fork before we start the
934 // service with |StartServiceIfRequired()|. this is because it is unsafe
935 // (could deadlock) to fork after we've spawned some threads which might
936 // printf (and thus hold locks).
937 const std::string path = RandomTraceFileName();
938 auto perfetto_proc = ExecPerfetto(
939 {
940 "-o",
941 path,
942 "-c",
943 "-",
944 },
945 trace_config.SerializeAsString());
Stephen Nuskoe8238112019-04-09 18:37:00 +0100946
Stephen Nusko87a12a82019-07-24 17:56:46 +0100947 auto trigger_proc =
948 ExecTrigger({"trigger_name_2", "trigger_name", "trigger_name_3"});
949
950 // Start the service and connect a simple fake producer.
951 StartServiceIfRequiredNoNewExecsAfterThis();
952 auto* fake_producer = ConnectFakeProducer();
Stephen Nuskoe8238112019-04-09 18:37:00 +0100953 EXPECT_TRUE(fake_producer);
954
Stephen Nusko87a12a82019-07-24 17:56:46 +0100955 // Start a background thread that will deliver the config now that we've
956 // started the service. See |perfetto_proc| above for the args passed.
957 std::thread background_trace([&perfetto_proc]() {
958 std::string stderr_str;
959 EXPECT_EQ(0, perfetto_proc.Run(&stderr_str)) << stderr_str;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100960 });
961
Stephen Nusko87a12a82019-07-24 17:56:46 +0100962 WaitForProducerEnabled();
Stephen Nuskoe8238112019-04-09 18:37:00 +0100963 // Wait for the producer to start, and then write out 11 packets, before the
964 // trace actually starts (the trigger is seen).
Stephen Nusko87a12a82019-07-24 17:56:46 +0100965 auto on_data_written = task_runner_.CreateCheckpoint("data_written_1");
966 fake_producer->ProduceEventBatch(WrapTask(on_data_written));
967 task_runner_.RunUntilCheckpoint("data_written_1");
Stephen Nuskoe8238112019-04-09 18:37:00 +0100968
Stephen Nusko87a12a82019-07-24 17:56:46 +0100969 EXPECT_EQ(0, trigger_proc.Run(&stderr_)) << "stderr: " << stderr_;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100970
971 background_trace.join();
972
973 std::string trace_str;
974 base::ReadFile(path, &trace_str);
Primiano Tuccife502c42019-12-11 01:00:27 +0000975 protos::gen::Trace trace;
Stephen Nuskoe8238112019-04-09 18:37:00 +0100976 ASSERT_TRUE(trace.ParseFromString(trace_str));
Primiano Tucci79e4dcb2020-04-08 09:51:02 +0100977 EXPECT_EQ(static_cast<int>(kBuiltinPackets + 1 + kMessageCount),
Primiano Tucci919ca1e2019-08-21 20:26:58 +0200978 trace.packet_size());
Stephen Nuskoe8238112019-04-09 18:37:00 +0100979 bool seen_first_trigger = false;
980 for (const auto& packet : trace.packet()) {
Primiano Tuccife502c42019-12-11 01:00:27 +0000981 if (packet.has_trace_config()) {
Stephen Nuskoe8238112019-04-09 18:37:00 +0100982 // Ensure the trace config properly includes the trigger mode we set.
Primiano Tuccife502c42019-12-11 01:00:27 +0000983 auto kStopTrig = protos::gen::TraceConfig::TriggerConfig::STOP_TRACING;
984 EXPECT_EQ(kStopTrig,
Stephen Nuskoe8238112019-04-09 18:37:00 +0100985 packet.trace_config().trigger_config().trigger_mode());
Primiano Tuccife502c42019-12-11 01:00:27 +0000986 } else if (packet.has_trigger()) {
Stephen Nuskoe8238112019-04-09 18:37:00 +0100987 // validate that the triggers are properly added to the trace.
988 if (!seen_first_trigger) {
989 EXPECT_EQ("trigger_name", packet.trigger().trigger_name());
990 seen_first_trigger = true;
991 } else {
992 EXPECT_EQ("trigger_name_3", packet.trigger().trigger_name());
993 }
Primiano Tuccife502c42019-12-11 01:00:27 +0000994 } else if (packet.has_for_testing()) {
Stephen Nuskoe8238112019-04-09 18:37:00 +0100995 // Make sure that the data size is correctly set based on what we
996 // requested.
997 EXPECT_EQ(kMessageSize, packet.for_testing().str().size());
998 }
999 }
1000}
1001
1002// Dropbox on the commandline client only works on android builds. So disable
1003// this test on all other builds.
1004#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
1005TEST_F(PerfettoCmdlineTest, NoSanitizers(NoDataNoFileWithoutTrigger)) {
1006#else
1007TEST_F(PerfettoCmdlineTest, DISABLED_NoDataNoFileWithoutTrigger) {
1008#endif
1009 // See |message_count| and |message_size| in the TraceConfig above.
1010 constexpr size_t kMessageCount = 11;
1011 constexpr size_t kMessageSize = 32;
Primiano Tuccife502c42019-12-11 01:00:27 +00001012 protos::gen::TraceConfig trace_config;
Stephen Nuskoe8238112019-04-09 18:37:00 +01001013 trace_config.add_buffers()->set_size_kb(1024);
Hector Dearmanb5ad80b2019-05-02 12:53:30 +01001014 trace_config.set_allow_user_build_tracing(true);
Stephen Nuskoe8238112019-04-09 18:37:00 +01001015 auto* ds_config = trace_config.add_data_sources()->mutable_config();
1016 ds_config->set_name("android.perfetto.FakeProducer");
1017 ds_config->mutable_for_testing()->set_message_count(kMessageCount);
1018 ds_config->mutable_for_testing()->set_message_size(kMessageSize);
1019 auto* trigger_cfg = trace_config.mutable_trigger_config();
1020 trigger_cfg->set_trigger_mode(
Primiano Tuccife502c42019-12-11 01:00:27 +00001021 protos::gen::TraceConfig::TriggerConfig::STOP_TRACING);
Stephen Nuskoe8238112019-04-09 18:37:00 +01001022 trigger_cfg->set_trigger_timeout_ms(1000);
1023 auto* trigger = trigger_cfg->add_triggers();
1024 trigger->set_name("trigger_name");
1025 // |stop_delay_ms| must be long enough that we can write the packets in
1026 // before the trace finishes. This has to be long enough for the slowest
1027 // emulator. But as short as possible to prevent the test running a long
1028 // time.
1029 trigger->set_stop_delay_ms(500);
1030 trigger = trigger_cfg->add_triggers();
1031
Stephen Nusko87a12a82019-07-24 17:56:46 +01001032 // We have to construct all the processes we want to fork before we start the
1033 // service with |StartServiceIfRequired()|. this is because it is unsafe
1034 // (could deadlock) to fork after we've spawned some threads which might
1035 // printf (and thus hold locks).
1036 const std::string path = RandomTraceFileName();
1037 auto perfetto_proc = ExecPerfetto(
1038 {
1039 "--dropbox",
1040 "TAG",
1041 "--no-guardrails",
1042 "-c",
1043 "-",
1044 },
1045 trace_config.SerializeAsString());
1046
1047 StartServiceIfRequiredNoNewExecsAfterThis();
1048 auto* fake_producer = ConnectFakeProducer();
Stephen Nuskoe8238112019-04-09 18:37:00 +01001049 EXPECT_TRUE(fake_producer);
1050
Stephen Nusko87a12a82019-07-24 17:56:46 +01001051 std::string stderr_str;
1052 std::thread background_trace([&perfetto_proc, &stderr_str]() {
1053 EXPECT_EQ(0, perfetto_proc.Run(&stderr_str));
Stephen Nuskoe8238112019-04-09 18:37:00 +01001054 });
1055 background_trace.join();
1056
Stephen Nusko87a12a82019-07-24 17:56:46 +01001057 EXPECT_THAT(stderr_str,
Ryan Savitski53ca60b2019-06-03 13:04:40 +01001058 ::testing::HasSubstr("Skipping write to dropbox. Empty trace."));
Stephen Nuskoe8238112019-04-09 18:37:00 +01001059}
1060
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001061TEST_F(PerfettoCmdlineTest, NoSanitizers(StopTracingTriggerFromConfig)) {
1062 // See |message_count| and |message_size| in the TraceConfig above.
1063 constexpr size_t kMessageCount = 11;
1064 constexpr size_t kMessageSize = 32;
Primiano Tuccife502c42019-12-11 01:00:27 +00001065 protos::gen::TraceConfig trace_config;
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001066 trace_config.add_buffers()->set_size_kb(1024);
1067 auto* ds_config = trace_config.add_data_sources()->mutable_config();
1068 ds_config->set_name("android.perfetto.FakeProducer");
1069 ds_config->mutable_for_testing()->set_message_count(kMessageCount);
1070 ds_config->mutable_for_testing()->set_message_size(kMessageSize);
1071 auto* trigger_cfg = trace_config.mutable_trigger_config();
1072 trigger_cfg->set_trigger_mode(
Primiano Tuccife502c42019-12-11 01:00:27 +00001073 protos::gen::TraceConfig::TriggerConfig::STOP_TRACING);
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001074 trigger_cfg->set_trigger_timeout_ms(15000);
1075 auto* trigger = trigger_cfg->add_triggers();
1076 trigger->set_name("trigger_name");
1077 // |stop_delay_ms| must be long enough that we can write the packets in
1078 // before the trace finishes. This has to be long enough for the slowest
1079 // emulator. But as short as possible to prevent the test running a long
1080 // time.
1081 trigger->set_stop_delay_ms(500);
1082 trigger = trigger_cfg->add_triggers();
1083 trigger->set_name("trigger_name_3");
1084 trigger->set_stop_delay_ms(60000);
1085
Stephen Nusko87a12a82019-07-24 17:56:46 +01001086 // We have to construct all the processes we want to fork before we start the
1087 // service with |StartServiceIfRequired()|. this is because it is unsafe
1088 // (could deadlock) to fork after we've spawned some threads which might
1089 // printf (and thus hold locks).
Stephen Nusko49c5a3c2019-04-17 13:36:09 +01001090 const std::string path = RandomTraceFileName();
Stephen Nusko87a12a82019-07-24 17:56:46 +01001091 auto perfetto_proc = ExecPerfetto(
1092 {
1093 "-o",
1094 path,
1095 "-c",
1096 "-",
1097 },
1098 trace_config.SerializeAsString());
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001099
1100 std::string triggers = R"(
1101 activate_triggers: "trigger_name_2"
1102 activate_triggers: "trigger_name"
1103 activate_triggers: "trigger_name_3"
1104 )";
Stephen Nusko87a12a82019-07-24 17:56:46 +01001105 auto perfetto_proc_2 = ExecPerfetto(
1106 {
1107 "-o",
1108 path,
1109 "-c",
1110 "-",
1111 "--txt",
1112 },
1113 triggers);
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001114
Stephen Nusko87a12a82019-07-24 17:56:46 +01001115 // Start the service and connect a simple fake producer.
1116 StartServiceIfRequiredNoNewExecsAfterThis();
1117 auto* fake_producer = ConnectFakeProducer();
1118 EXPECT_TRUE(fake_producer);
1119
1120 std::thread background_trace([&perfetto_proc]() {
1121 std::string stderr_str;
1122 EXPECT_EQ(0, perfetto_proc.Run(&stderr_str)) << stderr_str;
1123 });
1124
1125 WaitForProducerEnabled();
1126 // Wait for the producer to start, and then write out 11 packets, before the
1127 // trace actually starts (the trigger is seen).
1128 auto on_data_written = task_runner_.CreateCheckpoint("data_written_1");
1129 fake_producer->ProduceEventBatch(WrapTask(on_data_written));
1130 task_runner_.RunUntilCheckpoint("data_written_1");
1131
1132 EXPECT_EQ(0, perfetto_proc_2.Run(&stderr_)) << "stderr: " << stderr_;
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001133
1134 background_trace.join();
1135
1136 std::string trace_str;
Stephen Nusko49c5a3c2019-04-17 13:36:09 +01001137 base::ReadFile(path, &trace_str);
Primiano Tuccife502c42019-12-11 01:00:27 +00001138 protos::gen::Trace trace;
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001139 ASSERT_TRUE(trace.ParseFromString(trace_str));
Primiano Tucci919ca1e2019-08-21 20:26:58 +02001140 EXPECT_LT(static_cast<int>(kMessageCount), trace.packet_size());
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001141 bool seen_first_trigger = false;
1142 for (const auto& packet : trace.packet()) {
Primiano Tuccife502c42019-12-11 01:00:27 +00001143 if (packet.has_trace_config()) {
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001144 // Ensure the trace config properly includes the trigger mode we set.
Primiano Tuccife502c42019-12-11 01:00:27 +00001145 auto kStopTrig = protos::gen::TraceConfig::TriggerConfig::STOP_TRACING;
1146 EXPECT_EQ(kStopTrig,
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001147 packet.trace_config().trigger_config().trigger_mode());
Primiano Tuccife502c42019-12-11 01:00:27 +00001148 } else if (packet.has_trigger()) {
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001149 // validate that the triggers are properly added to the trace.
1150 if (!seen_first_trigger) {
1151 EXPECT_EQ("trigger_name", packet.trigger().trigger_name());
1152 seen_first_trigger = true;
1153 } else {
1154 EXPECT_EQ("trigger_name_3", packet.trigger().trigger_name());
1155 }
Primiano Tuccife502c42019-12-11 01:00:27 +00001156 } else if (packet.has_for_testing()) {
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001157 // Make sure that the data size is correctly set based on what we
1158 // requested.
1159 EXPECT_EQ(kMessageSize, packet.for_testing().str().size());
1160 }
1161 }
1162}
1163
1164TEST_F(PerfettoCmdlineTest, NoSanitizers(TriggerFromConfigStopsFileOpening)) {
1165 // See |message_count| and |message_size| in the TraceConfig above.
1166 constexpr size_t kMessageCount = 11;
1167 constexpr size_t kMessageSize = 32;
Primiano Tuccife502c42019-12-11 01:00:27 +00001168 protos::gen::TraceConfig trace_config;
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001169 trace_config.add_buffers()->set_size_kb(1024);
1170 auto* ds_config = trace_config.add_data_sources()->mutable_config();
1171 ds_config->set_name("android.perfetto.FakeProducer");
1172 ds_config->mutable_for_testing()->set_message_count(kMessageCount);
1173 ds_config->mutable_for_testing()->set_message_size(kMessageSize);
1174 auto* trigger_cfg = trace_config.mutable_trigger_config();
1175 trigger_cfg->set_trigger_mode(
Primiano Tuccife502c42019-12-11 01:00:27 +00001176 protos::gen::TraceConfig::TriggerConfig::STOP_TRACING);
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001177 trigger_cfg->set_trigger_timeout_ms(15000);
1178 auto* trigger = trigger_cfg->add_triggers();
1179 trigger->set_name("trigger_name");
1180 // |stop_delay_ms| must be long enough that we can write the packets in
1181 // before the trace finishes. This has to be long enough for the slowest
1182 // emulator. But as short as possible to prevent the test running a long
1183 // time.
1184 trigger->set_stop_delay_ms(500);
1185 trigger = trigger_cfg->add_triggers();
1186 trigger->set_name("trigger_name_3");
1187 trigger->set_stop_delay_ms(60000);
1188
Stephen Nusko87a12a82019-07-24 17:56:46 +01001189 // We have to construct all the processes we want to fork before we start the
1190 // service with |StartServiceIfRequired()|. this is because it is unsafe
1191 // (could deadlock) to fork after we've spawned some threads which might
1192 // printf (and thus hold locks).
Stephen Nusko49c5a3c2019-04-17 13:36:09 +01001193 const std::string path = RandomTraceFileName();
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001194 std::string triggers = R"(
1195 activate_triggers: "trigger_name_2"
1196 activate_triggers: "trigger_name"
1197 activate_triggers: "trigger_name_3"
1198 )";
Stephen Nusko87a12a82019-07-24 17:56:46 +01001199 auto perfetto_proc = ExecPerfetto(
1200 {
1201 "-o",
1202 path,
1203 "-c",
1204 "-",
1205 "--txt",
1206 },
1207 triggers);
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001208
Stephen Nusko87a12a82019-07-24 17:56:46 +01001209 // Start the service and connect a simple fake producer.
1210 StartServiceIfRequiredNoNewExecsAfterThis();
1211 auto* fake_producer = ConnectFakeProducer();
1212 EXPECT_TRUE(fake_producer);
1213
1214 std::string trace_str;
1215 EXPECT_FALSE(base::ReadFile(path, &trace_str));
1216
1217 EXPECT_EQ(0, perfetto_proc.Run(&stderr_)) << "stderr: " << stderr_;
Stephen Nusko9fa59cb2019-04-15 04:19:16 +01001218
1219 EXPECT_FALSE(base::ReadFile(path, &trace_str));
1220}
1221
Primiano Tucci2854a0a2019-06-03 14:51:18 +01001222TEST_F(PerfettoCmdlineTest, NoSanitizers(Query)) {
Stephen Nusko87a12a82019-07-24 17:56:46 +01001223 auto query = ExecPerfetto({"--query"});
1224 auto query_raw = ExecPerfetto({"--query-raw"});
1225 StartServiceIfRequiredNoNewExecsAfterThis();
1226 EXPECT_EQ(0, query.Run(&stderr_)) << stderr_;
1227 EXPECT_EQ(0, query_raw.Run(&stderr_)) << stderr_;
Primiano Tucci2854a0a2019-06-03 14:51:18 +01001228}
1229
Lalit Maganti79f2d7b2018-01-23 18:27:33 +00001230} // namespace perfetto